File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.388: download - view: text, annotated - select for diffs
Thu Oct 7 15:51:15 2021 UTC (2 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6914
  Domain configuration for WAF/Proxy includes Y/N option for use of alias in
  redirection to /adm/sso for server(s) supporting Shibboleth Single Sign On.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.388 2021/10/07 15:51:15 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,%saml,%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:                     if (ref($settings->{'saml'}) eq 'HASH') {
 7547:                         $saml{$dom} = $settings->{'saml'};
 7548:                     }
 7549:                 }
 7550:             }
 7551:         }
 7552:     }
 7553:     if ($setdom) {
 7554:         %{$values{$dom}} = ();
 7555:         if (ref($settings) eq 'HASH') {
 7556:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7557:                 $values{$dom}{$item} = $settings->{$item};
 7558:             }
 7559:         }
 7560:     }
 7561:     if (keys(%othercontrol)) {
 7562:         %otherdoms = reverse(%othercontrol);
 7563:         foreach my $domain (keys(%otherdoms)) {
 7564:             %{$values{$domain}} = ();
 7565:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 7566:             if (ref($config{'wafproxy'}) eq 'HASH') {
 7567:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 7568:                 if (exists($config{'wafproxy'}{'saml'})) { 
 7569:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 7570:                 }
 7571:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7572:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 7573:                 }
 7574:             }
 7575:         }
 7576:     }
 7577:     if ($position eq 'top') {
 7578:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7579:         my %aliasinfo;
 7580:         foreach my $server (sort(keys(%servers))) {
 7581:             $itemcount ++;
 7582:             my $dom_in_effect;
 7583:             my $aliasrows = '<tr>'.
 7584:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7585:                             &mt('Hostname').':&nbsp;'.
 7586:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 7587:             if ($othercontrol{$server}) {
 7588:                 $dom_in_effect = $othercontrol{$server};
 7589:                 my ($current,$forsaml);
 7590:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 7591:                     $current = $aliases{$dom_in_effect}{$server};
 7592:                 }
 7593:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 7594:                     if ($saml{$dom_in_effect}{$server}) {
 7595:                         $forsaml = 1;
 7596:                     }
 7597:                 }
 7598:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7599:                               &mt('Alias').':&nbsp';
 7600:                 if ($current) {
 7601:                     $aliasrows .= $current;
 7602:                     if ($forsaml) {
 7603:                          $aliasrows .= '&nbsp;('.&mt('also for Shibboleth').')';
 7604:                     }
 7605:                 } else {
 7606:                     $aliasrows .= &mt('None');
 7607:                 }
 7608:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 7609:                               &mt('controlled by domain: [_1]',
 7610:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 7611:             } else {
 7612:                 $dom_in_effect = $dom;
 7613:                 my ($current,$samlon,$samloff);
 7614:                 $samloff = ' checked="checked"';
 7615:                 if (ref($aliases{$dom}) eq 'HASH') {
 7616:                     if ($aliases{$dom}{$server}) {
 7617:                         $current = $aliases{$dom}{$server};
 7618:                     }
 7619:                 }
 7620:                 if (ref($saml{$dom}) eq 'HASH') {
 7621:                     if ($saml{$dom}{$server}) {
 7622:                         $samlon = $samloff;
 7623:                         undef($samloff);
 7624:                     }
 7625:                 }
 7626:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7627:                               &mt('Alias').':&nbsp;'.
 7628:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 7629:                               'value="'.$current.'" size="30" />'.
 7630:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 7631:                               &mt('Alias used for Shibboleth').':&nbsp;<label>'.
 7632:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 7633:                               &mt('No').'</label>&nbsp;<label>'. 
 7634:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 7635:                               &mt('Yes').'</label></span>'.
 7636:                               '</td>'; 
 7637:             }
 7638:             $aliasrows .= '</tr>';
 7639:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 7640:         }
 7641:         if ($aliasinfo{$dom}) {
 7642:             my ($onclick,$wafon,$wafoff,$showtable);
 7643:             $onclick = ' onclick="javascript:toggleWAF();"';
 7644:             $wafoff = ' checked="checked"';
 7645:             $showtable = ' style="display:none";';
 7646:             if ($showdom) {
 7647:                 $wafon = $wafoff;
 7648:                 $wafoff = '';
 7649:                 $showtable = ' style="display:inline;"';
 7650:             }
 7651:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7652:             $datatable = '<tr'.$css_class.'>'.
 7653:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 7654:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 7655:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 7656:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 7657:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 7658:                          &mt('No').'</label></span></td>'.
 7659:                          '<td class="LC_left_item">'.
 7660:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 7661:                          '</table></td></tr>';
 7662:             $itemcount++;
 7663:         }
 7664:         if (keys(%otherdoms)) {
 7665:             foreach my $key (sort(keys(%otherdoms))) {
 7666:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7667:                 $datatable .= '<tr'.$css_class.'>'.
 7668:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 7669:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 7670:                               '</table></td></tr>';
 7671:                 $itemcount++;
 7672:             }
 7673:         }
 7674:     } else {
 7675:         my %ip_methods = &remoteip_methods();
 7676:         if ($setdom) {
 7677:             $itemcount ++;
 7678:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7679:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 7680:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 7681:             $wafstyle = ' style="display:none;"';
 7682:             $nowafstyle = ' style="display:table-row;"';
 7683:             $currwafdisplay = ' style="display: none"';
 7684:             $wafrangestyle = ' style="display: none"';
 7685:             $curr_remotip = 'n';
 7686:             $ssltossl = ' checked="checked"';
 7687:             if ($showdom) {
 7688:                 $wafstyle = ' style="display:table-row;"';
 7689:                 $nowafstyle =  ' style="display:none;"';
 7690:                 if (keys(%{$values{$dom}})) {
 7691:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 7692:                         $curr_remotip = $values{$dom}{remoteip};
 7693:                     }
 7694:                     if ($curr_remotip eq 'h') {
 7695:                         $currwafdisplay = ' style="display:table-row"';
 7696:                         $wafrangestyle = ' style="display:inline-block;"';
 7697:                     }
 7698:                     if ($values{$dom}{'sslopt'}) {
 7699:                         $alltossl = ' checked="checked"';
 7700:                         $ssltossl = '';
 7701:                     }
 7702:                 }
 7703:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 7704:                     $vpndircheck = ' checked="checked"';
 7705:                     $currwafvpn = ' style="display:table-row;"';
 7706:                     $wafrangestyle = ' style="display:inline-block;"';
 7707:                 } else {
 7708:                     $vpnaliascheck = ' checked="checked"';
 7709:                     $currwafvpn = ' style="display:none;"';
 7710:                 }
 7711:             }
 7712:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7713:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 7714:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 7715:                           '</tr>'.
 7716:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7717:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 7718:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 7719:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'</div></td>'.
 7720:                           '<td class="LC_left_item"><table>'.
 7721:                           '<tr>'.
 7722:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 7723:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 7724:             foreach my $option ('m','h','n') {
 7725:                 my $sel;
 7726:                 if ($option eq $curr_remotip) {
 7727:                    $sel = ' selected="selected"';
 7728:                 }
 7729:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 7730:                               $ip_methods{$option}.'</option>';
 7731:             }
 7732:             $datatable .= '</select></td></tr>'."\n".
 7733:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 7734:                           $lt{'ipheader'}.':&nbsp;'.
 7735:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 7736:                           'name="wafproxy_ipheader" />'.
 7737:                           '</td></tr>'."\n".
 7738:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 7739:                           $lt{'trusted'}.':<br />'.
 7740:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 7741:                           $values{$dom}{'trusted'}.'</textarea>'.
 7742:                           '</td></tr>'."\n".
 7743:                           '<tr><td><hr /></td></tr>'."\n".
 7744:                           '<tr>'.
 7745:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 7746:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 7747:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 7748:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 7749:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 7750:             foreach my $item ('vpnint','vpnext') {
 7751:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 7752:                               '<td valign="top">'.$lt{$item}.':<br />'.
 7753:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 7754:                               $values{$dom}{$item}.'</textarea>'.
 7755:                               '</td></tr>'."\n";
 7756:             }
 7757:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 7758:                           '<tr>'.
 7759:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 7760:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 7761:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 7762:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 7763:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 7764:                           '</table></td></tr>';
 7765:         }
 7766:         if (keys(%otherdoms)) {
 7767:             foreach my $domain (sort(keys(%otherdoms))) {
 7768:                 $itemcount ++;
 7769:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7770:                 $datatable .= '<tr'.$css_class.'>'.
 7771:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 7772:                               '<td class="LC_left_item"><table>';
 7773:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 7774:                     my $showval = &mt('None');
 7775:                     if ($item eq 'ssl') {
 7776:                         $showval = $lt{'ssltossl'};
 7777:                     }
 7778:                     if ($values{$domain}{$item}) {
 7779:                         $showval = $values{$domain}{$item};
 7780:                         if ($item eq 'ssl') {
 7781:                             $showval = $lt{'alltossl'};
 7782:                         } elsif ($item eq 'remoteip') {
 7783:                             $showval = $ip_methods{$values{$domain}{$item}};
 7784:                         }
 7785:                     }
 7786:                     $datatable .= '<tr>'.
 7787:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 7788:                 }
 7789:                 $datatable .= '</table></td></tr>';
 7790:             }
 7791:         }
 7792:     }
 7793:     $$rowtotal += $itemcount;
 7794:     return $datatable;
 7795: }
 7796: 
 7797: sub wafproxy_titles {
 7798:     return &Apache::lonlocal::texthash(
 7799:                remoteip   => "Method for determining user's IP",
 7800:                ipheader   => 'Request header containing remote IP',
 7801:                trusted    => 'Trusted IP range(s)',
 7802:                vpnaccess  => 'Access from institutional VPN',
 7803:                vpndirect  => 'via regular hostname (no WAF)',
 7804:                vpnaliased => 'via aliased hostname (WAF)',
 7805:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 7806:                vpnext     => 'IP Range(s) for backend WAF connections',
 7807:                sslopt     => 'Forwarding http/https',
 7808:                alltossl   => 'WAF forwards both http and https requests to https',
 7809:                ssltossl   => 'WAF forwards http requests to http and https to https',
 7810:            );
 7811: }
 7812: 
 7813: sub remoteip_methods {
 7814:     return &Apache::lonlocal::texthash(
 7815:               m => 'Use Apache mod_remoteip',
 7816:               h => 'Use headers parsed by LON-CAPA',
 7817:               n => 'Not in use',
 7818:            );
 7819: }
 7820: 
 7821: sub print_usersessions {
 7822:     my ($position,$dom,$settings,$rowtotal) = @_;
 7823:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 7824:     my (%by_ip,%by_location,@intdoms,@instdoms);
 7825:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7826: 
 7827:     my @alldoms = &Apache::lonnet::all_domains();
 7828:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7829:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7830:     my %altids = &id_for_thisdom(%servers);
 7831:     if ($position eq 'top') {
 7832:         if (keys(%serverhomes) > 1) {
 7833:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 7834:             my ($curroffloadnow,$curroffloadoth);
 7835:             if (ref($settings) eq 'HASH') {
 7836:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 7837:                     $curroffloadnow = $settings->{'offloadnow'};
 7838:                 }
 7839:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 7840:                     $curroffloadoth = $settings->{'offloadoth'};
 7841:                 }
 7842:             }
 7843:             my $other_insts = scalar(keys(%by_location));
 7844:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 7845:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 7846:         } else {
 7847:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 7848:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 7849:                           '</td></tr>';
 7850:         }
 7851:     } else {
 7852:         my %titles = &usersession_titles();
 7853:         my ($prefix,@types);
 7854:         if ($position eq 'bottom') {
 7855:             $prefix = 'remote';
 7856:             @types = ('version','excludedomain','includedomain');
 7857:         } else {
 7858:             $prefix = 'hosted';
 7859:             @types = ('excludedomain','includedomain');
 7860:         }
 7861:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7862:     }
 7863:     $$rowtotal += $itemcount;
 7864:     return $datatable;
 7865: }
 7866: 
 7867: sub rules_by_location {
 7868:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 7869:     my ($datatable,$itemcount,$css_class);
 7870:     if (keys(%{$by_location}) == 0) {
 7871:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7872:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 7873:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 7874:                      '</td></tr>';
 7875:         $itemcount = 1;
 7876:     } else {
 7877:         $itemcount = 0;
 7878:         my $numinrow = 5;
 7879:         my (%current,%checkedon,%checkedoff);
 7880:         my @locations = sort(keys(%{$by_location}));
 7881:         foreach my $type (@{$types}) {
 7882:             $checkedon{$type} = '';
 7883:             $checkedoff{$type} = ' checked="checked"';
 7884:         }
 7885:         if (ref($settings) eq 'HASH') {
 7886:             if (ref($settings->{$prefix}) eq 'HASH') {
 7887:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 7888:                     $current{$key} = $settings->{$prefix}{$key};
 7889:                     if ($key eq 'version') {
 7890:                         if ($current{$key} ne '') {
 7891:                             $checkedon{$key} = ' checked="checked"';
 7892:                             $checkedoff{$key} = '';
 7893:                         }
 7894:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 7895:                         $checkedon{$key} = ' checked="checked"';
 7896:                         $checkedoff{$key} = '';
 7897:                     }
 7898:                 }
 7899:             }
 7900:         }
 7901:         foreach my $type (@{$types}) {
 7902:             next if ($type ne 'version' && !@locations);
 7903:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7904:             $datatable .= '<tr'.$css_class.'>
 7905:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 7906:                            <span class="LC_nobreak">&nbsp;
 7907:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 7908:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 7909:             if ($type eq 'version') {
 7910:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 7911:                 my $selector = '<select name="'.$prefix.'_version">';
 7912:                 foreach my $version (@lcversions) {
 7913:                     my $selected = '';
 7914:                     if ($current{'version'} eq $version) {
 7915:                         $selected = ' selected="selected"';
 7916:                     }
 7917:                     $selector .= ' <option value="'.$version.'"'.
 7918:                                  $selected.'>'.$version.'</option>';
 7919:                 }
 7920:                 $selector .= '</select> ';
 7921:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 7922:             } else {
 7923:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 7924:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 7925:                              ' />'.('&nbsp;'x2).
 7926:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 7927:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 7928:                              "\n".
 7929:                              '</div><div><table>';
 7930:                 my $rem;
 7931:                 for (my $i=0; $i<@locations; $i++) {
 7932:                     my ($showloc,$value,$checkedtype);
 7933:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 7934:                         my $ip = $by_location->{$locations[$i]}->[0];
 7935:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7936:                             $value = join(':',@{$by_ip->{$ip}});
 7937:                             $showloc = join(', ',@{$by_ip->{$ip}});
 7938:                             if (ref($current{$type}) eq 'ARRAY') {
 7939:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 7940:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 7941:                                         $checkedtype = ' checked="checked"';
 7942:                                         last;
 7943:                                     }
 7944:                                 }
 7945:                             }
 7946:                         }
 7947:                     }
 7948:                     $rem = $i%($numinrow);
 7949:                     if ($rem == 0) {
 7950:                         if ($i > 0) {
 7951:                             $datatable .= '</tr>';
 7952:                         }
 7953:                         $datatable .= '<tr>';
 7954:                     }
 7955:                     $datatable .= '<td class="LC_left_item">'.
 7956:                                   '<span class="LC_nobreak"><label>'.
 7957:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 7958:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 7959:                                   '</label></span></td>';
 7960:                 }
 7961:                 $rem = @locations%($numinrow);
 7962:                 my $colsleft = $numinrow - $rem;
 7963:                 if ($colsleft > 1 ) {
 7964:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7965:                                   '&nbsp;</td>';
 7966:                 } elsif ($colsleft == 1) {
 7967:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7968:                 }
 7969:                 $datatable .= '</tr></table>';
 7970:             }
 7971:             $datatable .= '</td></tr>';
 7972:             $itemcount ++;
 7973:         }
 7974:     }
 7975:     return ($datatable,$itemcount);
 7976: }
 7977: 
 7978: sub print_ssl {
 7979:     my ($position,$dom,$settings,$rowtotal) = @_;
 7980:     my ($css_class,$datatable);
 7981:     my $itemcount = 1;
 7982:     if ($position eq 'top') {
 7983:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7984:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7985:         my $same_institution;
 7986:         if ($intdom ne '') {
 7987:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 7988:             if (ref($internet_names) eq 'ARRAY') {
 7989:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 7990:                     $same_institution = 1;
 7991:                 }
 7992:             }
 7993:         }
 7994:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7995:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 7996:         if ($same_institution) {
 7997:             my %domservers = &Apache::lonnet::get_servers($dom);
 7998:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 7999:         } else {
 8000:             $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.");
 8001:         }
 8002:         $datatable .= '</td></tr>';
 8003:         $itemcount ++;
 8004:     } else {
 8005:         my %titles = &ssl_titles();
 8006:         my (%by_ip,%by_location,@intdoms,@instdoms);
 8007:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8008:         my @alldoms = &Apache::lonnet::all_domains();
 8009:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8010:         my @domservers = &Apache::lonnet::get_servers($dom);
 8011:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8012:         my %altids = &id_for_thisdom(%servers);
 8013:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 8014:             my $legacy;
 8015:             unless (ref($settings) eq 'HASH') {
 8016:                 my $name;
 8017:                 if ($position eq 'connto') {
 8018:                     $name = 'loncAllowInsecure';
 8019:                 } else {
 8020:                     $name = 'londAllowInsecure';
 8021:                 }
 8022:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 8023:                 my @ids=&Apache::lonnet::current_machine_ids();
 8024:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 8025:                     my %what = (
 8026:                                    $name => 1,
 8027:                                );
 8028:                     my ($result,$returnhash) =
 8029:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8030:                     if ($result eq 'ok') {
 8031:                         if (ref($returnhash) eq 'HASH') {
 8032:                             $legacy = $returnhash->{$name};
 8033:                         }
 8034:                     }
 8035:                 } else {
 8036:                     $legacy = $Apache::lonnet::perlvar{$name};
 8037:                 }
 8038:             }
 8039:             foreach my $type ('dom','intdom','other') {
 8040:                 my %checked;
 8041:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8042:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8043:                               '<td class="LC_right_item">';
 8044:                 my $skip; 
 8045:                 if ($type eq 'dom') {
 8046:                     unless (keys(%servers) > 1) {
 8047:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8048:                         $skip = 1;
 8049:                     }
 8050:                 }
 8051:                 if ($type eq 'intdom') {
 8052:                     unless (@instdoms > 1) {
 8053:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8054:                         $skip = 1;
 8055:                     } 
 8056:                 } elsif ($type eq 'other') {
 8057:                     if (keys(%by_location) == 0) {
 8058:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8059:                         $skip = 1;
 8060:                     }
 8061:                 }
 8062:                 unless ($skip) {
 8063:                     $checked{'yes'} = ' checked="checked"'; 
 8064:                     if (ref($settings) eq 'HASH') {
 8065:                         if (ref($settings->{$position}) eq 'HASH') {
 8066:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8067:                                 $checked{$1} = $checked{'yes'};
 8068:                                 delete($checked{'yes'}); 
 8069:                             }
 8070:                         }
 8071:                     } else {
 8072:                         if ($legacy == 0) {
 8073:                             $checked{'req'} = $checked{'yes'};
 8074:                             delete($checked{'yes'});    
 8075:                         }
 8076:                     }
 8077:                     foreach my $option ('no','yes','req') {
 8078:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8079:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8080:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8081:                                       '</label></span>'.('&nbsp;'x2);
 8082:                     }
 8083:                 }
 8084:                 $datatable .= '</td></tr>';
 8085:                 $itemcount ++; 
 8086:             }
 8087:         } else {
 8088:             my $prefix = 'replication';
 8089:             my @types = ('certreq','nocertreq');
 8090:             if (keys(%by_location) == 0) {
 8091:                 $datatable .= '<tr'.$css_class.'><td>'.
 8092:                               &mt('Nothing to set here, as there are no other institutions').
 8093:                               '</td></tr>';
 8094:                 $itemcount ++;
 8095:             } else {
 8096:                 ($datatable,$itemcount) = 
 8097:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8098:             }
 8099:         }
 8100:     }
 8101:     $$rowtotal += $itemcount;
 8102:     return $datatable;
 8103: }
 8104: 
 8105: sub ssl_titles {
 8106:     return &Apache::lonlocal::texthash (
 8107:                dom           => 'LON-CAPA servers/VMs from same domain',
 8108:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8109:                other         => 'External LON-CAPA servers/VMs',
 8110:                connto        => 'Connections to other servers',
 8111:                connfrom      => 'Connections from other servers',
 8112:                replication   => 'Replicating content to other institutions',
 8113:                certreq       => 'Client certificate required, but specific domains exempt',
 8114:                nocertreq     => 'No client certificate required, except for specific domains',
 8115:                no            => 'SSL not used',
 8116:                yes           => 'SSL Optional (used if available)',
 8117:                req           => 'SSL Required',
 8118:     );
 8119: }
 8120: 
 8121: sub print_trust {
 8122:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8123:     my ($css_class,$datatable,%checked,%choices);
 8124:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8125:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8126:     my $itemcount = 1;
 8127:     my %titles = &trust_titles();
 8128:     my @types = ('exc','inc');
 8129:     if ($prefix eq 'top') {
 8130:         $prefix = 'content';
 8131:     } elsif ($prefix eq 'bottom') {
 8132:         $prefix = 'msg';
 8133:     }
 8134:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8135:     $$rowtotal += $itemcount;
 8136:     return $datatable;
 8137: }
 8138: 
 8139: sub trust_titles {
 8140:     return &Apache::lonlocal::texthash(
 8141:                content  => "Access to this domain's content by others",
 8142:                shared   => "Access to other domain's content by this domain",
 8143:                enroll   => "Enrollment in this domain's courses by others", 
 8144:                othcoau  => "Co-author roles in this domain for others",
 8145:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8146:                domroles => "Domain roles in this domain assignable to others",
 8147:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8148:                reqcrs   => "Requests for creation of courses in this domain by others",
 8149:                msg      => "Users in other domains can send messages to this domain",
 8150:                exc      => "Allow all, but exclude specific domains",
 8151:                inc      => "Deny all, but include specific domains",
 8152:            );
 8153: } 
 8154: 
 8155: sub build_location_hashes {
 8156:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8157:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8158:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8159:     my %iphost = &Apache::lonnet::get_iphost();
 8160:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 8161:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 8162:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 8163:         foreach my $id (@{$iphost{$primary_ip}}) {
 8164:             my $intdom = &Apache::lonnet::internet_dom($id);
 8165:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 8166:                 push(@{$intdoms},$intdom);
 8167:             }
 8168:         }
 8169:     }
 8170:     foreach my $ip (keys(%iphost)) {
 8171:         if (ref($iphost{$ip}) eq 'ARRAY') {
 8172:             foreach my $id (@{$iphost{$ip}}) {
 8173:                 my $location = &Apache::lonnet::internet_dom($id);
 8174:                 if ($location) {
 8175:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 8176:                         my $dom = &Apache::lonnet::host_domain($id);
 8177:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 8178:                             push(@{$instdoms},$dom);
 8179:                         }
 8180:                         next;
 8181:                     }
 8182:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8183:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 8184:                             push(@{$by_ip->{$ip}},$location);
 8185:                         }
 8186:                     } else {
 8187:                         $by_ip->{$ip} = [$location];
 8188:                     }
 8189:                 }
 8190:             }
 8191:         }
 8192:     }
 8193:     foreach my $ip (sort(keys(%{$by_ip}))) {
 8194:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8195:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 8196:             my $first = $by_ip->{$ip}->[0];
 8197:             if (ref($by_location->{$first}) eq 'ARRAY') {
 8198:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 8199:                     push(@{$by_location->{$first}},$ip);
 8200:                 }
 8201:             } else {
 8202:                 $by_location->{$first} = [$ip];
 8203:             }
 8204:         }
 8205:     }
 8206:     return;
 8207: }
 8208: 
 8209: sub current_offloads_to {
 8210:     my ($dom,$settings,$servers) = @_;
 8211:     my (%spareid,%otherdomconfigs);
 8212:     if (ref($servers) eq 'HASH') {
 8213:         foreach my $lonhost (sort(keys(%{$servers}))) {
 8214:             my $gotspares;
 8215:             if (ref($settings) eq 'HASH') {
 8216:                 if (ref($settings->{'spares'}) eq 'HASH') {
 8217:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 8218:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 8219:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 8220:                         $gotspares = 1;
 8221:                     }
 8222:                 }
 8223:             }
 8224:             unless ($gotspares) {
 8225:                 my $gotspares;
 8226:                 my $serverhomeID =
 8227:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 8228:                 my $serverhomedom =
 8229:                     &Apache::lonnet::host_domain($serverhomeID);
 8230:                 if ($serverhomedom ne $dom) {
 8231:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 8232:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 8233:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 8234:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 8235:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 8236:                                 $gotspares = 1;
 8237:                             }
 8238:                         }
 8239:                     } else {
 8240:                         $otherdomconfigs{$serverhomedom} =
 8241:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 8242:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 8243:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 8244:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 8245:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 8246:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 8247:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 8248:                                         $gotspares = 1;
 8249:                                     }
 8250:                                 }
 8251:                             }
 8252:                         }
 8253:                     }
 8254:                 }
 8255:             }
 8256:             unless ($gotspares) {
 8257:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8258:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8259:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8260:                } else {
 8261:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 8262:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 8263:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8264:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8265:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8266:                     } else {
 8267:                         my %what = (
 8268:                              spareid => 1,
 8269:                         );
 8270:                         my ($result,$returnhash) = 
 8271:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 8272:                         if ($result eq 'ok') { 
 8273:                             if (ref($returnhash) eq 'HASH') {
 8274:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 8275:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 8276:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 8277:                                 }
 8278:                             }
 8279:                         }
 8280:                     }
 8281:                 }
 8282:             }
 8283:         }
 8284:     }
 8285:     return %spareid;
 8286: }
 8287: 
 8288: sub spares_row {
 8289:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 8290:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 8291:     my $css_class;
 8292:     my $numinrow = 4;
 8293:     my $itemcount = 1;
 8294:     my $datatable;
 8295:     my %typetitles = &sparestype_titles();
 8296:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8297:         foreach my $server (sort(keys(%{$servers}))) {
 8298:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 8299:             my ($othercontrol,$serverdom);
 8300:             if ($serverhome ne $server) {
 8301:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 8302:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8303:             } else {
 8304:                 $serverdom = &Apache::lonnet::host_domain($server);
 8305:                 if ($serverdom ne $dom) {
 8306:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8307:                 }
 8308:             }
 8309:             next unless (ref($spareid->{$server}) eq 'HASH');
 8310:             my ($checkednow,$checkedoth);
 8311:             if (ref($curroffloadnow) eq 'HASH') {
 8312:                 if ($curroffloadnow->{$server}) {
 8313:                     $checkednow = ' checked="checked"';
 8314:                 }
 8315:             }
 8316:             if (ref($curroffloadoth) eq 'HASH') {
 8317:                 if ($curroffloadoth->{$server}) {
 8318:                     $checkedoth = ' checked="checked"';
 8319:                 }
 8320:             }
 8321:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8322:             $datatable .= '<tr'.$css_class.'>
 8323:                            <td rowspan="2">
 8324:                             <span class="LC_nobreak">'.
 8325:                           &mt('[_1] when busy, offloads to:'
 8326:                               ,'<b>'.$server.'</b>').'</span><br />'.
 8327:                           '<span class="LC_nobreak">'."\n".
 8328:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 8329:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 8330:                           "\n";
 8331:             if ($other_insts) {
 8332:                 $datatable .= '<br />'.
 8333:                               '<span class="LC_nobreak">'."\n".
 8334:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 8335:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 8336:                           "\n";
 8337:             }
 8338:             my (%current,%canselect);
 8339:             my @choices = 
 8340:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 8341:             foreach my $type ('primary','default') {
 8342:                 if (ref($spareid->{$server}) eq 'HASH') {
 8343:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 8344:                         my @spares = @{$spareid->{$server}{$type}};
 8345:                         if (@spares > 0) {
 8346:                             if ($othercontrol) {
 8347:                                 $current{$type} = join(', ',@spares);
 8348:                             } else {
 8349:                                 $current{$type} .= '<table>';
 8350:                                 my $numspares = scalar(@spares);
 8351:                                 for (my $i=0;  $i<@spares; $i++) {
 8352:                                     my $rem = $i%($numinrow);
 8353:                                     if ($rem == 0) {
 8354:                                         if ($i > 0) {
 8355:                                             $current{$type} .= '</tr>';
 8356:                                         }
 8357:                                         $current{$type} .= '<tr>';
 8358:                                     }
 8359:                                     $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;'.
 8360:                                                        $spareid->{$server}{$type}[$i].
 8361:                                                        '</label></td>'."\n";
 8362:                                 }
 8363:                                 my $rem = @spares%($numinrow);
 8364:                                 my $colsleft = $numinrow - $rem;
 8365:                                 if ($colsleft > 1 ) {
 8366:                                     $current{$type} .= '<td colspan="'.$colsleft.
 8367:                                                        '" class="LC_left_item">'.
 8368:                                                        '&nbsp;</td>';
 8369:                                 } elsif ($colsleft == 1) {
 8370:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 8371:                                 }
 8372:                                 $current{$type} .= '</tr></table>';
 8373:                             }
 8374:                         }
 8375:                     }
 8376:                     if ($current{$type} eq '') {
 8377:                         $current{$type} = &mt('None specified');
 8378:                     }
 8379:                     if ($othercontrol) {
 8380:                         if ($type eq 'primary') {
 8381:                             $canselect{$type} = $othercontrol;
 8382:                         }
 8383:                     } else {
 8384:                         $canselect{$type} = 
 8385:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 8386:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 8387:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 8388:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 8389:                         if (@choices > 0) {
 8390:                             foreach my $lonhost (@choices) {
 8391:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 8392:                             }
 8393:                         }
 8394:                         $canselect{$type} .= '</select>'."\n";
 8395:                     }
 8396:                 } else {
 8397:                     $current{$type} = &mt('Could not be determined');
 8398:                     if ($type eq 'primary') {
 8399:                         $canselect{$type} =  $othercontrol;
 8400:                     }
 8401:                 }
 8402:                 if ($type eq 'default') {
 8403:                     $datatable .= '<tr'.$css_class.'>';
 8404:                 }
 8405:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 8406:                               '<td>'.$current{$type}.'</td>'."\n".
 8407:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 8408:             }
 8409:             $itemcount ++;
 8410:         }
 8411:     }
 8412:     $$rowtotal += $itemcount;
 8413:     return $datatable;
 8414: }
 8415: 
 8416: sub possible_newspares {
 8417:     my ($server,$currspares,$serverhomes,$altids) = @_;
 8418:     my $serverhostname = &Apache::lonnet::hostname($server);
 8419:     my %excluded;
 8420:     if ($serverhostname ne '') {
 8421:         %excluded = (
 8422:                        $serverhostname => 1,
 8423:                     );
 8424:     }
 8425:     if (ref($currspares) eq 'HASH') {
 8426:         foreach my $type (keys(%{$currspares})) {
 8427:             if (ref($currspares->{$type}) eq 'ARRAY') {
 8428:                 if (@{$currspares->{$type}} > 0) {
 8429:                     foreach my $curr (@{$currspares->{$type}}) {
 8430:                         my $hostname = &Apache::lonnet::hostname($curr);
 8431:                         $excluded{$hostname} = 1;
 8432:                     }
 8433:                 }
 8434:             }
 8435:         }
 8436:     }
 8437:     my @choices;
 8438:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8439:         if (keys(%{$serverhomes}) > 1) {
 8440:             foreach my $name (sort(keys(%{$serverhomes}))) {
 8441:                 unless ($excluded{$name}) {
 8442:                     if (exists($altids->{$serverhomes->{$name}})) {
 8443:                         push(@choices,$altids->{$serverhomes->{$name}});
 8444:                     } else {
 8445:                         push(@choices,$serverhomes->{$name});
 8446:                     }
 8447:                 }
 8448:             }
 8449:         }
 8450:     }
 8451:     return sort(@choices);
 8452: }
 8453: 
 8454: sub print_loadbalancing {
 8455:     my ($dom,$settings,$rowtotal) = @_;
 8456:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8457:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8458:     my $numinrow = 1;
 8459:     my $datatable;
 8460:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8461:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 8462:     if (ref($settings) eq 'HASH') {
 8463:         %existing = %{$settings};
 8464:     }
 8465:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 8466:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 8467:                                   \%currtargets,\%currrules,\%currcookies);
 8468:     } else {
 8469:         return;
 8470:     }
 8471:     my ($othertitle,$usertypes,$types) =
 8472:         &Apache::loncommon::sorted_inst_types($dom);
 8473:     my $rownum = 8;
 8474:     if (ref($types) eq 'ARRAY') {
 8475:         $rownum += scalar(@{$types});
 8476:     }
 8477:     my @css_class = ('LC_odd_row','LC_even_row');
 8478:     my $balnum = 0;
 8479:     my $islast;
 8480:     my (@toshow,$disabledtext);
 8481:     if (keys(%currbalancer) > 0) {
 8482:         @toshow = sort(keys(%currbalancer));
 8483:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 8484:             push(@toshow,'');
 8485:         }
 8486:     } else {
 8487:         @toshow = ('');
 8488:         $disabledtext = &mt('No existing load balancer');
 8489:     }
 8490:     foreach my $lonhost (@toshow) {
 8491:         if ($balnum == scalar(@toshow)-1) {
 8492:             $islast = 1;
 8493:         } else {
 8494:             $islast = 0;
 8495:         }
 8496:         my $cssidx = $balnum%2;
 8497:         my $targets_div_style = 'display: none';
 8498:         my $disabled_div_style = 'display: block';
 8499:         my $homedom_div_style = 'display: none';
 8500:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 8501:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8502:                       '<p>';
 8503:         if ($lonhost eq '') {
 8504:             $datatable .= '<span class="LC_nobreak">';
 8505:             if (keys(%currbalancer) > 0) {
 8506:                 $datatable .= &mt('Add balancer:');
 8507:             } else {
 8508:                 $datatable .= &mt('Enable balancer:');
 8509:             }
 8510:             $datatable .= '&nbsp;'.
 8511:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 8512:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 8513:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 8514:                           '<option value="" selected="selected">'.&mt('None').
 8515:                           '</option>'."\n";
 8516:             foreach my $server (sort(keys(%servers))) {
 8517:                 next if ($currbalancer{$server});
 8518:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 8519:             }
 8520:             $datatable .=
 8521:                 '</select>'."\n".
 8522:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 8523:         } else {
 8524:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 8525:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 8526:                            &mt('Stop balancing').'</label>'.
 8527:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 8528:             $targets_div_style = 'display: block';
 8529:             $disabled_div_style = 'display: none';
 8530:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 8531:                 $homedom_div_style = 'display: block';
 8532:             }
 8533:         }
 8534:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8535:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 8536:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 8537:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 8538:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 8539:         my @sparestypes = ('primary','default');
 8540:         my %typetitles = &sparestype_titles();
 8541:         my %hostherechecked = (
 8542:                                   no => ' checked="checked"',
 8543:                               );
 8544:         my %balcookiechecked = (
 8545:                                   no => ' checked="checked"', 
 8546:                                );
 8547:         foreach my $sparetype (@sparestypes) {
 8548:             my $targettable;
 8549:             for (my $i=0; $i<$numspares; $i++) {
 8550:                 my $checked;
 8551:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 8552:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8553:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8554:                             $checked = ' checked="checked"';
 8555:                         }
 8556:                     }
 8557:                 }
 8558:                 my ($chkboxval,$disabled);
 8559:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 8560:                     $chkboxval = $spares[$i];
 8561:                 }
 8562:                 if (exists($currbalancer{$spares[$i]})) {
 8563:                     $disabled = ' disabled="disabled"';
 8564:                 }
 8565:                 $targettable .=
 8566:                     '<td><span class="LC_nobreak"><label>'.
 8567:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 8568:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 8569:                     '</span></label></span></td>';
 8570:                 my $rem = $i%($numinrow);
 8571:                 if ($rem == 0) {
 8572:                     if (($i > 0) && ($i < $numspares-1)) {
 8573:                         $targettable .= '</tr>';
 8574:                     }
 8575:                     if ($i < $numspares-1) {
 8576:                         $targettable .= '<tr>';
 8577:                     }
 8578:                 }
 8579:             }
 8580:             if ($targettable ne '') {
 8581:                 my $rem = $numspares%($numinrow);
 8582:                 my $colsleft = $numinrow - $rem;
 8583:                 if ($colsleft > 1 ) {
 8584:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8585:                                     '&nbsp;</td>';
 8586:                 } elsif ($colsleft == 1) {
 8587:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 8588:                 }
 8589:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 8590:                                '<table><tr>'.$targettable.'</tr></table><br />';
 8591:             }
 8592:             $hostherechecked{$sparetype} = '';
 8593:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 8594:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8595:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8596:                         $hostherechecked{$sparetype} = ' checked="checked"';
 8597:                         $hostherechecked{'no'} = '';
 8598:                     }
 8599:                 }
 8600:             }
 8601:         }
 8602:         if ($currcookies{$lonhost}) {
 8603:             %balcookiechecked = (
 8604:                                     yes => ' checked="checked"',
 8605:                                 );
 8606:         }
 8607:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 8608:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 8609:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 8610:         foreach my $sparetype (@sparestypes) {
 8611:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 8612:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 8613:                           '</i></label><br />';
 8614:         }
 8615:         $datatable .= &mt('Use balancer cookie').'<br />'.
 8616:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 8617:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 8618:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 8619:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 8620:                       '</div></td></tr>'.
 8621:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 8622:                                            $othertitle,$usertypes,$types,\%servers,
 8623:                                            \%currbalancer,$lonhost,
 8624:                                            $targets_div_style,$homedom_div_style,
 8625:                                            $css_class[$cssidx],$balnum,$islast);
 8626:         $$rowtotal += $rownum;
 8627:         $balnum ++;
 8628:     }
 8629:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 8630:     return $datatable;
 8631: }
 8632: 
 8633: sub get_loadbalancers_config {
 8634:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 8635:     return unless ((ref($servers) eq 'HASH') &&
 8636:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 8637:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 8638:                    (ref($currcookies) eq 'HASH'));
 8639:     if (keys(%{$existing}) > 0) {
 8640:         my $oldlonhost;
 8641:         foreach my $key (sort(keys(%{$existing}))) {
 8642:             if ($key eq 'lonhost') {
 8643:                 $oldlonhost = $existing->{'lonhost'};
 8644:                 $currbalancer->{$oldlonhost} = 1;
 8645:             } elsif ($key eq 'targets') {
 8646:                 if ($oldlonhost) {
 8647:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 8648:                 }
 8649:             } elsif ($key eq 'rules') {
 8650:                 if ($oldlonhost) {
 8651:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 8652:                 }
 8653:             } elsif (ref($existing->{$key}) eq 'HASH') {
 8654:                 $currbalancer->{$key} = 1;
 8655:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 8656:                 $currrules->{$key} = $existing->{$key}{'rules'};
 8657:                 if ($existing->{$key}{'cookie'}) {
 8658:                     $currcookies->{$key} = 1;
 8659:                 }
 8660:             }
 8661:         }
 8662:     } else {
 8663:         my ($balancerref,$targetsref) =
 8664:                 &Apache::lonnet::get_lonbalancer_config($servers);
 8665:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 8666:             foreach my $server (sort(keys(%{$balancerref}))) {
 8667:                 $currbalancer->{$server} = 1;
 8668:                 $currtargets->{$server} = $targetsref->{$server};
 8669:             }
 8670:         }
 8671:     }
 8672:     return;
 8673: }
 8674: 
 8675: sub loadbalancing_rules {
 8676:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 8677:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 8678:         $css_class,$balnum,$islast) = @_;
 8679:     my $output;
 8680:     my $num = 0;
 8681:     my ($alltypes,$othertypes,$titles) =
 8682:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 8683:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 8684:         foreach my $type (@{$alltypes}) {
 8685:             $num ++;
 8686:             my $current;
 8687:             if (ref($currrules) eq 'HASH') {
 8688:                 $current = $currrules->{$type};
 8689:             }
 8690:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8691:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 8692:                     $current = '';
 8693:                 }
 8694:             }
 8695:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 8696:                                              $servers,$currbalancer,$lonhost,$dom,
 8697:                                              $targets_div_style,$homedom_div_style,
 8698:                                              $css_class,$balnum,$num,$islast);
 8699:         }
 8700:     }
 8701:     return $output;
 8702: }
 8703: 
 8704: sub loadbalancing_titles {
 8705:     my ($dom,$intdom,$usertypes,$types) = @_;
 8706:     my %othertypes = (
 8707:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 8708:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 8709:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 8710:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 8711:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 8712:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 8713:                      );
 8714:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 8715:     my @available;
 8716:     if (ref($types) eq 'ARRAY') {
 8717:         @available = @{$types};
 8718:     }
 8719:     unless (grep(/^default$/,@available)) {
 8720:         push(@available,'default');
 8721:     }
 8722:     unshift(@alltypes,@available);
 8723:     my %titles;
 8724:     foreach my $type (@alltypes) {
 8725:         if ($type =~ /^_LC_/) {
 8726:             $titles{$type} = $othertypes{$type};
 8727:         } elsif ($type eq 'default') {
 8728:             $titles{$type} = &mt('All users from [_1]',$dom);
 8729:             if (ref($types) eq 'ARRAY') {
 8730:                 if (@{$types} > 0) {
 8731:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 8732:                 }
 8733:             }
 8734:         } elsif (ref($usertypes) eq 'HASH') {
 8735:             $titles{$type} = $usertypes->{$type};
 8736:         }
 8737:     }
 8738:     return (\@alltypes,\%othertypes,\%titles);
 8739: }
 8740: 
 8741: sub loadbalance_rule_row {
 8742:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 8743:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 8744:     my @rulenames;
 8745:     my %ruletitles = &offloadtype_text();
 8746:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 8747:         @rulenames = ('balancer','offloadedto','specific');
 8748:     } else {
 8749:         @rulenames = ('default','homeserver');
 8750:         if ($type eq '_LC_external') {
 8751:             push(@rulenames,'externalbalancer');
 8752:         } else {
 8753:             push(@rulenames,'specific');
 8754:         }
 8755:         push(@rulenames,'none');
 8756:     }
 8757:     my $style = $targets_div_style;
 8758:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8759:         $style = $homedom_div_style;
 8760:     }
 8761:     my $space;
 8762:     if ($islast && $num == 1) {
 8763:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 8764:     }
 8765:     my $output =
 8766:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 8767:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 8768:         '<td valaign="top">'.$space.
 8769:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 8770:     for (my $i=0; $i<@rulenames; $i++) {
 8771:         my $rule = $rulenames[$i];
 8772:         my ($checked,$extra);
 8773:         if ($rulenames[$i] eq 'default') {
 8774:             $rule = '';
 8775:         }
 8776:         if ($rulenames[$i] eq 'specific') {
 8777:             if (ref($servers) eq 'HASH') {
 8778:                 my $default;
 8779:                 if (($current ne '') && (exists($servers->{$current}))) {
 8780:                     $checked = ' checked="checked"';
 8781:                 }
 8782:                 unless ($checked) {
 8783:                     $default = ' selected="selected"';
 8784:                 }
 8785:                 $extra =
 8786:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8787:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8788:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 8789:                     '<option value=""'.$default.'></option>'."\n";
 8790:                 foreach my $server (sort(keys(%{$servers}))) {
 8791:                     if (ref($currbalancer) eq 'HASH') {
 8792:                         next if (exists($currbalancer->{$server}));
 8793:                     }
 8794:                     my $selected;
 8795:                     if ($server eq $current) {
 8796:                         $selected = ' selected="selected"';
 8797:                     }
 8798:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 8799:                 }
 8800:                 $extra .= '</select>';
 8801:             }
 8802:         } elsif ($rule eq $current) {
 8803:             $checked = ' checked="checked"';
 8804:         }
 8805:         $output .= '<span class="LC_nobreak"><label>'.
 8806:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 8807:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 8808:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 8809:                    ')"'.$checked.' />&nbsp;';
 8810:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 8811:             $output .= $ruletitles{'particular'};
 8812:         } else {
 8813:             $output .= $ruletitles{$rulenames[$i]};
 8814:         }
 8815:         $output .= '</label>'.$extra.'</span><br />'."\n";
 8816:     }
 8817:     $output .= '</div></td></tr>'."\n";
 8818:     return $output;
 8819: }
 8820: 
 8821: sub offloadtype_text {
 8822:     my %ruletitles = &Apache::lonlocal::texthash (
 8823:            'default'          => 'Offloads to default destinations',
 8824:            'homeserver'       => "Offloads to user's home server",
 8825:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 8826:            'specific'         => 'Offloads to specific server',
 8827:            'none'             => 'No offload',
 8828:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 8829:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 8830:            'particular'       => 'Session hosted (after re-auth) on server:',
 8831:     );
 8832:     return %ruletitles;
 8833: }
 8834: 
 8835: sub sparestype_titles {
 8836:     my %typestitles = &Apache::lonlocal::texthash (
 8837:                           'primary' => 'primary',
 8838:                           'default' => 'default',
 8839:                       );
 8840:     return %typestitles;
 8841: }
 8842: 
 8843: sub contact_titles {
 8844:     my %titles = &Apache::lonlocal::texthash (
 8845:                    'supportemail'    => 'Support E-mail address',
 8846:                    'adminemail'      => 'Default Server Admin E-mail address',
 8847:                    'errormail'       => 'Error reports to be e-mailed to',
 8848:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 8849:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 8850:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 8851:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 8852:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 8853:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 8854:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 8855:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 8856:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 8857:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 8858:                    'errorweights'    => 'Weights used to compute error count',
 8859:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 8860:                  );
 8861:     my %short_titles = &Apache::lonlocal::texthash (
 8862:                            adminemail   => 'Admin E-mail address',
 8863:                            supportemail => 'Support E-mail',
 8864:                        );   
 8865:     return (\%titles,\%short_titles);
 8866: }
 8867: 
 8868: sub helpform_fields {
 8869:     my %titles =  &Apache::lonlocal::texthash (
 8870:                        'username'   => 'Name',
 8871:                        'user'       => 'Username/domain',
 8872:                        'phone'      => 'Phone',
 8873:                        'cc'         => 'Cc e-mail',
 8874:                        'course'     => 'Course Details',
 8875:                        'section'    => 'Sections',
 8876:                        'screenshot' => 'File upload',
 8877:     );
 8878:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 8879:     my %possoptions = (
 8880:                         username     => ['yes','no','req'],
 8881:                         phone        => ['yes','no','req'],
 8882:                         user         => ['yes','no'],
 8883:                         cc           => ['yes','no'],
 8884:                         course       => ['yes','no'],
 8885:                         section      => ['yes','no'],
 8886:                         screenshot   => ['yes','no'],
 8887:                       );
 8888:     my %fieldoptions = &Apache::lonlocal::texthash (
 8889:                          'yes'  => 'Optional',
 8890:                          'req'  => 'Required',
 8891:                          'no'   => "Not shown",
 8892:     );
 8893:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 8894: }
 8895: 
 8896: sub tool_titles {
 8897:     my %titles = &Apache::lonlocal::texthash (
 8898:                      aboutme    => 'Personal web page',
 8899:                      blog       => 'Blog',
 8900:                      webdav     => 'WebDAV',
 8901:                      portfolio  => 'Portfolio',
 8902:                      official   => 'Official courses (with institutional codes)',
 8903:                      unofficial => 'Unofficial courses',
 8904:                      community  => 'Communities',
 8905:                      textbook   => 'Textbook courses',
 8906:                      placement  => 'Placement tests',
 8907:                  );
 8908:     return %titles;
 8909: }
 8910: 
 8911: sub courserequest_titles {
 8912:     my %titles = &Apache::lonlocal::texthash (
 8913:                                    official   => 'Official',
 8914:                                    unofficial => 'Unofficial',
 8915:                                    community  => 'Communities',
 8916:                                    textbook   => 'Textbook',
 8917:                                    placement  => 'Placement tests',
 8918:                                    lti        => 'LTI Provider',
 8919:                                    norequest  => 'Not allowed',
 8920:                                    approval   => 'Approval by DC',
 8921:                                    validate   => 'With validation',
 8922:                                    autolimit  => 'Numerical limit',
 8923:                                    unlimited  => '(blank for unlimited)',
 8924:                  );
 8925:     return %titles;
 8926: }
 8927: 
 8928: sub authorrequest_titles {
 8929:     my %titles = &Apache::lonlocal::texthash (
 8930:                                    norequest  => 'Not allowed',
 8931:                                    approval   => 'Approval by Dom. Coord.',
 8932:                                    automatic  => 'Automatic approval',
 8933:                  );
 8934:     return %titles;
 8935: }
 8936: 
 8937: sub courserequest_conditions {
 8938:     my %conditions = &Apache::lonlocal::texthash (
 8939:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 8940:        validate   => '(Processing of request subject to institutional validation).',
 8941:                  );
 8942:     return %conditions;
 8943: }
 8944: 
 8945: 
 8946: sub print_usercreation {
 8947:     my ($position,$dom,$settings,$rowtotal) = @_;
 8948:     my $numinrow = 4;
 8949:     my $datatable;
 8950:     if ($position eq 'top') {
 8951:         $$rowtotal ++;
 8952:         my $rowcount = 0;
 8953:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 8954:         if (ref($rules) eq 'HASH') {
 8955:             if (keys(%{$rules}) > 0) {
 8956:                 $datatable .= &user_formats_row('username',$settings,$rules,
 8957:                                                 $ruleorder,$numinrow,$rowcount);
 8958:                 $$rowtotal ++;
 8959:                 $rowcount ++;
 8960:             }
 8961:         }
 8962:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 8963:         if (ref($idrules) eq 'HASH') {
 8964:             if (keys(%{$idrules}) > 0) {
 8965:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 8966:                                                 $idruleorder,$numinrow,$rowcount);
 8967:                 $$rowtotal ++;
 8968:                 $rowcount ++;
 8969:             }
 8970:         }
 8971:         if ($rowcount == 0) {
 8972:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 8973:             $$rowtotal ++;
 8974:             $rowcount ++;
 8975:         }
 8976:     } elsif ($position eq 'middle') {
 8977:         my @creators = ('author','course','requestcrs');
 8978:         my ($rules,$ruleorder) =
 8979:             &Apache::lonnet::inst_userrules($dom,'username');
 8980:         my %lt = &usercreation_types();
 8981:         my %checked;
 8982:         if (ref($settings) eq 'HASH') {
 8983:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 8984:                 foreach my $item (@creators) {
 8985:                     $checked{$item} = $settings->{'cancreate'}{$item};
 8986:                 }
 8987:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 8988:                 foreach my $item (@creators) {
 8989:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 8990:                         $checked{$item} = 'none';
 8991:                     }
 8992:                 }
 8993:             }
 8994:         }
 8995:         my $rownum = 0;
 8996:         foreach my $item (@creators) {
 8997:             $rownum ++;
 8998:             if ($checked{$item} eq '') {
 8999:                 $checked{$item} = 'any';
 9000:             }
 9001:             my $css_class;
 9002:             if ($rownum%2) {
 9003:                 $css_class = '';
 9004:             } else {
 9005:                 $css_class = ' class="LC_odd_row" ';
 9006:             }
 9007:             $datatable .= '<tr'.$css_class.'>'.
 9008:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 9009:                          '</span></td><td style="text-align: right">';
 9010:             my @options = ('any');
 9011:             if (ref($rules) eq 'HASH') {
 9012:                 if (keys(%{$rules}) > 0) {
 9013:                     push(@options,('official','unofficial'));
 9014:                 }
 9015:             }
 9016:             push(@options,'none');
 9017:             foreach my $option (@options) {
 9018:                 my $type = 'radio';
 9019:                 my $check = ' ';
 9020:                 if ($checked{$item} eq $option) {
 9021:                     $check = ' checked="checked" ';
 9022:                 } 
 9023:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9024:                               '<input type="'.$type.'" name="can_createuser_'.
 9025:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 9026:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 9027:             }
 9028:             $datatable .= '</td></tr>';
 9029:         }
 9030:     } else {
 9031:         my @contexts = ('author','course','domain');
 9032:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9033:         my %checked;
 9034:         if (ref($settings) eq 'HASH') {
 9035:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9036:                 foreach my $item (@contexts) {
 9037:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9038:                         foreach my $auth (@authtypes) {
 9039:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9040:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9041:                             }
 9042:                         }
 9043:                     }
 9044:                 }
 9045:             }
 9046:         } else {
 9047:             foreach my $item (@contexts) {
 9048:                 foreach my $auth (@authtypes) {
 9049:                     $checked{$item}{$auth} = ' checked="checked" ';
 9050:                 }
 9051:             }
 9052:         }
 9053:         my %title = &context_names();
 9054:         my %authname = &authtype_names();
 9055:         my $rownum = 0;
 9056:         my $css_class; 
 9057:         foreach my $item (@contexts) {
 9058:             if ($rownum%2) {
 9059:                 $css_class = '';
 9060:             } else {
 9061:                 $css_class = ' class="LC_odd_row" ';
 9062:             }
 9063:             $datatable .=   '<tr'.$css_class.'>'.
 9064:                             '<td>'.$title{$item}.
 9065:                             '</td><td class="LC_left_item">'.
 9066:                             '<span class="LC_nobreak">';
 9067:             foreach my $auth (@authtypes) {
 9068:                 $datatable .= '<label>'. 
 9069:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9070:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9071:                               $authname{$auth}.'</label>&nbsp;';
 9072:             }
 9073:             $datatable .= '</span></td></tr>';
 9074:             $rownum ++;
 9075:         }
 9076:         $$rowtotal += $rownum;
 9077:     }
 9078:     return $datatable;
 9079: }
 9080: 
 9081: sub print_selfcreation {
 9082:     my ($position,$dom,$settings,$rowtotal) = @_;
 9083:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9084:         $emaildomain,$datatable);
 9085:     if (ref($settings) eq 'HASH') {
 9086:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9087:             $createsettings = $settings->{'cancreate'};
 9088:             if (ref($createsettings) eq 'HASH') {
 9089:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9090:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9091:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9092:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9093:                         @selfcreate = ('email','login','sso');
 9094:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9095:                         @selfcreate = ($createsettings->{'selfcreate'});
 9096:                     }
 9097:                 }
 9098:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9099:                     $processing = $createsettings->{'selfcreateprocessing'};
 9100:                 }
 9101:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9102:                     $emailoptions = $createsettings->{'emailoptions'};
 9103:                 }
 9104:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9105:                     $emailverified = $createsettings->{'emailverified'};
 9106:                 }
 9107:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9108:                     $emaildomain = $createsettings->{'emaildomain'};
 9109:                 }
 9110:             }
 9111:         }
 9112:     }
 9113:     my %radiohash;
 9114:     my $numinrow = 4;
 9115:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9116:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9117:     if ($position eq 'top') {
 9118:         my %choices = &Apache::lonlocal::texthash (
 9119:                                                       cancreate_login      => 'Institutional Login',
 9120:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9121:                                                   );
 9122:         my @toggles = sort(keys(%choices));
 9123:         my %defaultchecked = (
 9124:                                'cancreate_login' => 'off',
 9125:                                'cancreate_sso'   => 'off',
 9126:                              );
 9127:         my ($onclick,$itemcount);
 9128:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9129:                                                      \%choices,$itemcount,$onclick);
 9130:         $$rowtotal += $itemcount;
 9131:         
 9132:         if (ref($usertypes) eq 'HASH') {
 9133:             if (keys(%{$usertypes}) > 0) {
 9134:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9135:                                              $dom,$numinrow,$othertitle,
 9136:                                              'statustocreate',$rowtotal);
 9137:                 $$rowtotal ++;
 9138:             }
 9139:         }
 9140:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9141:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9142:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9143:         my $rem;
 9144:         my $numperrow = 2;
 9145:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9146:         $datatable .= '<tr'.$css_class.'>'.
 9147:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9148:                      '<td class="LC_left_item">'."\n".
 9149:                      '<table>'."\n";
 9150:         for (my $i=0; $i<@fields; $i++) {
 9151:             $rem = $i%($numperrow);
 9152:             if ($rem == 0) {
 9153:                 if ($i > 0) {
 9154:                     $datatable .= '</tr>';
 9155:                 }
 9156:                 $datatable .= '<tr>';
 9157:             }
 9158:             my $currval;
 9159:             if (ref($createsettings) eq 'HASH') {
 9160:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 9161:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 9162:                 }
 9163:             }
 9164:             $datatable .= '<td class="LC_left_item">'.
 9165:                           '<span class="LC_nobreak">'.
 9166:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 9167:                           'value="'.$currval.'" size="10" />&nbsp;'.
 9168:                           $fieldtitles{$fields[$i]}.'</span></td>';
 9169:         }
 9170:         my $colsleft = $numperrow - $rem;
 9171:         if ($colsleft > 1 ) {
 9172:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9173:                          '&nbsp;</td>';
 9174:         } elsif ($colsleft == 1) {
 9175:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 9176:         }
 9177:         $datatable .= '</tr></table></td></tr>';
 9178:         $$rowtotal ++;
 9179:     } elsif ($position eq 'middle') {
 9180:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 9181:         my @posstypes;
 9182:         if (ref($types) eq 'ARRAY') {
 9183:             @posstypes = @{$types};
 9184:         }
 9185:         unless (grep(/^default$/,@posstypes)) {
 9186:             push(@posstypes,'default');
 9187:         }
 9188:         my %usertypeshash;
 9189:         if (ref($usertypes) eq 'HASH') {
 9190:             %usertypeshash = %{$usertypes};
 9191:         }
 9192:         $usertypeshash{'default'} = $othertitle;
 9193:         foreach my $status (@posstypes) {
 9194:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 9195:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 9196:             $$rowtotal ++;
 9197:         }
 9198:     } else {
 9199:         my %choices = &Apache::lonlocal::texthash (
 9200:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 9201:                                                   );
 9202:         my @toggles = sort(keys(%choices));
 9203:         my %defaultchecked = (
 9204:                                'cancreate_email' => 'off',
 9205:                              );
 9206:         my $customclass = 'LC_selfcreate_email';
 9207:         my $classprefix = 'LC_canmodify_emailusername_';
 9208:         my $optionsprefix = 'LC_options_emailusername_';
 9209:         my $display = 'none';
 9210:         my $rowstyle = 'display:none';
 9211:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 9212:             $display = 'block';
 9213:             $rowstyle = 'display:table-row';
 9214:         }
 9215:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 9216:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9217:                                                      \%choices,$$rowtotal,$onclick);
 9218:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 9219:                                          $rowstyle);
 9220:         $$rowtotal ++;
 9221:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 9222:                                       $rowstyle);
 9223:         $$rowtotal ++;
 9224:         my (@ordered,@posstypes,%usertypeshash);
 9225:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 9226:         my ($emailrules,$emailruleorder) =
 9227:             &Apache::lonnet::inst_userrules($dom,'email');
 9228:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9229:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9230:         if (ref($types) eq 'ARRAY') {
 9231:             @posstypes = @{$types};
 9232:         }
 9233:         if (@posstypes) {
 9234:             unless (grep(/^default$/,@posstypes)) {
 9235:                 push(@posstypes,'default');
 9236:             }
 9237:             if (ref($usertypes) eq 'HASH') {
 9238:                 %usertypeshash = %{$usertypes};
 9239:             }
 9240:             my $currassign;
 9241:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 9242:                 $currassign = {
 9243:                                   selfassign => $domdefaults{'inststatusguest'},
 9244:                               };
 9245:                 @ordered = @{$domdefaults{'inststatusguest'}};
 9246:             } else {
 9247:                 $currassign = { selfassign => [] };
 9248:             }
 9249:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 9250:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 9251:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 9252:                                          $numinrow,$othertitle,'selfassign',
 9253:                                          $rowtotal,$onclicktypes,$customclass,
 9254:                                          $rowstyle);
 9255:             $$rowtotal ++;
 9256:             $usertypeshash{'default'} = $othertitle;
 9257:             foreach my $status (@posstypes) {
 9258:                 my $css_class;
 9259:                 if ($$rowtotal%2) {
 9260:                     $css_class = 'LC_odd_row ';
 9261:                 }
 9262:                 $css_class .= $customclass;
 9263:                 my $rowid = $optionsprefix.$status;
 9264:                 my $hidden = 1;
 9265:                 my $currstyle = 'display:none';
 9266:                 if (grep(/^\Q$status\E$/,@ordered)) {
 9267:                     $currstyle = $rowstyle;
 9268:                     $hidden = 0; 
 9269:                 }
 9270:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9271:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 9272:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 9273:                 unless ($hidden) {
 9274:                     $$rowtotal ++;
 9275:                 }
 9276:             }
 9277:         } else {
 9278:             my $css_class;
 9279:             if ($$rowtotal%2) {
 9280:                 $css_class = 'LC_odd_row ';
 9281:             }
 9282:             $css_class .= $customclass;
 9283:             $usertypeshash{'default'} = $othertitle;
 9284:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9285:                                          $emailrules,$emailruleorder,$settings,'default','',
 9286:                                          $othertitle,$css_class,$rowstyle,$intdom);
 9287:             $$rowtotal ++;
 9288:         }
 9289:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 9290:         $numinrow = 1;
 9291:         if (@posstypes) {
 9292:             foreach my $status (@posstypes) {
 9293:                 my $rowid = $classprefix.$status;
 9294:                 my $datarowstyle = 'display:none';
 9295:                 if (grep(/^\Q$status\E$/,@ordered)) { 
 9296:                     $datarowstyle = $rowstyle; 
 9297:                 }
 9298:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 9299:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9300:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 9301:                 unless ($datarowstyle eq 'display:none') {
 9302:                     $$rowtotal ++;
 9303:                 }
 9304:             }
 9305:         } else {
 9306:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 9307:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9308:                                                    $infotitles,'',$customclass,$rowstyle);
 9309:         }
 9310:     }
 9311:     return $datatable;
 9312: }
 9313: 
 9314: sub selfcreate_javascript {
 9315:     return <<"ENDSCRIPT";
 9316: 
 9317: <script type="text/javascript">
 9318: // <![CDATA[
 9319: 
 9320: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 9321:     var x = document.getElementsByClassName(target);
 9322:     var insttypes = 0;
 9323:     var insttypeRegExp = new RegExp(prefix);
 9324:     if ((x.length != undefined) && (x.length > 0)) {
 9325:         if (form.elements[radio].length != undefined) {
 9326:             for (var i=0; i<form.elements[radio].length; i++) {
 9327:                 if (form.elements[radio][i].checked) {
 9328:                     if (form.elements[radio][i].value == 1) {
 9329:                         for (var j=0; j<x.length; j++) {
 9330:                             if (x[j].id == 'undefined') {
 9331:                                 x[j].style.display = 'table-row';
 9332:                             } else if (insttypeRegExp.test(x[j].id)) {
 9333:                                 insttypes ++;
 9334:                             } else {
 9335:                                 x[j].style.display = 'table-row';
 9336:                             }
 9337:                         }
 9338:                     } else {
 9339:                         for (var j=0; j<x.length; j++) {
 9340:                             x[j].style.display = 'none';
 9341:                         }
 9342:                     }
 9343:                     break;
 9344:                 }
 9345:             }
 9346:             if (insttypes > 0) {
 9347:                 toggleDataRow(form,checkbox,target,altprefix);
 9348:                 toggleDataRow(form,checkbox,target,prefix,1);
 9349:             }
 9350:         }
 9351:     }
 9352:     return;
 9353: }
 9354: 
 9355: function toggleDataRow(form,checkbox,target,prefix,docount) {
 9356:     if (form.elements[checkbox].length != undefined) {
 9357:         var count = 0;
 9358:         if (docount) {
 9359:             for (var i=0; i<form.elements[checkbox].length; i++) {
 9360:                 if (form.elements[checkbox][i].checked) {
 9361:                     count ++;
 9362:                 }
 9363:             }
 9364:         }
 9365:         for (var i=0; i<form.elements[checkbox].length; i++) {
 9366:             var type = form.elements[checkbox][i].value;
 9367:             if (document.getElementById(prefix+type)) {
 9368:                 if (form.elements[checkbox][i].checked) {
 9369:                     document.getElementById(prefix+type).style.display = 'table-row';
 9370:                     if (count % 2 == 1) {
 9371:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 9372:                     } else {
 9373:                         document.getElementById(prefix+type).className = target;
 9374:                     }
 9375:                     count ++;
 9376:                 } else {
 9377:                     document.getElementById(prefix+type).style.display = 'none';
 9378:                 }
 9379:             }
 9380:         }
 9381:     }
 9382:     return;
 9383: }
 9384: 
 9385: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 9386:     var caller = radio+'_'+status;
 9387:     if (form.elements[caller].length != undefined) {
 9388:         for (var i=0; i<form.elements[caller].length; i++) {
 9389:             if (form.elements[caller][i].checked) {
 9390:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 9391:                     var curr = form.elements[caller][i].value;
 9392:                     if (prefix) {
 9393:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 9394:                     }
 9395:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 9396:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 9397:                     if (curr == 'custom') {
 9398:                         if (prefix) { 
 9399:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 9400:                         }
 9401:                     } else if (curr == 'inst') {
 9402:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 9403:                     } else if (curr == 'noninst') {
 9404:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 9405:                     }
 9406:                     break;
 9407:                 }
 9408:             }
 9409:         }
 9410:     }
 9411: }
 9412: 
 9413: // ]]>
 9414: </script>
 9415: 
 9416: ENDSCRIPT
 9417: }
 9418: 
 9419: sub noninst_users {
 9420:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 9421:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
 9422:     my $class = 'LC_left_item';
 9423:     if ($css_class) {
 9424:         $css_class = ' class="'.$css_class.'"'; 
 9425:     }
 9426:     if ($rowid) {
 9427:         $rowid = ' id="'.$rowid.'"';
 9428:     }
 9429:     if ($rowstyle) {
 9430:         $rowstyle = ' style="'.$rowstyle.'"';
 9431:     }
 9432:     my ($output,$description);
 9433:     if ($type eq 'default') {
 9434:         $description = &mt('Requests for: [_1]',$typetitle);
 9435:     } else {
 9436:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 9437:     }
 9438:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 9439:               "<td>$description</td>\n".           
 9440:               '<td class="'.$class.'" colspan="2">'.
 9441:               '<table><tr>';
 9442:     my %headers = &Apache::lonlocal::texthash( 
 9443:               approve  => 'Processing',
 9444:               email    => 'E-mail',
 9445:               username => 'Username',
 9446:     );
 9447:     foreach my $item ('approve','email','username') {
 9448:         $output .= '<th>'.$headers{$item}.'</th>';
 9449:     }
 9450:     $output .= '</tr><tr>';
 9451:     foreach my $item ('approve','email','username') {
 9452:         $output .= '<td style="vertical-align: top">';
 9453:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 9454:         if ($item eq 'approve') {
 9455:             %choices = &Apache::lonlocal::texthash (
 9456:                                                      automatic => 'Automatically approved',
 9457:                                                      approval  => 'Queued for approval',
 9458:                                                    );
 9459:             @options = ('automatic','approval');
 9460:             $hashref = $processing;
 9461:             $defoption = 'automatic';
 9462:             $name = 'cancreate_emailprocess_'.$type;
 9463:         } elsif ($item eq 'email') {
 9464:             %choices = &Apache::lonlocal::texthash (
 9465:                                                      any     => 'Any e-mail',
 9466:                                                      inst    => 'Institutional only',
 9467:                                                      noninst => 'Non-institutional only',
 9468:                                                      custom  => 'Custom restrictions',
 9469:                                                    );
 9470:             @options = ('any','inst','noninst');
 9471:             my $showcustom;
 9472:             if (ref($emailrules) eq 'HASH') {
 9473:                 if (keys(%{$emailrules}) > 0) {
 9474:                     push(@options,'custom');
 9475:                     $showcustom = 'cancreate_emailrule';
 9476:                     if (ref($settings) eq 'HASH') {
 9477:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 9478:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 9479:                                 if (exists($emailrules->{$rule})) {
 9480:                                     $hascustom ++;
 9481:                                 }
 9482:                             }
 9483:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 9484:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 9485:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 9486:                                     if (exists($emailrules->{$rule})) {
 9487:                                         $hascustom ++;
 9488:                                     }
 9489:                                 }
 9490:                             }
 9491:                         }
 9492:                     }
 9493:                 }
 9494:             }
 9495:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 9496:                                                      "'cancreate_emaildomain','$type'".');"';
 9497:             $hashref = $emailoptions;
 9498:             $defoption = 'any';
 9499:             $name = 'cancreate_emailoptions_'.$type;
 9500:         } elsif ($item eq 'username') {
 9501:             %choices = &Apache::lonlocal::texthash (
 9502:                                                      all    => 'Same as e-mail',
 9503:                                                      first  => 'Omit @domain',
 9504:                                                      free   => 'Free to choose',
 9505:                                                    );
 9506:             @options = ('all','first','free');
 9507:             $hashref = $emailverified;
 9508:             $defoption = 'all';
 9509:             $name = 'cancreate_usernameoptions_'.$type;
 9510:         }
 9511:         foreach my $option (@options) {
 9512:             my $checked;
 9513:             if (ref($hashref) eq 'HASH') {
 9514:                 if ($type eq '') {
 9515:                     if (!exists($hashref->{'default'})) {
 9516:                         if ($option eq $defoption) {
 9517:                             $checked = ' checked="checked"';
 9518:                         }
 9519:                     } else {
 9520:                         if ($hashref->{'default'} eq $option) {
 9521:                             $checked = ' checked="checked"';
 9522:                         }
 9523:                     }
 9524:                 } else {
 9525:                     if (!exists($hashref->{$type})) {
 9526:                         if ($option eq $defoption) {
 9527:                             $checked = ' checked="checked"';
 9528:                         }
 9529:                     } else {
 9530:                         if ($hashref->{$type} eq $option) {
 9531:                             $checked = ' checked="checked"';
 9532:                         }
 9533:                     }
 9534:                 }
 9535:             } elsif (($item eq 'email') && ($hascustom)) {
 9536:                 if ($option eq 'custom') {
 9537:                     $checked = ' checked="checked"';
 9538:                 }
 9539:             } elsif ($option eq $defoption) {
 9540:                 $checked = ' checked="checked"';
 9541:             }
 9542:             $output .= '<span class="LC_nobreak"><label>'.
 9543:                        '<input type="radio" name="'.$name.'"'.
 9544:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 9545:                        $choices{$option}.'</label></span><br />';
 9546:             if ($item eq 'email') {
 9547:                 if ($option eq 'custom') {
 9548:                     my $id = 'cancreate_emailrule_'.$type;
 9549:                     my $display = 'none';
 9550:                     if ($checked) {
 9551:                         $display = 'inline';
 9552:                     }
 9553:                     my $numinrow = 2;
 9554:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 9555:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 9556:                                &user_formats_row('email',$settings,$emailrules,
 9557:                                                  $emailruleorder,$numinrow,'',$type);
 9558:                               '</table></fieldset>';
 9559:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 9560:                     my %text = &Apache::lonlocal::texthash (
 9561:                                                              inst    => 'must end:',
 9562:                                                              noninst => 'cannot end:',
 9563:                                                            );
 9564:                     my $value;
 9565:                     if (ref($emaildomain) eq 'HASH') {
 9566:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 9567:                             $value = $emaildomain->{$type}->{$option}; 
 9568:                         }
 9569:                     }
 9570:                     if ($value eq '') {
 9571:                         $value = '@'.$intdom;
 9572:                     }
 9573:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 9574:                     my $display = 'none';
 9575:                     if ($checked) {
 9576:                         $display = 'inline';
 9577:                     }
 9578:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 9579:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 9580:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 9581:                                '</div>';
 9582:                 }
 9583:             }
 9584:         }
 9585:         $output .= '</td>'."\n";
 9586:     }
 9587:     $output .= "</tr></table></td></tr>\n";
 9588:     return $output;
 9589: }
 9590: 
 9591: sub captcha_choice {
 9592:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 9593:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 9594:         $vertext,$currver);
 9595:     my %lt = &captcha_phrases();
 9596:     $keyentry = 'hidden';
 9597:     my $colspan=2;
 9598:     if ($context eq 'cancreate') {
 9599:         $rowname = &mt('CAPTCHA validation');
 9600:     } elsif ($context eq 'login') {
 9601:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 9602:     } elsif ($context eq 'passwords') {
 9603:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 9604:         $colspan=1;
 9605:     }
 9606:     if (ref($settings) eq 'HASH') {
 9607:         if ($settings->{'captcha'}) {
 9608:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 9609:         } else {
 9610:             $checked{'original'} = ' checked="checked"';
 9611:         }
 9612:         if ($settings->{'captcha'} eq 'recaptcha') {
 9613:             $pubtext = $lt{'pub'};
 9614:             $privtext = $lt{'priv'};
 9615:             $keyentry = 'text';
 9616:             $vertext = $lt{'ver'};
 9617:             $currver = $settings->{'recaptchaversion'};
 9618:             if ($currver ne '2') {
 9619:                 $currver = 1;
 9620:             }
 9621:         }
 9622:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 9623:             $currpub = $settings->{'recaptchakeys'}{'public'};
 9624:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 9625:         }
 9626:     } else {
 9627:         $checked{'original'} = ' checked="checked"';
 9628:     }
 9629:     my $css_class;
 9630:     if ($itemcount%2) {
 9631:         $css_class = 'LC_odd_row';
 9632:     }
 9633:     if ($customcss) {
 9634:         $css_class .= " $customcss";
 9635:     }
 9636:     $css_class =~ s/^\s+//;
 9637:     if ($css_class) {
 9638:         $css_class = ' class="'.$css_class.'"';
 9639:     }
 9640:     if ($rowstyle) {
 9641:         $css_class .= ' style="'.$rowstyle.'"';
 9642:     }
 9643:     my $output = '<tr'.$css_class.'>'.
 9644:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 9645:                  '<table><tr><td>'."\n";
 9646:     foreach my $option ('original','recaptcha','notused') {
 9647:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 9648:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 9649:                    $lt{$option}.'</label></span>';
 9650:         unless ($option eq 'notused') {
 9651:             $output .= ('&nbsp;'x2)."\n";
 9652:         }
 9653:     }
 9654: #
 9655: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 9656: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 9657: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 9658: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 9659: #
 9660:     $output .= '</td></tr>'."\n".
 9661:                '<tr><td class="LC_zero_height">'."\n".
 9662:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 9663:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 9664:                $currpub.'" size="40" /></span><br />'."\n".
 9665:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 9666:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 9667:                $currpriv.'" size="40" /></span><br />'.
 9668:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 9669:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 9670:                $currver.'" size="3" /></span><br />'.
 9671:                '</td></tr></table>'."\n".
 9672:                '</td></tr>';
 9673:     return $output;
 9674: }
 9675: 
 9676: sub user_formats_row {
 9677:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 9678:     my $output;
 9679:     my %text = (
 9680:                    'username' => 'new usernames',
 9681:                    'id'       => 'IDs',
 9682:                );
 9683:     unless ($type eq 'email') {
 9684:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 9685:         $output = '<tr '.$css_class.'>'.
 9686:                   '<td><span class="LC_nobreak">'.
 9687:                   &mt("Format rules to check for $text{$type}: ").
 9688:                   '</td><td class="LC_left_item" colspan="2"><table>';
 9689:     }
 9690:     my $rem;
 9691:     if (ref($ruleorder) eq 'ARRAY') {
 9692:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 9693:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 9694:                 my $rem = $i%($numinrow);
 9695:                 if ($rem == 0) {
 9696:                     if ($i > 0) {
 9697:                         $output .= '</tr>';
 9698:                     }
 9699:                     $output .= '<tr>';
 9700:                 }
 9701:                 my $check = ' ';
 9702:                 if (ref($settings) eq 'HASH') {
 9703:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 9704:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 9705:                             $check = ' checked="checked" ';
 9706:                         }
 9707:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 9708:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 9709:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 9710:                                 $check = ' checked="checked" ';
 9711:                             }
 9712:                         }
 9713:                     }
 9714:                 }
 9715:                 my $name = $type.'_rule';
 9716:                 if ($type eq 'email') {
 9717:                     $name .= '_'.$status;
 9718:                 }
 9719:                 $output .= '<td class="LC_left_item">'.
 9720:                            '<span class="LC_nobreak"><label>'.
 9721:                            '<input type="checkbox" name="'.$name.'" '.
 9722:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 9723:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 9724:             }
 9725:         }
 9726:         $rem = @{$ruleorder}%($numinrow);
 9727:     }
 9728:     my $colsleft;
 9729:     if ($rem) {
 9730:         $colsleft = $numinrow - $rem;
 9731:     }
 9732:     if ($colsleft > 1 ) {
 9733:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9734:                    '&nbsp;</td>';
 9735:     } elsif ($colsleft == 1) {
 9736:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9737:     }
 9738:     $output .= '</tr></table>';
 9739:     unless ($type eq 'email') {
 9740:         $output .= '</td></tr>';
 9741:     }
 9742:     return $output;
 9743: }
 9744: 
 9745: sub usercreation_types {
 9746:     my %lt = &Apache::lonlocal::texthash (
 9747:                     author     => 'When adding a co-author',
 9748:                     course     => 'When adding a user to a course',
 9749:                     requestcrs => 'When requesting a course',
 9750:                     any        => 'Any',
 9751:                     official   => 'Institutional only ',
 9752:                     unofficial => 'Non-institutional only',
 9753:                     none       => 'None',
 9754:     );
 9755:     return %lt;
 9756: }
 9757: 
 9758: sub selfcreation_types {
 9759:     my %lt = &Apache::lonlocal::texthash (
 9760:                     selfcreate => 'User creates own account',
 9761:                     any        => 'Any',
 9762:                     official   => 'Institutional only ',
 9763:                     unofficial => 'Non-institutional only',
 9764:                     email      => 'E-mail address',
 9765:                     login      => 'Institutional Login',
 9766:                     sso        => 'SSO',
 9767:              );
 9768: }
 9769: 
 9770: sub authtype_names {
 9771:     my %lt = &Apache::lonlocal::texthash(
 9772:                       int    => 'Internal',
 9773:                       krb4   => 'Kerberos 4',
 9774:                       krb5   => 'Kerberos 5',
 9775:                       loc    => 'Local',
 9776:                       lti    => 'LTI',
 9777:                   );
 9778:     return %lt;
 9779: }
 9780: 
 9781: sub context_names {
 9782:     my %context_title = &Apache::lonlocal::texthash(
 9783:        author => 'Creating users when an Author',
 9784:        course => 'Creating users when in a course',
 9785:        domain => 'Creating users when a Domain Coordinator',
 9786:     );
 9787:     return %context_title;
 9788: }
 9789: 
 9790: sub print_usermodification {
 9791:     my ($position,$dom,$settings,$rowtotal) = @_;
 9792:     my $numinrow = 4;
 9793:     my ($context,$datatable,$rowcount);
 9794:     if ($position eq 'top') {
 9795:         $rowcount = 0;
 9796:         $context = 'author'; 
 9797:         foreach my $role ('ca','aa') {
 9798:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9799:                                                    $numinrow,$rowcount);
 9800:             $$rowtotal ++;
 9801:             $rowcount ++;
 9802:         }
 9803:     } elsif ($position eq 'bottom') {
 9804:         $context = 'course';
 9805:         $rowcount = 0;
 9806:         foreach my $role ('st','ep','ta','in','cr') {
 9807:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9808:                                                    $numinrow,$rowcount);
 9809:             $$rowtotal ++;
 9810:             $rowcount ++;
 9811:         }
 9812:     }
 9813:     return $datatable;
 9814: }
 9815: 
 9816: sub print_defaults {
 9817:     my ($position,$dom,$settings,$rowtotal) = @_;
 9818:     my $rownum = 0;
 9819:     my ($datatable,$css_class,$titles);
 9820:     unless ($position eq 'bottom') {
 9821:         $titles = &defaults_titles($dom);
 9822:     }
 9823:     if ($position eq 'top') {
 9824:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 9825:                      'datelocale_def','portal_def');
 9826:         my %defaults;
 9827:         if (ref($settings) eq 'HASH') {
 9828:             %defaults = %{$settings};
 9829:         } else {
 9830:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9831:             foreach my $item (@items) {
 9832:                 $defaults{$item} = $domdefaults{$item};
 9833:             }
 9834:         }
 9835:         foreach my $item (@items) {
 9836:             if ($rownum%2) {
 9837:                 $css_class = '';
 9838:             } else {
 9839:                 $css_class = ' class="LC_odd_row" ';
 9840:             }
 9841:             $datatable .= '<tr'.$css_class.'>'.
 9842:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 9843:                           '</span></td><td class="LC_right_item" colspan="3">';
 9844:             if ($item eq 'auth_def') {
 9845:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
 9846:                 my %shortauth = (
 9847:                                  internal => 'int',
 9848:                                  krb4 => 'krb4',
 9849:                                  krb5 => 'krb5',
 9850:                                  localauth  => 'loc',
 9851:                                  lti => 'lti',
 9852:                                 );
 9853:                 my %authnames = &authtype_names();
 9854:                 foreach my $auth (@authtypes) {
 9855:                     my $checked = ' ';
 9856:                     if ($defaults{$item} eq $auth) {
 9857:                         $checked = ' checked="checked" ';
 9858:                     }
 9859:                     $datatable .= '<label><input type="radio" name="'.$item.
 9860:                                   '" value="'.$auth.'"'.$checked.'/>'.
 9861:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 9862:                 }
 9863:             } elsif ($item eq 'timezone_def') {
 9864:                 my $includeempty = 1;
 9865:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 9866:             } elsif ($item eq 'datelocale_def') {
 9867:                 my $includeempty = 1;
 9868:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 9869:             } elsif ($item eq 'lang_def') {
 9870:                 my $includeempty = 1;
 9871:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 9872:             } else {
 9873:                 my $size;
 9874:                 if ($item eq 'portal_def') {
 9875:                     $size = ' size="25"';
 9876:                 }
 9877:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 9878:                               $defaults{$item}.'"'.$size.' />';
 9879:             }
 9880:             $datatable .= '</td></tr>';
 9881:             $rownum ++;
 9882:         }
 9883:     } else {
 9884:         my %defaults;
 9885:         if (ref($settings) eq 'HASH') {
 9886:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9887:                 my $maxnum = @{$settings->{'inststatusorder'}};
 9888:                 for (my $i=0; $i<$maxnum; $i++) {
 9889:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 9890:                     my $item = $settings->{'inststatusorder'}->[$i];
 9891:                     my $title = $settings->{'inststatustypes'}->{$item};
 9892:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 9893:                     $datatable .= '<tr'.$css_class.'>'.
 9894:                                   '<td><span class="LC_nobreak">'.
 9895:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 9896:                     for (my $k=0; $k<=$maxnum; $k++) {
 9897:                         my $vpos = $k+1;
 9898:                         my $selstr;
 9899:                         if ($k == $i) {
 9900:                             $selstr = ' selected="selected" ';
 9901:                         }
 9902:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9903:                     }
 9904:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 9905:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 9906:                                   &mt('delete').'</span></td>'.
 9907:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 9908:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 9909:                                   '</span></td></tr>';
 9910:                 }
 9911:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 9912:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 9913:                 $datatable .= '<tr '.$css_class.'>'.
 9914:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 9915:                 for (my $k=0; $k<=$maxnum; $k++) {
 9916:                     my $vpos = $k+1;
 9917:                     my $selstr;
 9918:                     if ($k == $maxnum) {
 9919:                         $selstr = ' selected="selected" ';
 9920:                     }
 9921:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9922:                 }
 9923:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 9924:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 9925:                               '&nbsp;'.&mt('(new)').
 9926:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
 9927:                               &mt('Name displayed').':'.
 9928:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 9929:                               '</tr>'."\n";
 9930:                 $rownum ++;
 9931:             }
 9932:         }
 9933:     }
 9934:     $$rowtotal += $rownum;
 9935:     return $datatable;
 9936: }
 9937: 
 9938: sub get_languages_hash {
 9939:     my %langchoices;
 9940:     foreach my $id (&Apache::loncommon::languageids()) {
 9941:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 9942:         if ($code ne '') {
 9943:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 9944:         }
 9945:     }
 9946:     return %langchoices;
 9947: }
 9948: 
 9949: sub defaults_titles {
 9950:     my ($dom) = @_;
 9951:     my %titles = &Apache::lonlocal::texthash (
 9952:                    'auth_def'      => 'Default authentication type',
 9953:                    'auth_arg_def'  => 'Default authentication argument',
 9954:                    'lang_def'      => 'Default language',
 9955:                    'timezone_def'  => 'Default timezone',
 9956:                    'datelocale_def' => 'Default locale for dates',
 9957:                    'portal_def'     => 'Portal/Default URL',
 9958:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 9959:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 9960:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 9961:                  );
 9962:     if ($dom) {
 9963:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 9964:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 9965:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 9966:         $protocol = 'http' if ($protocol ne 'https');
 9967:         if ($uint_dom) {
 9968:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 9969:                                          $uint_dom);
 9970:         }
 9971:     }
 9972:     return (\%titles);
 9973: }
 9974: 
 9975: sub print_scantron {
 9976:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 9977:     if ($position eq 'top') {
 9978:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 9979:     } else {
 9980:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 9981:     }
 9982: }
 9983: 
 9984: sub scantron_javascript {
 9985:     return <<"ENDSCRIPT";
 9986: 
 9987: <script type="text/javascript">
 9988: // <![CDATA[
 9989: 
 9990: function toggleScantron(form) {
 9991:     var csvfieldset = new Array();
 9992:     if (document.getElementById('scantroncsv_cols')) {
 9993:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 9994:     }
 9995:     if (document.getElementById('scantroncsv_options')) {
 9996:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 9997:     }
 9998:     if (csvfieldset.length) {
 9999:         if (document.getElementById('scantronconfcsv')) {
10000:             var scantroncsv = document.getElementById('scantronconfcsv');
10001:             if (scantroncsv.checked) {
10002:                 for (var i=0; i<csvfieldset.length; i++) {
10003:                     csvfieldset[i].style.display = 'block';
10004:                 }
10005:             } else {
10006:                 for (var i=0; i<csvfieldset.length; i++) {
10007:                     csvfieldset[i].style.display = 'none';
10008:                 }
10009:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
10010:                 if (csvselects.length) {
10011:                     for (var j=0; j<csvselects.length; j++) {
10012:                         csvselects[j].selectedIndex = 0;
10013:                     }
10014:                 }
10015:             }
10016:         }
10017:     }
10018:     return;
10019: }
10020: // ]]>
10021: </script>
10022: 
10023: ENDSCRIPT
10024: 
10025: }
10026: 
10027: sub print_scantronformat {
10028:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10029:     my $itemcount = 1;
10030:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10031:         %confhash);
10032:     my $switchserver = &check_switchserver($dom,$confname);
10033:     my %lt = &Apache::lonlocal::texthash (
10034:                 default => 'Default bubblesheet format file error',
10035:                 custom  => 'Custom bubblesheet format file error',
10036:              );
10037:     my %scantronfiles = (
10038:         default => 'default.tab',
10039:         custom => 'custom.tab',
10040:     );
10041:     foreach my $key (keys(%scantronfiles)) {
10042:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10043:                               .$scantronfiles{$key};
10044:     }
10045:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10046:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10047:         if (!$switchserver) {
10048:             my $servadm = $r->dir_config('lonAdmEMail');
10049:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10050:             if ($configuserok eq 'ok') {
10051:                 if ($author_ok eq 'ok') {
10052:                     my %legacyfile = (
10053:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10054:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10055:                     );
10056:                     my %md5chk;
10057:                     foreach my $type (keys(%legacyfile)) {
10058:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10059:                         chomp($md5chk{$type});
10060:                     }
10061:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10062:                         foreach my $type (keys(%legacyfile)) {
10063:                             ($scantronurls{$type},my $error) =
10064:                                 &legacy_scantronformat($r,$dom,$confname,
10065:                                                  $type,$legacyfile{$type},
10066:                                                  $scantronurls{$type},
10067:                                                  $scantronfiles{$type});
10068:                             if ($error ne '') {
10069:                                 $error{$type} = $error;
10070:                             }
10071:                         }
10072:                         if (keys(%error) == 0) {
10073:                             $is_custom = 1;
10074:                             $confhash{'scantron'}{'scantronformat'} =
10075:                                 $scantronurls{'custom'};
10076:                             my $putresult =
10077:                                 &Apache::lonnet::put_dom('configuration',
10078:                                                          \%confhash,$dom);
10079:                             if ($putresult ne 'ok') {
10080:                                 $error{'custom'} =
10081:                                     '<span class="LC_error">'.
10082:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10083:                             }
10084:                         }
10085:                     } else {
10086:                         ($scantronurls{'default'},my $error) =
10087:                             &legacy_scantronformat($r,$dom,$confname,
10088:                                           'default',$legacyfile{'default'},
10089:                                           $scantronurls{'default'},
10090:                                           $scantronfiles{'default'});
10091:                         if ($error eq '') {
10092:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10093:                             my $putresult =
10094:                                 &Apache::lonnet::put_dom('configuration',
10095:                                                          \%confhash,$dom);
10096:                             if ($putresult ne 'ok') {
10097:                                 $error{'default'} =
10098:                                     '<span class="LC_error">'.
10099:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10100:                             }
10101:                         } else {
10102:                             $error{'default'} = $error;
10103:                         }
10104:                     }
10105:                 }
10106:             }
10107:         } else {
10108:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10109:         }
10110:     }
10111:     if (ref($settings) eq 'HASH') {
10112:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10113:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10114:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10115:                 $scantronurl = '';
10116:             } else {
10117:                 $scantronurl = $settings->{'scantronformat'};
10118:             }
10119:             $is_custom = 1;
10120:         } else {
10121:             $scantronurl = $scantronurls{'default'};
10122:         }
10123:     } else {
10124:         if ($is_custom) {
10125:             $scantronurl = $scantronurls{'custom'};
10126:         } else {
10127:             $scantronurl = $scantronurls{'default'};
10128:         }
10129:     }
10130:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10131:     $datatable .= '<tr'.$css_class.'>';
10132:     if (!$is_custom) {
10133:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
10134:                       '<span class="LC_nobreak">';
10135:         if ($scantronurl) {
10136:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
10137:                                                          undef,undef,undef,undef,'background-color:#ffffff');
10138:         } else {
10139:             $datatable = &mt('File unavailable for display');
10140:         }
10141:         $datatable .= '</span></td>';
10142:         if (keys(%error) == 0) { 
10143:             $datatable .= '<td style="vertical-align: bottom">';
10144:             if (!$switchserver) {
10145:                 $datatable .= &mt('Upload:').'<br />';
10146:             }
10147:         } else {
10148:             my $errorstr;
10149:             foreach my $key (sort(keys(%error))) {
10150:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10151:             }
10152:             $datatable .= '<td>'.$errorstr;
10153:         }
10154:     } else {
10155:         if (keys(%error) > 0) {
10156:             my $errorstr;
10157:             foreach my $key (sort(keys(%error))) {
10158:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10159:             } 
10160:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
10161:         } elsif ($scantronurl) {
10162:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
10163:                                                        undef,undef,undef,undef,'background-color:#ffffff');
10164:             $datatable .= '<td><span class="LC_nobreak">'.
10165:                           $link.
10166:                           '<label><input type="checkbox" name="scantronformat_del"'.
10167:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
10168:                           '<td><span class="LC_nobreak">&nbsp;'.
10169:                           &mt('Replace:').'</span><br />';
10170:         }
10171:     }
10172:     if (keys(%error) == 0) {
10173:         if ($switchserver) {
10174:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
10175:         } else {
10176:             $datatable .='<span class="LC_nobreak">&nbsp;'.
10177:                          '<input type="file" name="scantronformat" /></span>';
10178:         }
10179:     }
10180:     $datatable .= '</td></tr>';
10181:     $$rowtotal ++;
10182:     return $datatable;
10183: }
10184: 
10185: sub legacy_scantronformat {
10186:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
10187:     my ($url,$error);
10188:     my @statinfo = &Apache::lonnet::stat_file($newurl);
10189:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
10190:         (my $result,$url) =
10191:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
10192:                          '','',$newfile);
10193:         if ($result ne 'ok') {
10194:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
10195:         }
10196:     }
10197:     return ($url,$error);
10198: }
10199: 
10200: sub print_scantronconfig {
10201:     my ($dom,$settings,$rowtotal) = @_;
10202:     my $itemcount = 2;
10203:     my $is_checked = ' checked="checked"';
10204:     my %optionson = (
10205:                      hdr => ' checked="checked"',
10206:                      pad => ' checked="checked"',
10207:                      rem => ' checked="checked"',
10208:                     );
10209:     my %optionsoff = (
10210:                       hdr => '',
10211:                       pad => '',
10212:                       rem => '',
10213:                      );
10214:     my $currcsvsty = 'none';
10215:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
10216:     my @fields = &scantroncsv_fields();
10217:     my %titles = &scantronconfig_titles();
10218:     if (ref($settings) eq 'HASH') {
10219:         if (ref($settings->{config}) eq 'HASH') {
10220:             if ($settings->{config}->{dat}) {
10221:                 $checked{'dat'} = $is_checked;
10222:             }
10223:             if (ref($settings->{config}->{csv}) eq 'HASH') {
10224:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
10225:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
10226:                     if (keys(%csvfields) > 0) {
10227:                         $checked{'csv'} = $is_checked;
10228:                         $currcsvsty = 'block';
10229:                     }
10230:                 }
10231:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
10232:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
10233:                     foreach my $option (keys(%optionson)) {
10234:                         unless ($csvoptions{$option}) {
10235:                             $optionsoff{$option} = $optionson{$option};
10236:                             $optionson{$option} = '';
10237:                         }
10238:                     }
10239:                 }
10240:             }
10241:         } else {
10242:             $checked{'dat'} = $is_checked;
10243:         }
10244:     } else {
10245:         $checked{'dat'} = $is_checked;
10246:     }
10247:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
10248:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10249:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
10250:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
10251:     foreach my $item ('dat','csv') {
10252:         my $id;
10253:         if ($item eq 'csv') {
10254:             $id = 'id="scantronconfcsv" ';
10255:         }
10256:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
10257:                       $titles{$item}.'</label>'.('&nbsp;'x3);
10258:         if ($item eq 'csv') {
10259:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
10260:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
10261:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
10262:             foreach my $col (@fields) {
10263:                 my $selnone;
10264:                 if ($csvfields{$col} eq '') {
10265:                     $selnone = ' selected="selected"';
10266:                 }
10267:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
10268:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
10269:                               '<option value=""'.$selnone.'></option>';
10270:                 for (my $i=0; $i<20; $i++) {
10271:                     my $shown = $i+1;
10272:                     my $sel;
10273:                     unless ($selnone) {
10274:                         if (exists($csvfields{$col})) {
10275:                             if ($csvfields{$col} == $i) {
10276:                                 $sel = ' selected="selected"';
10277:                             }
10278:                         }
10279:                     }
10280:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
10281:                 }
10282:                 $datatable .= '</select></td></tr>';
10283:            }
10284:            $datatable .= '</table></fieldset>'.
10285:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
10286:                          '<legend>'.&mt('CSV Options').'</legend>';
10287:            foreach my $option ('hdr','pad','rem') {
10288:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
10289:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
10290:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
10291:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
10292:            }
10293:            $datatable .= '</fieldset>';
10294:            $itemcount ++;
10295:         }
10296:     }
10297:     $datatable .= '</td></tr>';
10298:     $$rowtotal ++;
10299:     return $datatable;
10300: }
10301: 
10302: sub scantronconfig_titles {
10303:     return &Apache::lonlocal::texthash(
10304:                                           dat => 'Standard format (.dat)',
10305:                                           csv => 'Comma separated values (.csv)',
10306:                                           hdr => 'Remove first line in file (contains column titles)',
10307:                                           pad => 'Prepend 0s to PaperID',
10308:                                           rem => 'Remove leading spaces (except Question Response columns)',
10309:                                           CODE => 'CODE',
10310:                                           ID   => 'Student ID',
10311:                                           PaperID => 'Paper ID',
10312:                                           FirstName => 'First Name',
10313:                                           LastName => 'Last Name',
10314:                                           FirstQuestion => 'First Question Response',
10315:                                           Section => 'Section',
10316:     );
10317: }
10318: 
10319: sub scantroncsv_fields {
10320:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
10321: }
10322: 
10323: sub print_coursecategories {
10324:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
10325:     my $datatable;
10326:     if ($position eq 'top') {
10327:         my (%checked);
10328:         my @catitems = ('unauth','auth');
10329:         my @cattypes = ('std','domonly','codesrch','none');
10330:         $checked{'unauth'} = 'std';
10331:         $checked{'auth'} = 'std';
10332:         if (ref($settings) eq 'HASH') {
10333:             foreach my $type (@cattypes) {
10334:                 if ($type eq $settings->{'unauth'}) {
10335:                     $checked{'unauth'} = $type;
10336:                 }
10337:                 if ($type eq $settings->{'auth'}) {
10338:                     $checked{'auth'} = $type;
10339:                 }
10340:             }
10341:         }
10342:         my %lt = &Apache::lonlocal::texthash (
10343:                                                unauth   => 'Catalog type for unauthenticated users',
10344:                                                auth     => 'Catalog type for authenticated users',
10345:                                                none     => 'No catalog',
10346:                                                std      => 'Standard catalog',
10347:                                                domonly  => 'Domain-only catalog',
10348:                                                codesrch => "Code search form",
10349:                                              );
10350:        my $itemcount = 0;
10351:        foreach my $item (@catitems) {
10352:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10353:            $datatable .= '<tr '.$css_class.'>'.
10354:                          '<td>'.$lt{$item}.'</td>'.
10355:                          '<td class="LC_right_item"><span class="LC_nobreak">';
10356:            foreach my $type (@cattypes) {
10357:                my $ischecked;
10358:                if ($checked{$item} eq $type) {
10359:                    $ischecked=' checked="checked"';
10360:                }
10361:                $datatable .= '<label>'.
10362:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
10363:                              ' />'.$lt{$type}.'</label>&nbsp;';
10364:            }
10365:            $datatable .= '</span></td></tr>';
10366:            $itemcount ++;
10367:         }
10368:         $$rowtotal += $itemcount;
10369:     } elsif ($position eq 'middle') {
10370:         my $toggle_cats_crs = ' ';
10371:         my $toggle_cats_dom = ' checked="checked" ';
10372:         my $can_cat_crs = ' ';
10373:         my $can_cat_dom = ' checked="checked" ';
10374:         my $toggle_catscomm_comm = ' ';
10375:         my $toggle_catscomm_dom = ' checked="checked" ';
10376:         my $can_catcomm_comm = ' ';
10377:         my $can_catcomm_dom = ' checked="checked" ';
10378:         my $toggle_catsplace_place = ' ';
10379:         my $toggle_catsplace_dom = ' checked="checked" ';
10380:         my $can_catplace_place = ' ';
10381:         my $can_catplace_dom = ' checked="checked" ';
10382: 
10383:         if (ref($settings) eq 'HASH') {
10384:             if ($settings->{'togglecats'} eq 'crs') {
10385:                 $toggle_cats_crs = $toggle_cats_dom;
10386:                 $toggle_cats_dom = ' ';
10387:             }
10388:             if ($settings->{'categorize'} eq 'crs') {
10389:                 $can_cat_crs = $can_cat_dom;
10390:                 $can_cat_dom = ' ';
10391:             }
10392:             if ($settings->{'togglecatscomm'} eq 'comm') {
10393:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
10394:                 $toggle_catscomm_dom = ' ';
10395:             }
10396:             if ($settings->{'categorizecomm'} eq 'comm') {
10397:                 $can_catcomm_comm = $can_catcomm_dom;
10398:                 $can_catcomm_dom = ' ';
10399:             }
10400:             if ($settings->{'togglecatsplace'} eq 'place') {
10401:                 $toggle_catsplace_place = $toggle_catsplace_dom;
10402:                 $toggle_catsplace_dom = ' ';
10403:             }
10404:             if ($settings->{'categorizeplace'} eq 'place') {
10405:                 $can_catplace_place = $can_catplace_dom;
10406:                 $can_catplace_dom = ' ';
10407:             }
10408:         }
10409:         my %title = &Apache::lonlocal::texthash (
10410:                      togglecats      => 'Show/Hide a course in catalog',
10411:                      togglecatscomm  => 'Show/Hide a community in catalog',
10412:                      togglecatsplace => 'Show/Hide a placement test in catalog',
10413:                      categorize      => 'Assign a category to a course',
10414:                      categorizecomm  => 'Assign a category to a community',
10415:                      categorizeplace => 'Assign a category to a placement test',
10416:                     );
10417:         my %level = &Apache::lonlocal::texthash (
10418:                      dom   => 'Set in Domain',
10419:                      crs   => 'Set in Course',
10420:                      comm  => 'Set in Community',
10421:                      place => 'Set in Placement Test',
10422:                     );
10423:         $datatable = '<tr class="LC_odd_row">'.
10424:                   '<td>'.$title{'togglecats'}.'</td>'.
10425:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10426:                   '<input type="radio" name="togglecats"'.
10427:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10428:                   '<label><input type="radio" name="togglecats"'.
10429:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
10430:                   '</tr><tr>'.
10431:                   '<td>'.$title{'categorize'}.'</td>'.
10432:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10433:                   '<label><input type="radio" name="categorize"'.
10434:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10435:                   '<label><input type="radio" name="categorize"'.
10436:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
10437:                   '</tr><tr class="LC_odd_row">'.
10438:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
10439:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10440:                   '<input type="radio" name="togglecatscomm"'.
10441:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10442:                   '<label><input type="radio" name="togglecatscomm"'.
10443:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
10444:                   '</tr><tr>'.
10445:                   '<td>'.$title{'categorizecomm'}.'</td>'.
10446:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10447:                   '<label><input type="radio" name="categorizecomm"'.
10448:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10449:                   '<label><input type="radio" name="categorizecomm"'.
10450:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
10451:                   '</tr><tr class="LC_odd_row">'.
10452:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
10453:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10454:                   '<input type="radio" name="togglecatsplace"'.
10455:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10456:                   '<label><input type="radio" name="togglecatscomm"'.
10457:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
10458:                   '</tr><tr>'.
10459:                   '<td>'.$title{'categorizeplace'}.'</td>'.
10460:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10461:                   '<label><input type="radio" name="categorizeplace"'.
10462:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10463:                   '<label><input type="radio" name="categorizeplace"'.
10464:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
10465:                   '</tr>';
10466:         $$rowtotal += 6;
10467:     } else {
10468:         my $css_class;
10469:         my $itemcount = 1;
10470:         my $cathash; 
10471:         if (ref($settings) eq 'HASH') {
10472:             $cathash = $settings->{'cats'};
10473:         }
10474:         if (ref($cathash) eq 'HASH') {
10475:             my (@cats,@trails,%allitems,%idx,@jsarray);
10476:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
10477:                                                    \%allitems,\%idx,\@jsarray);
10478:             my $maxdepth = scalar(@cats);
10479:             my $colattrib = '';
10480:             if ($maxdepth > 2) {
10481:                 $colattrib = ' colspan="2" ';
10482:             }
10483:             my @path;
10484:             if (@cats > 0) {
10485:                 if (ref($cats[0]) eq 'ARRAY') {
10486:                     my $numtop = @{$cats[0]};
10487:                     my $maxnum = $numtop;
10488:                     my %default_names = (
10489:                           instcode    => &mt('Official courses'),
10490:                           communities => &mt('Communities'),
10491:                           placement   => &mt('Placement Tests'),
10492:                     );
10493: 
10494:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
10495:                         ($cathash->{'instcode::0'} eq '') ||
10496:                         (!grep(/^communities$/,@{$cats[0]})) || 
10497:                         ($cathash->{'communities::0'} eq '') ||
10498:                         (!grep(/^placement$/,@{$cats[0]})) ||
10499:                         ($cathash->{'placement::0'} eq '')) {
10500:                         $maxnum ++;
10501:                     }
10502:                     my $lastidx;
10503:                     for (my $i=0; $i<$numtop; $i++) {
10504:                         my $parent = $cats[0][$i];
10505:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10506:                         my $item = &escape($parent).'::0';
10507:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
10508:                         $lastidx = $idx{$item};
10509:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10510:                                       .'<select name="'.$item.'"'.$chgstr.'>';
10511:                         for (my $k=0; $k<=$maxnum; $k++) {
10512:                             my $vpos = $k+1;
10513:                             my $selstr;
10514:                             if ($k == $i) {
10515:                                 $selstr = ' selected="selected" ';
10516:                             }
10517:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10518:                         }
10519:                         $datatable .= '</select></span></td><td>';
10520:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
10521:                             $datatable .=  '<span class="LC_nobreak">'
10522:                                            .$default_names{$parent}.'</span>';
10523:                             if ($parent eq 'instcode') {
10524:                                 $datatable .= '<br /><span class="LC_nobreak">('
10525:                                               .&mt('with institutional codes')
10526:                                               .')</span></td><td'.$colattrib.'>';
10527:                             } else {
10528:                                 $datatable .= '<table><tr><td>';
10529:                             }
10530:                             $datatable .= '<span class="LC_nobreak">'
10531:                                           .'<label><input type="radio" name="'
10532:                                           .$parent.'" value="1" checked="checked" />'
10533:                                           .&mt('Display').'</label>';
10534:                             if ($parent eq 'instcode') {
10535:                                 $datatable .= '&nbsp;';
10536:                             } else {
10537:                                 $datatable .= '</span></td></tr><tr><td>'
10538:                                               .'<span class="LC_nobreak">';
10539:                             }
10540:                             $datatable .= '<label><input type="radio" name="'
10541:                                           .$parent.'" value="0" />'
10542:                                           .&mt('Do not display').'</label></span>';
10543:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
10544:                                 $datatable .= '</td></tr></table>';
10545:                             }
10546:                             $datatable .= '</td>';
10547:                         } else {
10548:                             $datatable .= $parent
10549:                                           .'&nbsp;<span class="LC_nobreak"><label>'
10550:                                           .'<input type="checkbox" name="deletecategory" '
10551:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
10552:                         }
10553:                         my $depth = 1;
10554:                         push(@path,$parent);
10555:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
10556:                         pop(@path);
10557:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10558:                         $itemcount ++;
10559:                     }
10560:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10561:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
10562:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
10563:                     for (my $k=0; $k<=$maxnum; $k++) {
10564:                         my $vpos = $k+1;
10565:                         my $selstr;
10566:                         if ($k == $numtop) {
10567:                             $selstr = ' selected="selected" ';
10568:                         }
10569:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10570:                     }
10571:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
10572:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
10573:                                   .'</tr>'."\n";
10574:                     $itemcount ++;
10575:                     foreach my $default ('instcode','communities','placement') {
10576:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
10577:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
10578:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
10579:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
10580:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
10581:                             for (my $k=0; $k<=$maxnum; $k++) {
10582:                                 my $vpos = $k+1;
10583:                                 my $selstr;
10584:                                 if ($k == $maxnum) {
10585:                                     $selstr = ' selected="selected" ';
10586:                                 }
10587:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10588:                             }
10589:                             $datatable .= '</select></span></td>'.
10590:                                           '<td><span class="LC_nobreak">'.
10591:                                           $default_names{$default}.'</span>';
10592:                             if ($default eq 'instcode') {
10593:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
10594:                                               .&mt('with institutional codes').')</span>';
10595:                             }
10596:                             $datatable .= '</td>'
10597:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
10598:                                           .&mt('Display').'</label>&nbsp;'
10599:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
10600:                                           .&mt('Do not display').'</label></span></td></tr>';
10601:                         }
10602:                     }
10603:                 }
10604:             } else {
10605:                 $datatable .= &initialize_categories($itemcount);
10606:             }
10607:         } else {
10608:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
10609:                           .&initialize_categories($itemcount);
10610:         }
10611:         $$rowtotal += $itemcount;
10612:     }
10613:     return $datatable;
10614: }
10615: 
10616: sub print_serverstatuses {
10617:     my ($dom,$settings,$rowtotal) = @_;
10618:     my $datatable;
10619:     my @pages = &serverstatus_pages();
10620:     my (%namedaccess,%machineaccess);
10621:     foreach my $type (@pages) {
10622:         $namedaccess{$type} = '';
10623:         $machineaccess{$type}= '';
10624:     }
10625:     if (ref($settings) eq 'HASH') {
10626:         foreach my $type (@pages) {
10627:             if (exists($settings->{$type})) {
10628:                 if (ref($settings->{$type}) eq 'HASH') {
10629:                     foreach my $key (keys(%{$settings->{$type}})) {
10630:                         if ($key eq 'namedusers') {
10631:                             $namedaccess{$type} = $settings->{$type}->{$key};
10632:                         } elsif ($key eq 'machines') {
10633:                             $machineaccess{$type} = $settings->{$type}->{$key};
10634:                         }
10635:                     }
10636:                 }
10637:             }
10638:         }
10639:     }
10640:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
10641:     my $rownum = 0;
10642:     my $css_class;
10643:     foreach my $type (@pages) {
10644:         $rownum ++;
10645:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10646:         $datatable .= '<tr'.$css_class.'>'.
10647:                       '<td><span class="LC_nobreak">'.
10648:                       $titles->{$type}.'</span></td>'.
10649:                       '<td class="LC_left_item">'.
10650:                       '<input type="text" name="'.$type.'_namedusers" '.
10651:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
10652:                       '<td class="LC_right_item">'.
10653:                       '<span class="LC_nobreak">'.
10654:                       '<input type="text" name="'.$type.'_machines" '.
10655:                       'value="'.$machineaccess{$type}.'" size="10" />'.
10656:                       '</span></td></tr>'."\n";
10657:     }
10658:     $$rowtotal += $rownum;
10659:     return $datatable;
10660: }
10661: 
10662: sub serverstatus_pages {
10663:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
10664:             'checksums','clusterstatus','certstatus','metadata_keywords',
10665:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
10666:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
10667: }
10668: 
10669: sub defaults_javascript {
10670:     my ($settings) = @_;
10671:     return unless (ref($settings) eq 'HASH');
10672:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10673:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
10674:         if ($maxnum eq '') {
10675:             $maxnum = 0;
10676:         }
10677:         $maxnum ++;
10678:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
10679:         return <<"ENDSCRIPT";
10680: <script type="text/javascript">
10681: // <![CDATA[
10682: function reorderTypes(form,caller) {
10683:     var changedVal;
10684: $jstext 
10685:     var newpos = 'addinststatus_pos';
10686:     var current = new Array;
10687:     var maxh = $maxnum;
10688:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10689:     var oldVal;
10690:     if (caller == newpos) {
10691:         changedVal = newitemVal;
10692:     } else {
10693:         var curritem = 'inststatus_pos_'+caller;
10694:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
10695:         current[newitemVal] = newpos;
10696:     }
10697:     for (var i=0; i<inststatuses.length; i++) {
10698:         if (inststatuses[i] != caller) {
10699:             var elementName = 'inststatus_pos_'+inststatuses[i];
10700:             if (form.elements[elementName]) {
10701:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10702:                 current[currVal] = elementName;
10703:             }
10704:         }
10705:     }
10706:     for (var j=0; j<maxh; j++) {
10707:         if (current[j] == undefined) {
10708:             oldVal = j;
10709:         }
10710:     }
10711:     if (oldVal < changedVal) {
10712:         for (var k=oldVal+1; k<=changedVal ; k++) {
10713:            var elementName = current[k];
10714:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10715:         }
10716:     } else {
10717:         for (var k=changedVal; k<oldVal; k++) {
10718:             var elementName = current[k];
10719:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10720:         }
10721:     }
10722:     return;
10723: }
10724: 
10725: // ]]>
10726: </script>
10727: 
10728: ENDSCRIPT
10729:     }
10730:     return;
10731: }
10732: 
10733: sub passwords_javascript {
10734:     my %intalert = &Apache::lonlocal::texthash (
10735:         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.',
10736:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
10737:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
10738:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
10739:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
10740:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
10741:     );
10742:     &js_escape(\%intalert);
10743:     my $defmin = $Apache::lonnet::passwdmin;
10744:     my $intauthjs = <<"ENDSCRIPT";
10745: 
10746: function warnIntAuth(field) {
10747:     if (field.name == 'intauth_check') {
10748:         if (field.value == '2') {
10749:             alert('$intalert{authcheck}');
10750:         }
10751:     }
10752:     if (field.name == 'intauth_cost') {
10753:         field.value.replace(/\s/g,'');
10754:         if (field.value != '') {
10755:             var regexdigit=/^\\d+\$/;
10756:             if (!regexdigit.test(field.value)) {
10757:                 alert('$intalert{authcost}');
10758:             }
10759:         }
10760:     }
10761:     return;
10762: }
10763: 
10764: function warnIntPass(field) {
10765:     field.value.replace(/^\s+/,'');
10766:     field.value.replace(/\s+\$/,'');
10767:     var regexdigit=/^\\d+\$/;
10768:     if (field.name == 'passwords_min') {
10769:         if (field.value == '') {
10770:             alert('$intalert{passmin}');
10771:             field.value = '$defmin';
10772:         } else {
10773:             if (!regexdigit.test(field.value)) {
10774:                 alert('$intalert{passmin}');
10775:                 field.value = '$defmin';
10776:             }
10777:             var minval = parseInt(field.value,10);
10778:             if (minval < $defmin) {
10779:                 alert('$intalert{passmin}');
10780:                 field.value = '$defmin';
10781:             }
10782:         }
10783:     } else {
10784:         if (field.value == '0') {
10785:             field.value = '';
10786:         }
10787:         if (field.value != '') {
10788:             if (field.name == 'passwords_expire') {
10789:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
10790:                 if (!regexpposnum.test(field.value)) {
10791:                     alert('$intalert{passexp}');
10792:                     field.value = '';
10793:                 } else {
10794:                     var expval = parseFloat(field.value);
10795:                     if (expval == 0) {
10796:                         alert('$intalert{passexp}');
10797:                         field.value = '';
10798:                     }
10799:                 }
10800:             } else {
10801:                 if (!regexdigit.test(field.value)) {
10802:                     if (field.name == 'passwords_max') {
10803:                         alert('$intalert{passmax}');
10804:                     } else {
10805:                         if (field.name == 'passwords_numsaved') {
10806:                             alert('$intalert{passnum}');
10807:                         }
10808:                     }
10809:                     field.value = '';
10810:                 }
10811:             }
10812:         }
10813:     }
10814:     return;
10815: }
10816: 
10817: ENDSCRIPT
10818:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
10819: }
10820: 
10821: sub coursecategories_javascript {
10822:     my ($settings) = @_;
10823:     my ($output,$jstext,$cathash);
10824:     if (ref($settings) eq 'HASH') {
10825:         $cathash = $settings->{'cats'};
10826:     }
10827:     if (ref($cathash) eq 'HASH') {
10828:         my (@cats,@jsarray,%idx);
10829:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
10830:         if (@jsarray > 0) {
10831:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
10832:             for (my $i=0; $i<@jsarray; $i++) {
10833:                 if (ref($jsarray[$i]) eq 'ARRAY') {
10834:                     my $catstr = join('","',@{$jsarray[$i]});
10835:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
10836:                 }
10837:             }
10838:         }
10839:     } else {
10840:         $jstext  = '    var categories = Array(1);'."\n".
10841:                    '    categories[0] = Array("instcode_pos");'."\n"; 
10842:     }
10843:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
10844:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
10845:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
10846:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
10847:     &js_escape(\$instcode_reserved);
10848:     &js_escape(\$communities_reserved);
10849:     &js_escape(\$placement_reserved);
10850:     &js_escape(\$choose_again);
10851:     $output = <<"ENDSCRIPT";
10852: <script type="text/javascript">
10853: // <![CDATA[
10854: function reorderCats(form,parent,item,idx) {
10855:     var changedVal;
10856: $jstext
10857:     var newpos = 'addcategory_pos';
10858:     if (parent == '') {
10859:         var has_instcode = 0;
10860:         var maxtop = categories[idx].length;
10861:         for (var j=0; j<maxtop; j++) {
10862:             if (categories[idx][j] == 'instcode::0') {
10863:                 has_instcode == 1;
10864:             }
10865:         }
10866:         if (has_instcode == 0) {
10867:             categories[idx][maxtop] = 'instcode_pos';
10868:         }
10869:     } else {
10870:         newpos += '_'+parent;
10871:     }
10872:     var maxh = 1 + categories[idx].length;
10873:     var current = new Array;
10874:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10875:     if (item == newpos) {
10876:         changedVal = newitemVal;
10877:     } else {
10878:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
10879:         current[newitemVal] = newpos;
10880:     }
10881:     for (var i=0; i<categories[idx].length; i++) {
10882:         var elementName = categories[idx][i];
10883:         if (elementName != item) {
10884:             if (form.elements[elementName]) {
10885:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10886:                 current[currVal] = elementName;
10887:             }
10888:         }
10889:     }
10890:     var oldVal;
10891:     for (var j=0; j<maxh; j++) {
10892:         if (current[j] == undefined) {
10893:             oldVal = j;
10894:         }
10895:     }
10896:     if (oldVal < changedVal) {
10897:         for (var k=oldVal+1; k<=changedVal ; k++) {
10898:            var elementName = current[k];
10899:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10900:         }
10901:     } else {
10902:         for (var k=changedVal; k<oldVal; k++) {
10903:             var elementName = current[k];
10904:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10905:         }
10906:     }
10907:     return;
10908: }
10909: 
10910: function categoryCheck(form) {
10911:     if (form.elements['addcategory_name'].value == 'instcode') {
10912:         alert('$instcode_reserved\\n$choose_again');
10913:         return false;
10914:     }
10915:     if (form.elements['addcategory_name'].value == 'communities') {
10916:         alert('$communities_reserved\\n$choose_again');
10917:         return false;
10918:     }
10919:     if (form.elements['addcategory_name'].value == 'placement') {
10920:         alert('$placement_reserved\\n$choose_again');
10921:         return false;
10922:     }
10923:     return true;
10924: }
10925: 
10926: // ]]>
10927: </script>
10928: 
10929: ENDSCRIPT
10930:     return $output;
10931: }
10932: 
10933: sub initialize_categories {
10934:     my ($itemcount) = @_;
10935:     my ($datatable,$css_class,$chgstr);
10936:     my %default_names = &Apache::lonlocal::texthash (
10937:                       instcode    => 'Official courses (with institutional codes)',
10938:                       communities => 'Communities',
10939:                       placement   => 'Placement Tests',
10940:                         );
10941:     my %selnum = (
10942:                    instcode    => '0',
10943:                    communities => '1',
10944:                    placement   => '2',
10945:                  );
10946:     my %selected;
10947:     foreach my $default ('instcode','communities','placement') {
10948:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10949:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
10950:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
10951:         $selected{$selnum{$default}} = ' selected="selected"';
10952:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10953:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
10954:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
10955:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
10956:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
10957:                      .'<option value="3">4</option></select>&nbsp;'
10958:                      .$default_names{$default}
10959:                      .'</span></td><td><span class="LC_nobreak">'
10960:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
10961:                      .&mt('Display').'</label>&nbsp;<label>'
10962:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
10963:                  .'</label></span></td></tr>';
10964:         $itemcount ++;
10965:     }
10966:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10967:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
10968:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10969:                   .'<select name="addcategory_pos"'.$chgstr.'>'
10970:                   .'<option value="0">1</option>'
10971:                   .'<option value="1">2</option>'
10972:                   .'<option value="2">3</option>'
10973:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
10974:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
10975:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
10976:                   .'</td></tr>';
10977:     return $datatable;
10978: }
10979: 
10980: sub build_category_rows {
10981:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
10982:     my ($text,$name,$item,$chgstr);
10983:     if (ref($cats) eq 'ARRAY') {
10984:         my $maxdepth = scalar(@{$cats});
10985:         if (ref($cats->[$depth]) eq 'HASH') {
10986:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10987:                 my $numchildren = @{$cats->[$depth]{$parent}};
10988:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10989:                 $text .= '<td><table class="LC_data_table">';
10990:                 my ($idxnum,$parent_name,$parent_item);
10991:                 my $higher = $depth - 1;
10992:                 if ($higher == 0) {
10993:                     $parent_name = &escape($parent).'::'.$higher;
10994:                 } else {
10995:                     if (ref($path) eq 'ARRAY') {
10996:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10997:                     }
10998:                 }
10999:                 $parent_item = 'addcategory_pos_'.$parent_name;
11000:                 for (my $j=0; $j<=$numchildren; $j++) {
11001:                     if ($j < $numchildren) {
11002:                         $name = $cats->[$depth]{$parent}[$j];
11003:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
11004:                         $idxnum = $idx->{$item};
11005:                     } else {
11006:                         $name = $parent_name;
11007:                         $item = $parent_item;
11008:                     }
11009:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
11010:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
11011:                     for (my $i=0; $i<=$numchildren; $i++) {
11012:                         my $vpos = $i+1;
11013:                         my $selstr;
11014:                         if ($j == $i) {
11015:                             $selstr = ' selected="selected" ';
11016:                         }
11017:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
11018:                     }
11019:                     $text .= '</select>&nbsp;';
11020:                     if ($j < $numchildren) {
11021:                         my $deeper = $depth+1;
11022:                         $text .= $name.'&nbsp;'
11023:                                  .'<label><input type="checkbox" name="deletecategory" value="'
11024:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
11025:                         if(ref($path) eq 'ARRAY') {
11026:                             push(@{$path},$name);
11027:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11028:                             pop(@{$path});
11029:                         }
11030:                     } else {
11031:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11032:                         if ($j == $numchildren) {
11033:                             $text .= $name;
11034:                         } else {
11035:                             $text .= $item;
11036:                         }
11037:                         $text .= '" value="" />';
11038:                     }
11039:                     $text .= '</td></tr>';
11040:                 }
11041:                 $text .= '</table></td>';
11042:             } else {
11043:                 my $higher = $depth-1;
11044:                 if ($higher == 0) {
11045:                     $name = &escape($parent).'::'.$higher;
11046:                 } else {
11047:                     if (ref($path) eq 'ARRAY') {
11048:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11049:                     }
11050:                 }
11051:                 my $colspan;
11052:                 if ($parent ne 'instcode') {
11053:                     $colspan = $maxdepth - $depth - 1;
11054:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11055:                 }
11056:             }
11057:         }
11058:     }
11059:     return $text;
11060: }
11061: 
11062: sub modifiable_userdata_row {
11063:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11064:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11065:     my ($role,$rolename,$statustype);
11066:     $role = $item;
11067:     if ($context eq 'cancreate') {
11068:         if ($item =~ /^(emailusername)_(.+)$/) {
11069:             $role = $1;
11070:             $statustype = $2;
11071:             if (ref($usertypes) eq 'HASH') {
11072:                 if ($usertypes->{$statustype}) {
11073:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11074:                 } else {
11075:                     $rolename = &mt('Data provided by user');
11076:                 }
11077:             }
11078:         }
11079:     } elsif ($context eq 'selfcreate') {
11080:         if (ref($usertypes) eq 'HASH') {
11081:             $rolename = $usertypes->{$role};
11082:         } else {
11083:             $rolename = $role;
11084:         }
11085:     } elsif ($context eq 'lti') {
11086:         $rolename = &mt('Institutional data used (if available)');
11087:     } elsif ($context eq 'privacy') {
11088:         $rolename = $itemdesc;
11089:     } else {
11090:         if ($role eq 'cr') {
11091:             $rolename = &mt('Custom role');
11092:         } else {
11093:             $rolename = &Apache::lonnet::plaintext($role);
11094:         }
11095:     }
11096:     my (@fields,%fieldtitles);
11097:     if (ref($fieldsref) eq 'ARRAY') {
11098:         @fields = @{$fieldsref};
11099:     } else {
11100:         @fields = ('lastname','firstname','middlename','generation',
11101:                    'permanentemail','id');
11102:     }
11103:     if ((ref($titlesref) eq 'HASH')) {
11104:         %fieldtitles = %{$titlesref};
11105:     } else {
11106:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11107:     }
11108:     my $output;
11109:     my $css_class;
11110:     if ($rowcount%2) {
11111:         $css_class = 'LC_odd_row';
11112:     }
11113:     if ($customcss) {
11114:         $css_class .= " $customcss";
11115:     }
11116:     $css_class =~ s/^\s+//;
11117:     if ($css_class) {
11118:         $css_class = ' class="'.$css_class.'"';
11119:     }
11120:     if ($rowstyle) {
11121:         $css_class .= ' style="'.$rowstyle.'"';
11122:     }
11123:     if ($rowid) {
11124:         $rowid = ' id="'.$rowid.'"';
11125:     }
11126:     $output = '<tr '.$css_class.$rowid.'>'.
11127:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
11128:               '<td class="LC_left_item" colspan="2"><table>';
11129:     my $rem;
11130:     my %checks;
11131:     my %current;
11132:     if (ref($settings) eq 'HASH') {
11133:         my $hashref;
11134:         if ($context eq 'lti') {
11135:             if (ref($settings) eq 'HASH') {
11136:                 $hashref = $settings->{'instdata'};
11137:             }
11138:         } elsif ($context eq 'privacy') {
11139:             my ($key,$inner) = split(/_/,$role);
11140:             if (ref($settings) eq 'HASH') {
11141:                 if (ref($settings->{$key}) eq 'HASH') {
11142:                     $hashref = $settings->{$key}->{$inner};
11143:                 }
11144:             }
11145:         } elsif (ref($settings->{$context}) eq 'HASH') {
11146:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
11147:                 $hashref = $settings->{'lti_instdata'};
11148:             }
11149:             if ($role eq 'emailusername') {
11150:                 if ($statustype) {
11151:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
11152:                         $hashref = $settings->{$context}->{$role}->{$statustype};
11153:                     }
11154:                 }
11155:             }
11156:         }
11157:         if (ref($hashref) eq 'HASH') { 
11158:             foreach my $field (@fields) {
11159:                 if ($hashref->{$field}) {
11160:                     if ($role eq 'emailusername') {
11161:                         $checks{$field} = $hashref->{$field};
11162:                     } else {
11163:                         $checks{$field} = ' checked="checked" ';
11164:                     }
11165:                 }
11166:             }
11167:         }
11168:     }
11169:  
11170:     my $total = scalar(@fields);
11171:     for (my $i=0; $i<$total; $i++) {
11172:         $rem = $i%($numinrow);
11173:         if ($rem == 0) {
11174:             if ($i > 0) {
11175:                 $output .= '</tr>';
11176:             }
11177:             $output .= '<tr>';
11178:         }
11179:         my $check = ' ';
11180:         unless ($role eq 'emailusername') {
11181:             if (exists($checks{$fields[$i]})) {
11182:                 $check = $checks{$fields[$i]};
11183:             } elsif ($context eq 'privacy') {
11184:                 if ($role =~ /^priv_(domain|course)$/) {
11185:                     if (ref($settings) ne 'HASH') {
11186:                         $check = ' checked="checked" ';
11187:                     }
11188:                 } elsif ($role =~ /^priv_(author|community)$/) {
11189:                     if (ref($settings) ne 'HASH') {
11190:                         unless ($fields[$i] eq 'id') {
11191:                             $check = ' checked="checked" ';
11192:                         }
11193:                     }
11194:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
11195:                     if (ref($settings) ne 'HASH') {
11196:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
11197:                             $check = ' checked="checked" ';
11198:                         }
11199:                     }
11200:                 }
11201:             } elsif ($context ne 'lti') {
11202:                 if ($role eq 'st') {
11203:                     if (ref($settings) ne 'HASH') {
11204:                         $check = ' checked="checked" '; 
11205:                     }
11206:                 }
11207:             }
11208:         }
11209:         $output .= '<td class="LC_left_item">'.
11210:                    '<span class="LC_nobreak">';
11211:         my $prefix = 'canmodify';
11212:         if ($role eq 'emailusername') {
11213:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
11214:                 $checks{$fields[$i]} = 'omit';
11215:             }
11216:             foreach my $option ('required','optional','omit') {
11217:                 my $checked='';
11218:                 if ($checks{$fields[$i]} eq $option) {
11219:                     $checked='checked="checked" ';
11220:                 }
11221:                 $output .= '<label>'.
11222:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
11223:                            &mt($option).'</label>'.('&nbsp;' x2);
11224:             }
11225:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
11226:         } else {
11227:             if ($context eq 'lti') {
11228:                 $prefix = 'lti';
11229:             } elsif ($context eq 'privacy') {
11230:                 $prefix = 'privacy';
11231:             }
11232:             $output .= '<label>'.
11233:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
11234:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
11235:                        '</label>';
11236:         }
11237:         $output .= '</span></td>';
11238:     }
11239:     $rem = $total%$numinrow;
11240:     my $colsleft;
11241:     if ($rem) {
11242:         $colsleft = $numinrow - $rem;
11243:     }
11244:     if ($colsleft > 1) {
11245:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
11246:                    '&nbsp;</td>';
11247:     } elsif ($colsleft == 1) {
11248:         $output .= '<td class="LC_left_item">&nbsp;</td>';
11249:     }
11250:     $output .= '</tr></table></td></tr>';
11251:     return $output;
11252: }
11253: 
11254: sub insttypes_row {
11255:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
11256:         $customcss,$rowstyle) = @_;
11257:     my %lt = &Apache::lonlocal::texthash (
11258:                       cansearch => 'Users allowed to search',
11259:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
11260:                       lockablenames => 'User preference to lock name',
11261:                       selfassign    => 'Self-reportable affiliations',
11262:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
11263:              );
11264:     my $showdom;
11265:     if ($context eq 'cansearch') {
11266:         $showdom = ' ('.$dom.')';
11267:     }
11268:     my $class = 'LC_left_item';
11269:     if ($context eq 'statustocreate') {
11270:         $class = 'LC_right_item';
11271:     }
11272:     my $css_class;
11273:     if ($$rowtotal%2) {
11274:         $css_class = 'LC_odd_row';
11275:     }
11276:     if ($customcss) {
11277:         $css_class .= ' '.$customcss;
11278:     }
11279:     $css_class =~ s/^\s+//;
11280:     if ($css_class) {
11281:         $css_class = ' class="'.$css_class.'"';
11282:     }
11283:     if ($rowstyle) {
11284:         $css_class .= ' style="'.$rowstyle.'"';
11285:     }
11286:     if ($onclick) {
11287:         $onclick = 'onclick="'.$onclick.'" ';
11288:     }
11289:     my $output = '<tr'.$css_class.'>'.
11290:                  '<td>'.$lt{$context}.$showdom.
11291:                  '</td><td class="'.$class.'" colspan="2"><table>';
11292:     my $rem;
11293:     if (ref($types) eq 'ARRAY') {
11294:         for (my $i=0; $i<@{$types}; $i++) {
11295:             if (defined($usertypes->{$types->[$i]})) {
11296:                 my $rem = $i%($numinrow);
11297:                 if ($rem == 0) {
11298:                     if ($i > 0) {
11299:                         $output .= '</tr>';
11300:                     }
11301:                     $output .= '<tr>';
11302:                 }
11303:                 my $check = ' ';
11304:                 if (ref($settings) eq 'HASH') {
11305:                     if (ref($settings->{$context}) eq 'ARRAY') {
11306:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
11307:                             $check = ' checked="checked" ';
11308:                         }
11309:                     } elsif (ref($settings->{$context}) eq 'HASH') {
11310:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
11311:                             $check = ' checked="checked" ';
11312:                         }
11313:                     } elsif ($context eq 'statustocreate') {
11314:                         $check = ' checked="checked" ';
11315:                     }
11316:                 }
11317:                 $output .= '<td class="LC_left_item">'.
11318:                            '<span class="LC_nobreak"><label>'.
11319:                            '<input type="checkbox" name="'.$context.'" '.
11320:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
11321:                            $usertypes->{$types->[$i]}.'</label></span></td>';
11322:             }
11323:         }
11324:         $rem = @{$types}%($numinrow);
11325:     }
11326:     my $colsleft = $numinrow - $rem;
11327:     if ($context eq 'overrides') {
11328:         if ($colsleft > 1) {
11329:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11330:         } else {
11331:             $output .= '<td class="LC_left_item">';
11332:         }
11333:         $output .= '&nbsp;';  
11334:     } else {
11335:         if ($rem == 0) {
11336:             $output .= '<tr>';
11337:         }
11338:         if ($colsleft > 1) {
11339:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11340:         } else {
11341:             $output .= '<td class="LC_left_item">';
11342:         }
11343:         my $defcheck = ' ';
11344:         if (ref($settings) eq 'HASH') {  
11345:             if (ref($settings->{$context}) eq 'ARRAY') {
11346:                 if (grep(/^default$/,@{$settings->{$context}})) {
11347:                     $defcheck = ' checked="checked" ';
11348:                 }
11349:             } elsif ($context eq 'statustocreate') {
11350:                 $defcheck = ' checked="checked" ';
11351:             }
11352:         }
11353:         $output .= '<span class="LC_nobreak"><label>'.
11354:                    '<input type="checkbox" name="'.$context.'" '.
11355:                    'value="default"'.$defcheck.$onclick.' />'.
11356:                    $othertitle.'</label></span>';
11357:     }
11358:     $output .= '</td></tr></table></td></tr>';
11359:     return $output;
11360: }
11361: 
11362: sub sorted_searchtitles {
11363:     my %searchtitles = &Apache::lonlocal::texthash(
11364:                          'uname' => 'username',
11365:                          'lastname' => 'last name',
11366:                          'lastfirst' => 'last name, first name',
11367:                      );
11368:     my @titleorder = ('uname','lastname','lastfirst');
11369:     return (\%searchtitles,\@titleorder);
11370: }
11371: 
11372: sub sorted_searchtypes {
11373:     my %srchtypes_desc = (
11374:                            exact    => 'is exact match',
11375:                            contains => 'contains ..',
11376:                            begins   => 'begins with ..',
11377:                          );
11378:     my @srchtypeorder = ('exact','begins','contains');
11379:     return (\%srchtypes_desc,\@srchtypeorder);
11380: }
11381: 
11382: sub usertype_update_row {
11383:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
11384:     my $datatable;
11385:     my $numinrow = 4;
11386:     foreach my $type (@{$types}) {
11387:         if (defined($usertypes->{$type})) {
11388:             $$rownums ++;
11389:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
11390:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
11391:                           '</td><td class="LC_left_item"><table>';
11392:             for (my $i=0; $i<@{$fields}; $i++) {
11393:                 my $rem = $i%($numinrow);
11394:                 if ($rem == 0) {
11395:                     if ($i > 0) {
11396:                         $datatable .= '</tr>';
11397:                     }
11398:                     $datatable .= '<tr>';
11399:                 }
11400:                 my $check = ' ';
11401:                 if (ref($settings) eq 'HASH') {
11402:                     if (ref($settings->{'fields'}) eq 'HASH') {
11403:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
11404:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
11405:                                 $check = ' checked="checked" ';
11406:                             }
11407:                         }
11408:                     }
11409:                 }
11410: 
11411:                 if ($i == @{$fields}-1) {
11412:                     my $colsleft = $numinrow - $rem;
11413:                     if ($colsleft > 1) {
11414:                         $datatable .= '<td colspan="'.$colsleft.'">';
11415:                     } else {
11416:                         $datatable .= '<td>';
11417:                     }
11418:                 } else {
11419:                     $datatable .= '<td>';
11420:                 }
11421:                 $datatable .= '<span class="LC_nobreak"><label>'.
11422:                               '<input type="checkbox" name="updateable_'.$type.
11423:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
11424:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
11425:             }
11426:             $datatable .= '</tr></table></td></tr>';
11427:         }
11428:     }
11429:     return $datatable;
11430: }
11431: 
11432: sub modify_login {
11433:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
11434:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
11435:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
11436:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
11437:     %title = ( coursecatalog => 'Display course catalog',
11438:                adminmail => 'Display administrator E-mail address',
11439:                helpdesk  => 'Display "Contact Helpdesk" link',
11440:                newuser => 'Link for visitors to create a user account',
11441:                loginheader => 'Log-in box header',
11442:                saml => 'Dual SSO and non-SSO login');
11443:     @offon = ('off','on');
11444:     if (ref($domconfig{login}) eq 'HASH') {
11445:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
11446:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
11447:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
11448:             }
11449:         }
11450:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
11451:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
11452:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
11453:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
11454:                     $saml{$lonhost} = 1;
11455:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
11456:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
11457:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
11458:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
11459:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
11460:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
11461:                 }
11462:             }
11463:         }
11464:     }
11465:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
11466:                                            \%domconfig,\%loginhash);
11467:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11468:     foreach my $item (@toggles) {
11469:         $loginhash{login}{$item} = $env{'form.'.$item};
11470:     }
11471:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
11472:     if (ref($colchanges{'login'}) eq 'HASH') {  
11473:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
11474:                                          \%loginhash);
11475:     }
11476: 
11477:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
11478:     my %domservers = &Apache::lonnet::get_servers($dom);
11479:     my @loginvia_attribs = ('serverpath','custompath','exempt');
11480:     if (keys(%servers) > 1) {
11481:         foreach my $lonhost (keys(%servers)) {
11482:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
11483:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
11484:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
11485:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
11486:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
11487:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11488:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11489:                         $changes{'loginvia'}{$lonhost} = 1;
11490:                     } else {
11491:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
11492:                         $changes{'loginvia'}{$lonhost} = 1;
11493:                     }
11494:                 } else {
11495:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11496:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11497:                         $changes{'loginvia'}{$lonhost} = 1;
11498:                     }
11499:                 }
11500:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
11501:                     foreach my $item (@loginvia_attribs) {
11502:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
11503:                     }
11504:                 } else {
11505:                     foreach my $item (@loginvia_attribs) {
11506:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11507:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11508:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
11509:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11510:                                 $new = '/';
11511:                             }
11512:                         }
11513:                         if (($item eq 'custompath') && 
11514:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11515:                             $new = '';
11516:                         }
11517:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
11518:                             $changes{'loginvia'}{$lonhost} = 1;
11519:                         }
11520:                         if ($item eq 'exempt') {
11521:                             $new = &check_exempt_addresses($new);
11522:                         }
11523:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11524:                     }
11525:                 }
11526:             } else {
11527:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11528:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11529:                     $changes{'loginvia'}{$lonhost} = 1;
11530:                     foreach my $item (@loginvia_attribs) {
11531:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11532:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11533:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11534:                                 $new = '/';
11535:                             }
11536:                         }
11537:                         if (($item eq 'custompath') && 
11538:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11539:                             $new = '';
11540:                         }
11541:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11542:                     }
11543:                 }
11544:             }
11545:         }
11546:     }
11547: 
11548:     my $servadm = $r->dir_config('lonAdmEMail');
11549:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
11550:     if (ref($domconfig{'login'}) eq 'HASH') {
11551:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
11552:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
11553:                 if ($lang eq 'nolang') {
11554:                     push(@currlangs,$lang);
11555:                 } elsif (defined($langchoices{$lang})) {
11556:                     push(@currlangs,$lang);
11557:                 } else {
11558:                     next;
11559:                 }
11560:             }
11561:         }
11562:     }
11563:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
11564:     if (@currlangs > 0) {
11565:         foreach my $lang (@currlangs) {
11566:             if (grep(/^\Q$lang\E$/,@delurls)) {
11567:                 $changes{'helpurl'}{$lang} = 1;
11568:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
11569:                 $changes{'helpurl'}{$lang} = 1;
11570:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
11571:                 push(@newlangs,$lang);
11572:             } else {
11573:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11574:             }
11575:         }
11576:     }
11577:     unless (grep(/^nolang$/,@currlangs)) {
11578:         if ($env{'form.loginhelpurl_nolang.filename'}) {
11579:             $changes{'helpurl'}{'nolang'} = 1;
11580:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
11581:             push(@newlangs,'nolang');
11582:         }
11583:     }
11584:     if ($env{'form.loginhelpurl_add_lang'}) {
11585:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
11586:             ($env{'form.loginhelpurl_add_file.filename'})) {
11587:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
11588:             $addedfile = $env{'form.loginhelpurl_add_lang'};
11589:         }
11590:     }
11591:     if ((@newlangs > 0) || ($addedfile)) {
11592:         my $error;
11593:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11594:         if ($configuserok eq 'ok') {
11595:             if ($switchserver) {
11596:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
11597:             } elsif ($author_ok eq 'ok') {
11598:                 my @allnew = @newlangs;
11599:                 if ($addedfile ne '') {
11600:                     push(@allnew,$addedfile);
11601:                 }
11602:                 foreach my $lang (@allnew) {
11603:                     my $formelem = 'loginhelpurl_'.$lang;
11604:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
11605:                         $formelem = 'loginhelpurl_add_file';
11606:                     }
11607:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11608:                                                                "help/$lang",'','',$newfile{$lang});
11609:                     if ($result eq 'ok') {
11610:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
11611:                         $changes{'helpurl'}{$lang} = 1;
11612:                     } else {
11613:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
11614:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11615:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
11616:                             (!grep(/^\Q$lang\E$/,@delurls))) {
11617:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11618:                         }
11619:                     }
11620:                 }
11621:             } else {
11622:                 $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);
11623:             }
11624:         } else {
11625:             $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);
11626:         }
11627:         if ($error) {
11628:             &Apache::lonnet::logthis($error);
11629:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11630:         }
11631:     }
11632: 
11633:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
11634:     if (ref($domconfig{'login'}) eq 'HASH') {
11635:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
11636:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
11637:                 if ($domservers{$lonhost}) {
11638:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11639:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
11640:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
11641:                     }
11642:                 }
11643:             }
11644:         }
11645:     }
11646:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
11647:     foreach my $lonhost (sort(keys(%domservers))) {
11648:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11649:             $changes{'headtag'}{$lonhost} = 1;
11650:         } else {
11651:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
11652:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
11653:             }
11654:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
11655:                 push(@newhosts,$lonhost);
11656:             } elsif ($currheadtagurls{$lonhost}) {
11657:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
11658:                 if ($currexempt{$lonhost}) {
11659:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
11660:                         $changes{'headtag'}{$lonhost} = 1;
11661:                     }
11662:                 } elsif ($possexempt{$lonhost}) {
11663:                     $changes{'headtag'}{$lonhost} = 1;
11664:                 }
11665:                 if ($possexempt{$lonhost}) {
11666:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11667:                 }
11668:             }
11669:         }
11670:     }
11671:     if (@newhosts) {
11672:         my $error;
11673:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11674:         if ($configuserok eq 'ok') {
11675:             if ($switchserver) {
11676:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
11677:             } elsif ($author_ok eq 'ok') {
11678:                 foreach my $lonhost (@newhosts) {
11679:                     my $formelem = 'loginheadtag_'.$lonhost;
11680:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11681:                                                                           "login/headtag/$lonhost",'','',
11682:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
11683:                     if ($result eq 'ok') {
11684:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
11685:                         $changes{'headtag'}{$lonhost} = 1;
11686:                         if ($possexempt{$lonhost}) {
11687:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11688:                         }
11689:                     } else {
11690:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
11691:                                            $newheadtagurls{$lonhost},$result);
11692:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11693:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
11694:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
11695:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
11696:                         }
11697:                     }
11698:                 }
11699:             } else {
11700:                 $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);
11701:             }
11702:         } else {
11703:             $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);
11704:         }
11705:         if ($error) {
11706:             &Apache::lonnet::logthis($error);
11707:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11708:         }
11709:     }
11710:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
11711:     my @newsamlimgs;
11712:     foreach my $lonhost (keys(%domservers)) {
11713:         if ($env{'form.saml_'.$lonhost}) {
11714:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
11715:                 push(@newsamlimgs,$lonhost);
11716:             }
11717:             foreach my $item ('text','alt','url','title','notsso') {
11718:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
11719:             }
11720:             if ($saml{$lonhost}) {
11721:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
11722: #FIXME Need to obsolete published image
11723:                     delete($currsaml{$lonhost}{'img'});
11724:                     $changes{'saml'}{$lonhost} = 1;
11725:                 }
11726:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
11727:                     $changes{'saml'}{$lonhost} = 1;
11728:                 }
11729:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
11730:                     $changes{'saml'}{$lonhost} = 1;
11731:                 }
11732:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
11733:                     $changes{'saml'}{$lonhost} = 1;
11734:                 }
11735:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
11736:                     $changes{'saml'}{$lonhost} = 1;
11737:                 }
11738:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
11739:                     $changes{'saml'}{$lonhost} = 1;
11740:                 }
11741:             } else {
11742:                 $changes{'saml'}{$lonhost} = 1;
11743:             }
11744:             foreach my $item ('text','alt','url','title','notsso') {
11745:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
11746:             }
11747:         } else {
11748:             delete($currsaml{$lonhost});
11749:         }
11750:     }
11751:     foreach my $posshost (keys(%currsaml)) {
11752:         unless (exists($domservers{$posshost})) { 
11753:             delete($currsaml{$posshost}); 
11754:         }
11755:     }
11756:     %{$loginhash{'login'}{'saml'}} = %currsaml;
11757:     if (@newsamlimgs) {
11758:         my $error;
11759:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11760:         if ($configuserok eq 'ok') {
11761:             if ($switchserver) {
11762:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
11763:             } elsif ($author_ok eq 'ok') {
11764:                 foreach my $lonhost (@newsamlimgs) {
11765:                     my $formelem = 'saml_img_'.$lonhost;
11766:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11767:                                                         "login/saml/$lonhost",'','',
11768:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
11769:                     if ($result eq 'ok') {
11770:                         $currsaml{$lonhost}{'img'} = $imgurl;
11771:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
11772:                         $changes{'saml'}{$lonhost} = 1;
11773:                     } else {
11774:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
11775:                                            $lonhost,$result);
11776:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11777:                     }
11778:                 }
11779:             } else {
11780:                 $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);
11781:             }
11782:         } else {
11783:             $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);
11784:         }
11785:         if ($error) {
11786:             &Apache::lonnet::logthis($error);
11787:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11788:         }
11789:     }
11790:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
11791: 
11792:     my $defaulthelpfile = '/adm/loginproblems.html';
11793:     my $defaulttext = &mt('Default in use');
11794: 
11795:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
11796:                                              $dom);
11797:     if ($putresult eq 'ok') {
11798:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11799:         my %defaultchecked = (
11800:                     'coursecatalog' => 'on',
11801:                     'helpdesk'      => 'on',
11802:                     'adminmail'     => 'off',
11803:                     'newuser'       => 'off',
11804:         );
11805:         if (ref($domconfig{'login'}) eq 'HASH') {
11806:             foreach my $item (@toggles) {
11807:                 if ($defaultchecked{$item} eq 'on') { 
11808:                     if (($domconfig{'login'}{$item} eq '0') &&
11809:                         ($env{'form.'.$item} eq '1')) {
11810:                         $changes{$item} = 1;
11811:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11812:                               $domconfig{'login'}{$item} eq '1') &&
11813:                              ($env{'form.'.$item} eq '0')) {
11814:                         $changes{$item} = 1;
11815:                     }
11816:                 } elsif ($defaultchecked{$item} eq 'off') {
11817:                     if (($domconfig{'login'}{$item} eq '1') &&
11818:                         ($env{'form.'.$item} eq '0')) {
11819:                         $changes{$item} = 1;
11820:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11821:                               $domconfig{'login'}{$item} eq '0') &&
11822:                              ($env{'form.'.$item} eq '1')) {
11823:                         $changes{$item} = 1;
11824:                     }
11825:                 }
11826:             }
11827:         }
11828:         if (keys(%changes) > 0 || $colchgtext) {
11829:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11830:             if (exists($changes{'saml'})) {
11831:                 my $hostid_in_use;
11832:                 my @hosts = &Apache::lonnet::current_machine_ids();
11833:                 if (@hosts > 1) {
11834:                     foreach my $hostid (@hosts) {
11835:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
11836:                             $hostid_in_use = $hostid;
11837:                             last;
11838:                         }
11839:                     }
11840:                 } else {
11841:                     $hostid_in_use = $r->dir_config('lonHostID');
11842:                 }
11843:                 if (($hostid_in_use) &&
11844:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
11845:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
11846:                 }
11847:                 if (ref($lastactref) eq 'HASH') {
11848:                     if (ref($changes{'saml'}) eq 'HASH') {
11849:                         my %updates;
11850:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
11851:                         $lastactref->{'samllanding'} = \%updates;
11852:                     }
11853:                 }
11854:             }
11855:             if (ref($lastactref) eq 'HASH') {
11856:                 $lastactref->{'domainconfig'} = 1;
11857:             }
11858:             $resulttext = &mt('Changes made:').'<ul>';
11859:             foreach my $item (sort(keys(%changes))) {
11860:                 if ($item eq 'loginvia') {
11861:                     if (ref($changes{$item}) eq 'HASH') {
11862:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
11863:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11864:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
11865:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
11866:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
11867:                                     $protocol = 'http' if ($protocol ne 'https');
11868:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
11869: 
11870:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
11871:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
11872:                                     } else {
11873:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
11874:                                     }
11875:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
11876:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
11877:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
11878:                                     }
11879:                                     $resulttext .= '</li>';
11880:                                 } else {
11881:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
11882:                                 }
11883:                             } else {
11884:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
11885:                             }
11886:                         }
11887:                         $resulttext .= '</ul></li>';
11888:                     }
11889:                 } elsif ($item eq 'helpurl') {
11890:                     if (ref($changes{$item}) eq 'HASH') {
11891:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
11892:                             if (grep(/^\Q$lang\E$/,@delurls)) {
11893:                                 my ($chg,$link);
11894:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
11895:                                 if ($lang eq 'nolang') {
11896:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
11897:                                 } else {
11898:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
11899:                                 }
11900:                                 $resulttext .= '<li>'.$chg.'</li>';
11901:                             } else {
11902:                                 my $chg;
11903:                                 if ($lang eq 'nolang') {
11904:                                     $chg = &mt('custom log-in help file for no preferred language');
11905:                                 } else {
11906:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
11907:                                 }
11908:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
11909:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
11910:                                                       '?inhibitmenu=yes',$chg,600,500).
11911:                                                '</li>';
11912:                             }
11913:                         }
11914:                     }
11915:                 } elsif ($item eq 'headtag') {
11916:                     if (ref($changes{$item}) eq 'HASH') {
11917:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11918:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11919:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
11920:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11921:                                 $resulttext .= '<li><a href="'.
11922:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
11923:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
11924:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
11925:                                 if ($possexempt{$lonhost}) {
11926:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
11927:                                 } else {
11928:                                     $resulttext .= &mt('included for any client IP');
11929:                                 }
11930:                                 $resulttext .= '</li>';
11931:                             }
11932:                         }
11933:                     }
11934:                 } elsif ($item eq 'saml') {
11935:                     if (ref($changes{$item}) eq 'HASH') {
11936:                         my %notlt = (
11937:                                        text   => 'Text for log-in by SSO',
11938:                                        img    => 'SSO button image',
11939:                                        alt    => 'Alt text for button image',
11940:                                        url    => 'SSO URL',
11941:                                        title  => 'Tooltip for SSO link',
11942:                                        notsso => 'Text for non-SSO log-in',
11943:                                     );
11944:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11945:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
11946:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
11947:                                                '<ul>';
11948:                                 foreach my $key ('text','img','alt','url','title','notsso') {
11949:                                     if ($currsaml{$lonhost}{$key} eq '') {
11950:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
11951:                                     } else {
11952:                                         my $value = "'$currsaml{$lonhost}{$key}'";
11953:                                         if ($key eq 'img') {
11954:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
11955:                                         }
11956:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
11957:                                                                   $value).'</li>';
11958:                                     }
11959:                                 }
11960:                                 $resulttext .= '</ul></li>';
11961:                             } else {
11962:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
11963:                             }
11964:                         }
11965:                     }
11966:                 } elsif ($item eq 'captcha') {
11967:                     if (ref($loginhash{'login'}) eq 'HASH') {
11968:                         my $chgtxt;
11969:                         if ($loginhash{'login'}{$item} eq 'notused') {
11970:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
11971:                         } else {
11972:                             my %captchas = &captcha_phrases();
11973:                             if ($captchas{$loginhash{'login'}{$item}}) {
11974:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
11975:                             } else {
11976:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
11977:                             }
11978:                         }
11979:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11980:                     }
11981:                 } elsif ($item eq 'recaptchakeys') {
11982:                     if (ref($loginhash{'login'}) eq 'HASH') {
11983:                         my ($privkey,$pubkey);
11984:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
11985:                             $pubkey = $loginhash{'login'}{$item}{'public'};
11986:                             $privkey = $loginhash{'login'}{$item}{'private'};
11987:                         }
11988:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
11989:                         if (!$pubkey) {
11990:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
11991:                         } else {
11992:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
11993:                         }
11994:                         if (!$privkey) {
11995:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
11996:                         } else {
11997:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
11998:                         }
11999:                         $chgtxt .= '</ul>';
12000:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12001:                     }
12002:                 } elsif ($item eq 'recaptchaversion') {
12003:                     if (ref($loginhash{'login'}) eq 'HASH') {
12004:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
12005:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
12006:                                            '</li>';
12007:                         }
12008:                     }
12009:                 } else {
12010:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
12011:                 }
12012:             }
12013:             $resulttext .= $colchgtext.'</ul>';
12014:         } else {
12015:             $resulttext = &mt('No changes made to log-in page settings');
12016:         }
12017:     } else {
12018:         $resulttext = '<span class="LC_error">'.
12019: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12020:     }
12021:     if ($errors) {
12022:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12023:                        $errors.'</ul>';
12024:     }
12025:     return $resulttext;
12026: }
12027: 
12028: sub check_exempt_addresses {
12029:     my ($iplist) = @_;
12030:     $iplist =~ s/^\s+//;
12031:     $iplist =~ s/\s+$//;
12032:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12033:     my (@okips,$new);
12034:     foreach my $ip (@poss_ips) {
12035:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12036:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12037:                 push(@okips,$ip);
12038:             }
12039:         }
12040:     }
12041:     if (@okips > 0) {
12042:         $new = join(',',@okips);
12043:     } else {
12044:         $new = '';
12045:     }
12046:     return $new;
12047: }
12048: 
12049: sub color_font_choices {
12050:     my %choices =
12051:         &Apache::lonlocal::texthash (
12052:             img => "Header",
12053:             bgs => "Background colors",
12054:             links => "Link colors",
12055:             images => "Images",
12056:             font => "Font color",
12057:             fontmenu => "Font menu",
12058:             pgbg => "Page",
12059:             tabbg => "Header",
12060:             sidebg => "Border",
12061:             link => "Link",
12062:             alink => "Active link",
12063:             vlink => "Visited link",
12064:         );
12065:     return %choices;
12066: }
12067: 
12068: sub modify_rolecolors {
12069:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
12070:     my ($resulttext,%rolehash);
12071:     $rolehash{'rolecolors'} = {};
12072:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
12073:         if ($domconfig{'rolecolors'} eq '') {
12074:             $domconfig{'rolecolors'} = {};
12075:         }
12076:     }
12077:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
12078:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
12079:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
12080:                                              $dom);
12081:     if ($putresult eq 'ok') {
12082:         if (keys(%changes) > 0) {
12083:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12084:             if (ref($lastactref) eq 'HASH') {
12085:                 $lastactref->{'domainconfig'} = 1;
12086:             }
12087:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
12088:                                              $rolehash{'rolecolors'});
12089:         } else {
12090:             $resulttext = &mt('No changes made to default color schemes');
12091:         }
12092:     } else {
12093:         $resulttext = '<span class="LC_error">'.
12094: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12095:     }
12096:     if ($errors) {
12097:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
12098:                        $errors.'</ul>';
12099:     }
12100:     return $resulttext;
12101: }
12102: 
12103: sub modify_colors {
12104:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
12105:     my (%changes,%choices);
12106:     my @bgs;
12107:     my @links = ('link','alink','vlink');
12108:     my @logintext;
12109:     my @images;
12110:     my $servadm = $r->dir_config('lonAdmEMail');
12111:     my $errors;
12112:     my %defaults;
12113:     foreach my $role (@{$roles}) {
12114:         if ($role eq 'login') {
12115:             %choices = &login_choices();
12116:             @logintext = ('textcol','bgcol');
12117:         } else {
12118:             %choices = &color_font_choices();
12119:         }
12120:         if ($role eq 'login') {
12121:             @images = ('img','logo','domlogo','login');
12122:             @bgs = ('pgbg','mainbg','sidebg');
12123:         } else {
12124:             @images = ('img');
12125:             @bgs = ('pgbg','tabbg','sidebg');
12126:         }
12127:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
12128:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
12129:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
12130:         }
12131:         if ($role eq 'login') {
12132:             foreach my $item (@logintext) {
12133:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
12134:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
12135:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
12136:                 }
12137:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
12138:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
12139:                 }
12140:             }
12141:         } else {
12142:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
12143:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
12144:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
12145:             }
12146:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
12147:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
12148:             }
12149:         }
12150:         foreach my $item (@bgs) {
12151:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
12152:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
12153:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
12154:             }
12155:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
12156:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
12157:             }
12158:         }
12159:         foreach my $item (@links) {
12160:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
12161:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
12162:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
12163:             }
12164:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
12165:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
12166:             }
12167:         }
12168:         my ($configuserok,$author_ok,$switchserver) = 
12169:             &config_check($dom,$confname,$servadm);
12170:         my ($width,$height) = &thumb_dimensions();
12171:         if (ref($domconfig->{$role}) ne 'HASH') {
12172:             $domconfig->{$role} = {};
12173:         }
12174:         foreach my $img (@images) {
12175:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
12176:                 if (defined($env{'form.login_showlogo_'.$img})) {
12177:                     $confhash->{$role}{'showlogo'}{$img} = 1;
12178:                 } else { 
12179:                     $confhash->{$role}{'showlogo'}{$img} = 0;
12180:                 }
12181:             } 
12182: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
12183: 		 && !defined($domconfig->{$role}{$img})
12184: 		 && !$env{'form.'.$role.'_del_'.$img}
12185: 		 && $env{'form.'.$role.'_import_'.$img}) {
12186: 		# import the old configured image from the .tab setting
12187: 		# if they haven't provided a new one 
12188: 		$domconfig->{$role}{$img} = 
12189: 		    $env{'form.'.$role.'_import_'.$img};
12190: 	    }
12191:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
12192:                 my $error;
12193:                 if ($configuserok eq 'ok') {
12194:                     if ($switchserver) {
12195:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
12196:                     } else {
12197:                         if ($author_ok eq 'ok') {
12198:                             my ($result,$logourl) = 
12199:                                 &publishlogo($r,'upload',$role.'_'.$img,
12200:                                            $dom,$confname,$img,$width,$height);
12201:                             if ($result eq 'ok') {
12202:                                 $confhash->{$role}{$img} = $logourl;
12203:                                 $changes{$role}{'images'}{$img} = 1;
12204:                             } else {
12205:                                 $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);
12206:                             }
12207:                         } else {
12208:                             $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);
12209:                         }
12210:                     }
12211:                 } else {
12212:                     $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);
12213:                 }
12214:                 if ($error) {
12215:                     &Apache::lonnet::logthis($error);
12216:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12217:                 }
12218:             } elsif ($domconfig->{$role}{$img} ne '') {
12219:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
12220:                     my $error;
12221:                     if ($configuserok eq 'ok') {
12222: # is confname an author?
12223:                         if ($switchserver eq '') {
12224:                             if ($author_ok eq 'ok') {
12225:                                 my ($result,$logourl) = 
12226:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
12227:                                             $dom,$confname,$img,$width,$height);
12228:                                 if ($result eq 'ok') {
12229:                                     $confhash->{$role}{$img} = $logourl;
12230: 				    $changes{$role}{'images'}{$img} = 1;
12231:                                 }
12232:                             }
12233:                         }
12234:                     }
12235:                 }
12236:             }
12237:         }
12238:         if (ref($domconfig) eq 'HASH') {
12239:             if (ref($domconfig->{$role}) eq 'HASH') {
12240:                 foreach my $img (@images) {
12241:                     if ($domconfig->{$role}{$img} ne '') {
12242:                         if ($env{'form.'.$role.'_del_'.$img}) {
12243:                             $confhash->{$role}{$img} = '';
12244:                             $changes{$role}{'images'}{$img} = 1;
12245:                         } else {
12246:                             if ($confhash->{$role}{$img} eq '') {
12247:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
12248:                             }
12249:                         }
12250:                     } else {
12251:                         if ($env{'form.'.$role.'_del_'.$img}) {
12252:                             $confhash->{$role}{$img} = '';
12253:                             $changes{$role}{'images'}{$img} = 1;
12254:                         } 
12255:                     }
12256:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
12257:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
12258:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
12259:                                 $domconfig->{$role}{'showlogo'}{$img}) {
12260:                                 $changes{$role}{'showlogo'}{$img} = 1; 
12261:                             }
12262:                         } else {
12263:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
12264:                                 $changes{$role}{'showlogo'}{$img} = 1;
12265:                             }
12266:                         }
12267:                     }
12268:                 }
12269:                 if ($domconfig->{$role}{'font'} ne '') {
12270:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
12271:                         $changes{$role}{'font'} = 1;
12272:                     }
12273:                 } else {
12274:                     if ($confhash->{$role}{'font'}) {
12275:                         $changes{$role}{'font'} = 1;
12276:                     }
12277:                 }
12278:                 if ($role ne 'login') {
12279:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
12280:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
12281:                             $changes{$role}{'fontmenu'} = 1;
12282:                         }
12283:                     } else {
12284:                         if ($confhash->{$role}{'fontmenu'}) {
12285:                             $changes{$role}{'fontmenu'} = 1;
12286:                         }
12287:                     }
12288:                 }
12289:                 foreach my $item (@bgs) {
12290:                     if ($domconfig->{$role}{$item} ne '') {
12291:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
12292:                             $changes{$role}{'bgs'}{$item} = 1;
12293:                         } 
12294:                     } else {
12295:                         if ($confhash->{$role}{$item}) {
12296:                             $changes{$role}{'bgs'}{$item} = 1;
12297:                         }
12298:                     }
12299:                 }
12300:                 foreach my $item (@links) {
12301:                     if ($domconfig->{$role}{$item} ne '') {
12302:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
12303:                             $changes{$role}{'links'}{$item} = 1;
12304:                         }
12305:                     } else {
12306:                         if ($confhash->{$role}{$item}) {
12307:                             $changes{$role}{'links'}{$item} = 1;
12308:                         }
12309:                     }
12310:                 }
12311:                 foreach my $item (@logintext) {
12312:                     if ($domconfig->{$role}{$item} ne '') {
12313:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
12314:                             $changes{$role}{'logintext'}{$item} = 1;
12315:                         }
12316:                     } else {
12317:                         if ($confhash->{$role}{$item}) {
12318:                             $changes{$role}{'logintext'}{$item} = 1;
12319:                         }
12320:                     }
12321:                 }
12322:             } else {
12323:                 &default_change_checker($role,\@images,\@links,\@bgs,
12324:                                         \@logintext,$confhash,\%changes); 
12325:             }
12326:         } else {
12327:             &default_change_checker($role,\@images,\@links,\@bgs,
12328:                                     \@logintext,$confhash,\%changes); 
12329:         }
12330:     }
12331:     return ($errors,%changes);
12332: }
12333: 
12334: sub config_check {
12335:     my ($dom,$confname,$servadm) = @_;
12336:     my ($configuserok,$author_ok,$switchserver,%currroles);
12337:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
12338:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
12339:                                                    $confname,$servadm);
12340:     if ($configuserok eq 'ok') {
12341:         $switchserver = &check_switchserver($dom,$confname);
12342:         if ($switchserver eq '') {
12343:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
12344:         }
12345:     }
12346:     return ($configuserok,$author_ok,$switchserver);
12347: }
12348: 
12349: sub default_change_checker {
12350:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
12351:     foreach my $item (@{$links}) {
12352:         if ($confhash->{$role}{$item}) {
12353:             $changes->{$role}{'links'}{$item} = 1;
12354:         }
12355:     }
12356:     foreach my $item (@{$bgs}) {
12357:         if ($confhash->{$role}{$item}) {
12358:             $changes->{$role}{'bgs'}{$item} = 1;
12359:         }
12360:     }
12361:     foreach my $item (@{$logintext}) {
12362:         if ($confhash->{$role}{$item}) {
12363:             $changes->{$role}{'logintext'}{$item} = 1;
12364:         }
12365:     }
12366:     foreach my $img (@{$images}) {
12367:         if ($env{'form.'.$role.'_del_'.$img}) {
12368:             $confhash->{$role}{$img} = '';
12369:             $changes->{$role}{'images'}{$img} = 1;
12370:         }
12371:         if ($role eq 'login') {
12372:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
12373:                 $changes->{$role}{'showlogo'}{$img} = 1;
12374:             }
12375:         }
12376:     }
12377:     if ($confhash->{$role}{'font'}) {
12378:         $changes->{$role}{'font'} = 1;
12379:     }
12380: }
12381: 
12382: sub display_colorchgs {
12383:     my ($dom,$changes,$roles,$confhash) = @_;
12384:     my (%choices,$resulttext);
12385:     if (!grep(/^login$/,@{$roles})) {
12386:         $resulttext = &mt('Changes made:').'<br />';
12387:     }
12388:     foreach my $role (@{$roles}) {
12389:         if ($role eq 'login') {
12390:             %choices = &login_choices();
12391:         } else {
12392:             %choices = &color_font_choices();
12393:         }
12394:         if (ref($changes->{$role}) eq 'HASH') {
12395:             if ($role ne 'login') {
12396:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
12397:             }
12398:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
12399:                 if ($role ne 'login') {
12400:                     $resulttext .= '<ul>';
12401:                 }
12402:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
12403:                     if ($role ne 'login') {
12404:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
12405:                     }
12406:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
12407:                         if (($role eq 'login') && ($key eq 'showlogo')) {
12408:                             if ($confhash->{$role}{$key}{$item}) {
12409:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
12410:                             } else {
12411:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
12412:                             }
12413:                         } elsif ($confhash->{$role}{$item} eq '') {
12414:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
12415:                         } else {
12416:                             my $newitem = $confhash->{$role}{$item};
12417:                             if ($key eq 'images') {
12418:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
12419:                             }
12420:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
12421:                         }
12422:                     }
12423:                     if ($role ne 'login') {
12424:                         $resulttext .= '</ul></li>';
12425:                     }
12426:                 } else {
12427:                     if ($confhash->{$role}{$key} eq '') {
12428:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
12429:                     } else {
12430:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
12431:                     }
12432:                 }
12433:                 if ($role ne 'login') {
12434:                     $resulttext .= '</ul>';
12435:                 }
12436:             }
12437:         }
12438:     }
12439:     return $resulttext;
12440: }
12441: 
12442: sub thumb_dimensions {
12443:     return ('200','50');
12444: }
12445: 
12446: sub check_dimensions {
12447:     my ($inputfile) = @_;
12448:     my ($fullwidth,$fullheight);
12449:     if ($inputfile =~ m|^[/\w.\-]+$|) {
12450:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
12451:             my $imageinfo = <PIPE>;
12452:             if (!close(PIPE)) {
12453:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
12454:             }
12455:             chomp($imageinfo);
12456:             my ($fullsize) = 
12457:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
12458:             if ($fullsize) {
12459:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
12460:             }
12461:         }
12462:     }
12463:     return ($fullwidth,$fullheight);
12464: }
12465: 
12466: sub check_configuser {
12467:     my ($uhome,$dom,$confname,$servadm) = @_;
12468:     my ($configuserok,%currroles);
12469:     if ($uhome eq 'no_host') {
12470:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
12471:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
12472:         $configuserok = 
12473:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
12474:                              $configpass,'','','','','',undef,$servadm);
12475:     } else {
12476:         $configuserok = 'ok';
12477:         %currroles = 
12478:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
12479:     }
12480:     return ($configuserok,%currroles);
12481: }
12482: 
12483: sub check_authorstatus {
12484:     my ($dom,$confname,%currroles) = @_;
12485:     my $author_ok;
12486:     if (!$currroles{':'.$dom.':au'}) {
12487:         my $start = time;
12488:         my $end = 0;
12489:         $author_ok = 
12490:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
12491:                                         'au',$end,$start,'','','domconfig');
12492:     } else {
12493:         $author_ok = 'ok';
12494:     }
12495:     return $author_ok;
12496: }
12497: 
12498: sub publishlogo {
12499:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
12500:     my ($output,$fname,$logourl,$madethumb);
12501:     if ($action eq 'upload') {
12502:         $fname=$env{'form.'.$formname.'.filename'};
12503:         chop($env{'form.'.$formname});
12504:     } else {
12505:         ($fname) = ($formname =~ /([^\/]+)$/);
12506:     }
12507:     if ($savefileas ne '') {
12508:         $fname = $savefileas;
12509:     }
12510:     $fname=&Apache::lonnet::clean_filename($fname);
12511: # See if there is anything left
12512:     unless ($fname) { return ('error: no uploaded file'); }
12513:     $fname="$subdir/$fname";
12514:     my $docroot=$r->dir_config('lonDocRoot');
12515:     my $filepath="$docroot/priv";
12516:     my $relpath = "$dom/$confname";
12517:     my ($fnamepath,$file,$fetchthumb);
12518:     $file=$fname;
12519:     if ($fname=~m|/|) {
12520:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
12521:     }
12522:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
12523:     my $count;
12524:     for ($count=5;$count<=$#parts;$count++) {
12525:         $filepath.="/$parts[$count]";
12526:         if ((-e $filepath)!=1) {
12527:             mkdir($filepath,02770);
12528:         }
12529:     }
12530:     # Check for bad extension and disallow upload
12531:     if ($file=~/\.(\w+)$/ &&
12532:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12533:         $output = 
12534:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
12535:     } elsif ($file=~/\.(\w+)$/ &&
12536:         !defined(&Apache::loncommon::fileembstyle($1))) {
12537:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
12538:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
12539:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
12540:     } elsif (-d "$filepath/$file") {
12541:         $output = &mt('Filename is a directory name - rename the file and re-upload');
12542:     } else {
12543:         my $source = $filepath.'/'.$file;
12544:         my $logfile;
12545:         if (!open($logfile,">>",$source.'.log')) {
12546:             return (&mt('No write permission to Authoring Space'));
12547:         }
12548:         print $logfile
12549: "\n================= Publish ".localtime()." ================\n".
12550: $env{'user.name'}.':'.$env{'user.domain'}."\n";
12551: # Save the file
12552:         if (!open(FH,">",$source)) {
12553:             &Apache::lonnet::logthis('Failed to create '.$source);
12554:             return (&mt('Failed to create file'));
12555:         }
12556:         if ($action eq 'upload') {
12557:             if (!print FH ($env{'form.'.$formname})) {
12558:                 &Apache::lonnet::logthis('Failed to write to '.$source);
12559:                 return (&mt('Failed to write file'));
12560:             }
12561:         } else {
12562:             my $original = &Apache::lonnet::filelocation('',$formname);
12563:             if(!copy($original,$source)) {
12564:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
12565:                 return (&mt('Failed to write file'));
12566:             }
12567:         }
12568:         close(FH);
12569:         chmod(0660, $source); # Permissions to rw-rw---.
12570: 
12571:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
12572:         my $copyfile=$targetdir.'/'.$file;
12573: 
12574:         my @parts=split(/\//,$targetdir);
12575:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
12576:         for (my $count=5;$count<=$#parts;$count++) {
12577:             $path.="/$parts[$count]";
12578:             if (!-e $path) {
12579:                 print $logfile "\nCreating directory ".$path;
12580:                 mkdir($path,02770);
12581:             }
12582:         }
12583:         my $versionresult;
12584:         if (-e $copyfile) {
12585:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
12586:         } else {
12587:             $versionresult = 'ok';
12588:         }
12589:         if ($versionresult eq 'ok') {
12590:             if (copy($source,$copyfile)) {
12591:                 print $logfile "\nCopied original source to ".$copyfile."\n";
12592:                 $output = 'ok';
12593:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
12594:                 push(@{$modified_urls},[$copyfile,$source]);
12595:                 my $metaoutput = 
12596:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
12597:                 unless ($registered_cleanup) {
12598:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12599:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12600:                     $registered_cleanup=1;
12601:                 }
12602:             } else {
12603:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
12604:                 $output = &mt('Failed to copy file to RES space').", $!";
12605:             }
12606:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
12607:                 my $inputfile = $filepath.'/'.$file;
12608:                 my $outfile = $filepath.'/'.'tn-'.$file;
12609:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
12610:                 if ($fullwidth ne '' && $fullheight ne '') { 
12611:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
12612:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
12613:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
12614:                         system({$args[0]} @args);
12615:                         chmod(0660, $filepath.'/tn-'.$file);
12616:                         if (-e $outfile) {
12617:                             my $copyfile=$targetdir.'/tn-'.$file;
12618:                             if (copy($outfile,$copyfile)) {
12619:                                 print $logfile "\nCopied source to ".$copyfile."\n";
12620:                                 my $thumb_metaoutput = 
12621:                                     &write_metadata($dom,$confname,$formname,
12622:                                                     $targetdir,'tn-'.$file,$logfile);
12623:                                 push(@{$modified_urls},[$copyfile,$outfile]);
12624:                                 unless ($registered_cleanup) {
12625:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12626:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12627:                                     $registered_cleanup=1;
12628:                                 }
12629:                                 $madethumb = 1;
12630:                             } else {
12631:                                 print $logfile "\nUnable to write ".$copyfile.
12632:                                                ':'.$!."\n";
12633:                             }
12634:                         }
12635:                     }
12636:                 }
12637:             }
12638:         } else {
12639:             $output = $versionresult;
12640:         }
12641:     }
12642:     return ($output,$logourl,$madethumb);
12643: }
12644: 
12645: sub logo_versioning {
12646:     my ($targetdir,$file,$logfile) = @_;
12647:     my $target = $targetdir.'/'.$file;
12648:     my ($maxversion,$fn,$extn,$output);
12649:     $maxversion = 0;
12650:     if ($file =~ /^(.+)\.(\w+)$/) {
12651:         $fn=$1;
12652:         $extn=$2;
12653:     }
12654:     opendir(DIR,$targetdir);
12655:     while (my $filename=readdir(DIR)) {
12656:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
12657:             $maxversion=($1>$maxversion)?$1:$maxversion;
12658:         }
12659:     }
12660:     $maxversion++;
12661:     print $logfile "\nCreating old version ".$maxversion."\n";
12662:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
12663:     if (copy($target,$copyfile)) {
12664:         print $logfile "Copied old target to ".$copyfile."\n";
12665:         $copyfile=$copyfile.'.meta';
12666:         if (copy($target.'.meta',$copyfile)) {
12667:             print $logfile "Copied old target metadata to ".$copyfile."\n";
12668:             $output = 'ok';
12669:         } else {
12670:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
12671:             $output = &mt('Failed to copy old meta').", $!, ";
12672:         }
12673:     } else {
12674:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
12675:         $output = &mt('Failed to copy old target').", $!, ";
12676:     }
12677:     return $output;
12678: }
12679: 
12680: sub write_metadata {
12681:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
12682:     my (%metadatafields,%metadatakeys,$output);
12683:     $metadatafields{'title'}=$formname;
12684:     $metadatafields{'creationdate'}=time;
12685:     $metadatafields{'lastrevisiondate'}=time;
12686:     $metadatafields{'copyright'}='public';
12687:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
12688:                                          $env{'user.domain'};
12689:     $metadatafields{'authorspace'}=$confname.':'.$dom;
12690:     $metadatafields{'domain'}=$dom;
12691:     {
12692:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
12693:         my $mfh;
12694:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
12695:             foreach (sort(keys(%metadatafields))) {
12696:                 unless ($_=~/\./) {
12697:                     my $unikey=$_;
12698:                     $unikey=~/^([A-Za-z]+)/;
12699:                     my $tag=$1;
12700:                     $tag=~tr/A-Z/a-z/;
12701:                     print $mfh "\n\<$tag";
12702:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
12703:                         my $value=$metadatafields{$unikey.'.'.$_};
12704:                         $value=~s/\"/\'\'/g;
12705:                         print $mfh ' '.$_.'="'.$value.'"';
12706:                     }
12707:                     print $mfh '>'.
12708:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
12709:                             .'</'.$tag.'>';
12710:                 }
12711:             }
12712:             $output = 'ok';
12713:             print $logfile "\nWrote metadata";
12714:             close($mfh);
12715:         } else {
12716:             print $logfile "\nFailed to open metadata file";
12717:             $output = &mt('Could not write metadata');
12718:         }
12719:     }
12720:     return $output;
12721: }
12722: 
12723: sub notifysubscribed {
12724:     foreach my $targetsource (@{$modified_urls}){
12725:         next unless (ref($targetsource) eq 'ARRAY');
12726:         my ($target,$source)=@{$targetsource};
12727:         if ($source ne '') {
12728:             if (open(my $logfh,">>",$source.'.log')) {
12729:                 print $logfh "\nCleanup phase: Notifications\n";
12730:                 my @subscribed=&subscribed_hosts($target);
12731:                 foreach my $subhost (@subscribed) {
12732:                     print $logfh "\nNotifying host ".$subhost.':';
12733:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
12734:                     print $logfh $reply;
12735:                 }
12736:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
12737:                 foreach my $subhost (@subscribedmeta) {
12738:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
12739:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
12740:                                                         $subhost);
12741:                     print $logfh $reply;
12742:                 }
12743:                 print $logfh "\n============ Done ============\n";
12744:                 close($logfh);
12745:             }
12746:         }
12747:     }
12748:     return OK;
12749: }
12750: 
12751: sub subscribed_hosts {
12752:     my ($target) = @_;
12753:     my @subscribed;
12754:     if (open(my $fh,"<","$target.subscription")) {
12755:         while (my $subline=<$fh>) {
12756:             if ($subline =~ /^($match_lonid):/) {
12757:                 my $host = $1;
12758:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
12759:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
12760:                         push(@subscribed,$host);
12761:                     }
12762:                 }
12763:             }
12764:         }
12765:     }
12766:     return @subscribed;
12767: }
12768: 
12769: sub check_switchserver {
12770:     my ($dom,$confname) = @_;
12771:     my ($allowed,$switchserver);
12772:     my $home = &Apache::lonnet::homeserver($confname,$dom);
12773:     if ($home eq 'no_host') {
12774:         $home = &Apache::lonnet::domain($dom,'primary');
12775:     }
12776:     my @ids=&Apache::lonnet::current_machine_ids();
12777:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
12778:     if (!$allowed) {
12779: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
12780:     }
12781:     return $switchserver;
12782: }
12783: 
12784: sub modify_quotas {
12785:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12786:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
12787:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
12788:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
12789:         $validationfieldsref);
12790:     if ($action eq 'quotas') {
12791:         $context = 'tools'; 
12792:     } else {
12793:         $context = $action;
12794:     }
12795:     if ($context eq 'requestcourses') {
12796:         @usertools = ('official','unofficial','community','textbook','placement','lti');
12797:         @options =('norequest','approval','validate','autolimit');
12798:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
12799:         %titles = &courserequest_titles();
12800:         $toolregexp = join('|',@usertools);
12801:         %conditions = &courserequest_conditions();
12802:         $confname = $dom.'-domainconfig';
12803:         my $servadm = $r->dir_config('lonAdmEMail');
12804:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12805:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
12806:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
12807:     } elsif ($context eq 'requestauthor') {
12808:         @usertools = ('author');
12809:         %titles = &authorrequest_titles();
12810:     } else {
12811:         @usertools = ('aboutme','blog','webdav','portfolio');
12812:         %titles = &tool_titles();
12813:     }
12814:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12815:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12816:     foreach my $key (keys(%env)) {
12817:         if ($context eq 'requestcourses') {
12818:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
12819:                 my $item = $1;
12820:                 my $type = $2;
12821:                 if ($type =~ /^limit_(.+)/) {
12822:                     $limithash{$item}{$1} = $env{$key};
12823:                 } else {
12824:                     $confhash{$item}{$type} = $env{$key};
12825:                 }
12826:             }
12827:         } elsif ($context eq 'requestauthor') {
12828:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
12829:                 $confhash{$1} = $env{$key};
12830:             }
12831:         } else {
12832:             if ($key =~ /^form\.quota_(.+)$/) {
12833:                 $confhash{'defaultquota'}{$1} = $env{$key};
12834:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
12835:                 $confhash{'authorquota'}{$1} = $env{$key};
12836:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
12837:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
12838:             }
12839:         }
12840:     }
12841:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12842:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
12843:         @approvalnotify = sort(@approvalnotify);
12844:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
12845:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
12846:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
12847:         foreach my $type (@hasuniquecode) {
12848:             if (grep(/^\Q$type\E$/,@crstypes)) {
12849:                 $confhash{'uniquecode'}{$type} = 1;
12850:             }
12851:         }
12852:         my (%newbook,%allpos);
12853:         if ($context eq 'requestcourses') {
12854:             foreach my $type ('textbooks','templates') {
12855:                 @{$allpos{$type}} = (); 
12856:                 my $invalid;
12857:                 if ($type eq 'textbooks') {
12858:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
12859:                 } else {
12860:                     $invalid = &mt('Invalid LON-CAPA course for template');
12861:                 }
12862:                 if ($env{'form.'.$type.'_addbook'}) {
12863:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
12864:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
12865:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
12866:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
12867:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12868:                         } else {
12869:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
12870:                             my $position = $env{'form.'.$type.'_addbook_pos'};
12871:                             $position =~ s/\D+//g;
12872:                             if ($position ne '') {
12873:                                 $allpos{$type}[$position] = $newbook{$type};
12874:                             }
12875:                         }
12876:                     } else {
12877:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12878:                     }
12879:                 }
12880:             } 
12881:         }
12882:         if (ref($domconfig{$action}) eq 'HASH') {
12883:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
12884:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
12885:                     $changes{'notify'}{'approval'} = 1;
12886:                 }
12887:             } else {
12888:                 if ($confhash{'notify'}{'approval'}) {
12889:                     $changes{'notify'}{'approval'} = 1;
12890:                 }
12891:             }
12892:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
12893:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
12894:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
12895:                         unless ($confhash{'uniquecode'}{$crstype}) {
12896:                             $changes{'uniquecode'} = 1;
12897:                         }
12898:                     }
12899:                     unless ($changes{'uniquecode'}) {
12900:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
12901:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
12902:                                 $changes{'uniquecode'} = 1;
12903:                             }
12904:                         }
12905:                     }
12906:                } else {
12907:                    $changes{'uniquecode'} = 1;
12908:                }
12909:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
12910:                 $changes{'uniquecode'} = 1;
12911:             }
12912:             if ($context eq 'requestcourses') {
12913:                 foreach my $type ('textbooks','templates') {
12914:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
12915:                         my %deletions;
12916:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
12917:                         if (@todelete) {
12918:                             map { $deletions{$_} = 1; } @todelete;
12919:                         }
12920:                         my %imgdeletions;
12921:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
12922:                         if (@todeleteimages) {
12923:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
12924:                         }
12925:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
12926:                         for (my $i=0; $i<=$maxnum; $i++) {
12927:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
12928:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
12929:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
12930:                                 if ($deletions{$key}) {
12931:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
12932:                                         #FIXME need to obsolete item in RES space
12933:                                     }
12934:                                     next;
12935:                                 } else {
12936:                                     my $newpos = $env{'form.'.$itemid};
12937:                                     $newpos =~ s/\D+//g;
12938:                                     foreach my $item ('subject','title','publisher','author') {
12939:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12940:                                                  ($type eq 'templates'));
12941:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
12942:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
12943:                                             $changes{$type}{$key} = 1;
12944:                                         }
12945:                                     }
12946:                                     $allpos{$type}[$newpos] = $key;
12947:                                 }
12948:                                 if ($imgdeletions{$key}) {
12949:                                     $changes{$type}{$key} = 1;
12950:                                     #FIXME need to obsolete item in RES space
12951:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
12952:                                     my ($cdom,$cnum) = split(/_/,$key);
12953:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12954:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12955:                                     } else {
12956:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
12957:                                                                                       $cdom,$cnum,$type,$configuserok,
12958:                                                                                       $switchserver,$author_ok);
12959:                                         if ($imgurl) {
12960:                                             $confhash{$type}{$key}{'image'} = $imgurl;
12961:                                             $changes{$type}{$key} = 1; 
12962:                                         }
12963:                                         if ($error) {
12964:                                             &Apache::lonnet::logthis($error);
12965:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12966:                                         }
12967:                                     }
12968:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
12969:                                     $confhash{$type}{$key}{'image'} = 
12970:                                         $domconfig{$action}{$type}{$key}{'image'};
12971:                                 }
12972:                             }
12973:                         }
12974:                     }
12975:                 }
12976:             }
12977:         } else {
12978:             if ($confhash{'notify'}{'approval'}) {
12979:                 $changes{'notify'}{'approval'} = 1;
12980:             }
12981:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
12982:                 $changes{'uniquecode'} = 1;
12983:             }
12984:         }
12985:         if ($context eq 'requestcourses') {
12986:             foreach my $type ('textbooks','templates') {
12987:                 if ($newbook{$type}) {
12988:                     $changes{$type}{$newbook{$type}} = 1;
12989:                     foreach my $item ('subject','title','publisher','author') {
12990:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12991:                                  ($type eq 'template'));
12992:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
12993:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
12994:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
12995:                         }
12996:                     }
12997:                     if ($type eq 'textbooks') {
12998:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
12999:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
13000:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
13001:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
13002:                             } else {
13003:                                 my ($imageurl,$error) =
13004:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
13005:                                                             $configuserok,$switchserver,$author_ok);
13006:                                 if ($imageurl) {
13007:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
13008:                                 }
13009:                                 if ($error) {
13010:                                     &Apache::lonnet::logthis($error);
13011:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13012:                                 }
13013:                             }
13014:                         }
13015:                     }
13016:                 }
13017:                 if (@{$allpos{$type}} > 0) {
13018:                     my $idx = 0;
13019:                     foreach my $item (@{$allpos{$type}}) {
13020:                         if ($item ne '') {
13021:                             $confhash{$type}{$item}{'order'} = $idx;
13022:                             if (ref($domconfig{$action}) eq 'HASH') {
13023:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
13024:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
13025:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
13026:                                             $changes{$type}{$item} = 1;
13027:                                         }
13028:                                     }
13029:                                 }
13030:                             }
13031:                             $idx ++;
13032:                         }
13033:                     }
13034:                 }
13035:             }
13036:             if (ref($validationitemsref) eq 'ARRAY') {
13037:                 foreach my $item (@{$validationitemsref}) {
13038:                     if ($item eq 'fields') {
13039:                         my @changed;
13040:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
13041:                         if (@{$confhash{'validation'}{$item}} > 0) {
13042:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
13043:                         }
13044:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13045:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13046:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
13047:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
13048:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
13049:                                 } else {
13050:                                     @changed = @{$confhash{'validation'}{$item}};
13051:                                 }
13052:                             } else {
13053:                                 @changed = @{$confhash{'validation'}{$item}};
13054:                             }
13055:                         } else {
13056:                             @changed = @{$confhash{'validation'}{$item}};
13057:                         }
13058:                         if (@changed) {
13059:                             if ($confhash{'validation'}{$item}) {
13060:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
13061:                             } else {
13062:                                 $changes{'validation'}{$item} = &mt('None');
13063:                             }
13064:                         }
13065:                     } else {
13066:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
13067:                         if ($item eq 'markup') {
13068:                             if ($env{'form.requestcourses_validation_'.$item}) {
13069:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
13070:                             }
13071:                         }
13072:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13073:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13074:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
13075:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13076:                                 }
13077:                             } else {
13078:                                 if ($confhash{'validation'}{$item} ne '') {
13079:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13080:                                 }
13081:                             }
13082:                         } else {
13083:                             if ($confhash{'validation'}{$item} ne '') {
13084:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
13085:                             }
13086:                         }
13087:                     }
13088:                 }
13089:             }
13090:             if ($env{'form.validationdc'}) {
13091:                 my $newval = $env{'form.validationdc'};
13092:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
13093:                 if (exists($domcoords{$newval})) {
13094:                     $confhash{'validation'}{'dc'} = $newval;
13095:                 }
13096:             }
13097:             if (ref($confhash{'validation'}) eq 'HASH') {
13098:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13099:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13100:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
13101:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
13102:                                 if ($confhash{'validation'}{'dc'} eq '') {
13103:                                     $changes{'validation'}{'dc'} = &mt('None');
13104:                                 } else {
13105:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13106:                                 }
13107:                             }
13108:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
13109:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13110:                         }
13111:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
13112:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13113:                     }
13114:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
13115:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
13116:                 }
13117:             } else {
13118:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
13119:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
13120:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
13121:                             $changes{'validation'}{'dc'} = &mt('None');
13122:                         }
13123:                     }
13124:                 }
13125:             }
13126:         }
13127:     } else {
13128:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
13129:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
13130:     }
13131:     foreach my $item (@usertools) {
13132:         foreach my $type (@{$types},'default','_LC_adv') {
13133:             my $unset; 
13134:             if ($context eq 'requestcourses') {
13135:                 $unset = '0';
13136:                 if ($type eq '_LC_adv') {
13137:                     $unset = '';
13138:                 }
13139:                 if ($confhash{$item}{$type} eq 'autolimit') {
13140:                     $confhash{$item}{$type} .= '=';
13141:                     unless ($limithash{$item}{$type} =~ /\D/) {
13142:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
13143:                     }
13144:                 }
13145:             } elsif ($context eq 'requestauthor') {
13146:                 $unset = '0';
13147:                 if ($type eq '_LC_adv') {
13148:                     $unset = '';
13149:                 }
13150:             } else {
13151:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
13152:                     $confhash{$item}{$type} = 1;
13153:                 } else {
13154:                     $confhash{$item}{$type} = 0;
13155:                 }
13156:             }
13157:             if (ref($domconfig{$action}) eq 'HASH') {
13158:                 if ($action eq 'requestauthor') {
13159:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
13160:                         $changes{$type} = 1;
13161:                     }
13162:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
13163:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
13164:                         $changes{$item}{$type} = 1;
13165:                     }
13166:                 } else {
13167:                     if ($context eq 'requestcourses') {
13168:                         if ($confhash{$item}{$type} ne $unset) {
13169:                             $changes{$item}{$type} = 1;
13170:                         }
13171:                     } else {
13172:                         if (!$confhash{$item}{$type}) {
13173:                             $changes{$item}{$type} = 1;
13174:                         }
13175:                     }
13176:                 }
13177:             } else {
13178:                 if ($context eq 'requestcourses') {
13179:                     if ($confhash{$item}{$type} ne $unset) {
13180:                         $changes{$item}{$type} = 1;
13181:                     }
13182:                 } elsif ($context eq 'requestauthor') {
13183:                     if ($confhash{$type} ne $unset) {
13184:                         $changes{$type} = 1;
13185:                     }
13186:                 } else {
13187:                     if (!$confhash{$item}{$type}) {
13188:                         $changes{$item}{$type} = 1;
13189:                     }
13190:                 }
13191:             }
13192:         }
13193:     }
13194:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13195:         if (ref($domconfig{'quotas'}) eq 'HASH') {
13196:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
13197:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
13198:                     if (exists($confhash{'defaultquota'}{$key})) {
13199:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
13200:                             $changes{'defaultquota'}{$key} = 1;
13201:                         }
13202:                     } else {
13203:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
13204:                     }
13205:                 }
13206:             } else {
13207:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
13208:                     if (exists($confhash{'defaultquota'}{$key})) {
13209:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
13210:                             $changes{'defaultquota'}{$key} = 1;
13211:                         }
13212:                     } else {
13213:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
13214:                     }
13215:                 }
13216:             }
13217:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
13218:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
13219:                     if (exists($confhash{'authorquota'}{$key})) {
13220:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
13221:                             $changes{'authorquota'}{$key} = 1;
13222:                         }
13223:                     } else {
13224:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
13225:                     }
13226:                 }
13227:             }
13228:         }
13229:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
13230:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
13231:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
13232:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
13233:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
13234:                             $changes{'defaultquota'}{$key} = 1;
13235:                         }
13236:                     } else {
13237:                         if (!exists($domconfig{'quotas'}{$key})) {
13238:                             $changes{'defaultquota'}{$key} = 1;
13239:                         }
13240:                     }
13241:                 } else {
13242:                     $changes{'defaultquota'}{$key} = 1;
13243:                 }
13244:             }
13245:         }
13246:         if (ref($confhash{'authorquota'}) eq 'HASH') {
13247:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
13248:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
13249:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
13250:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
13251:                             $changes{'authorquota'}{$key} = 1;
13252:                         }
13253:                     } else {
13254:                         $changes{'authorquota'}{$key} = 1;
13255:                     }
13256:                 } else {
13257:                     $changes{'authorquota'}{$key} = 1;
13258:                 }
13259:             }
13260:         }
13261:     }
13262: 
13263:     if ($context eq 'requestauthor') {
13264:         $domdefaults{'requestauthor'} = \%confhash;
13265:     } else {
13266:         foreach my $key (keys(%confhash)) {
13267:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
13268:                 $domdefaults{$key} = $confhash{$key};
13269:             }
13270:         }
13271:     }
13272: 
13273:     my %quotahash = (
13274:                       $action => { %confhash }
13275:                     );
13276:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
13277:                                              $dom);
13278:     if ($putresult eq 'ok') {
13279:         if (keys(%changes) > 0) {
13280:             my $cachetime = 24*60*60;
13281:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
13282:             if (ref($lastactref) eq 'HASH') {
13283:                 $lastactref->{'domdefaults'} = 1;
13284:             }
13285:             $resulttext = &mt('Changes made:').'<ul>';
13286:             unless (($context eq 'requestcourses') ||
13287:                     ($context eq 'requestauthor')) {
13288:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
13289:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
13290:                     foreach my $type (@{$types},'default') {
13291:                         if (defined($changes{'defaultquota'}{$type})) {
13292:                             my $typetitle = $usertypes->{$type};
13293:                             if ($type eq 'default') {
13294:                                 $typetitle = $othertitle;
13295:                             }
13296:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
13297:                         }
13298:                     }
13299:                     $resulttext .= '</ul></li>';
13300:                 }
13301:                 if (ref($changes{'authorquota'}) eq 'HASH') {
13302:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
13303:                     foreach my $type (@{$types},'default') {
13304:                         if (defined($changes{'authorquota'}{$type})) {
13305:                             my $typetitle = $usertypes->{$type};
13306:                             if ($type eq 'default') {
13307:                                 $typetitle = $othertitle;
13308:                             }
13309:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
13310:                         }
13311:                     }
13312:                     $resulttext .= '</ul></li>';
13313:                 }
13314:             }
13315:             my %newenv;
13316:             foreach my $item (@usertools) {
13317:                 my (%haschgs,%inconf);
13318:                 if ($context eq 'requestauthor') {
13319:                     %haschgs = %changes;
13320:                     %inconf = %confhash;
13321:                 } else {
13322:                     if (ref($changes{$item}) eq 'HASH') {
13323:                         %haschgs = %{$changes{$item}};
13324:                     }
13325:                     if (ref($confhash{$item}) eq 'HASH') {
13326:                         %inconf = %{$confhash{$item}};
13327:                     }
13328:                 }
13329:                 if (keys(%haschgs) > 0) {
13330:                     my $newacc = 
13331:                         &Apache::lonnet::usertools_access($env{'user.name'},
13332:                                                           $env{'user.domain'},
13333:                                                           $item,'reload',$context);
13334:                     if (($context eq 'requestcourses') ||
13335:                         ($context eq 'requestauthor')) {
13336:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
13337:                             $newenv{'environment.canrequest.'.$item} = $newacc;
13338:                         }
13339:                     } else {
13340:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
13341:                             $newenv{'environment.availabletools.'.$item} = $newacc;
13342:                         }
13343:                     }
13344:                     unless ($context eq 'requestauthor') {
13345:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
13346:                     }
13347:                     foreach my $type (@{$types},'default','_LC_adv') {
13348:                         if ($haschgs{$type}) {
13349:                             my $typetitle = $usertypes->{$type};
13350:                             if ($type eq 'default') {
13351:                                 $typetitle = $othertitle;
13352:                             } elsif ($type eq '_LC_adv') {
13353:                                 $typetitle = 'LON-CAPA Advanced Users'; 
13354:                             }
13355:                             if ($inconf{$type}) {
13356:                                 if ($context eq 'requestcourses') {
13357:                                     my $cond;
13358:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
13359:                                         if ($1 eq '') {
13360:                                             $cond = &mt('(Automatic processing of any request).');
13361:                                         } else {
13362:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
13363:                                         }
13364:                                     } else { 
13365:                                         $cond = $conditions{$inconf{$type}};
13366:                                     }
13367:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
13368:                                 } elsif ($context eq 'requestauthor') {
13369:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
13370:                                                              $titles{$inconf{$type}},$typetitle);
13371: 
13372:                                 } else {
13373:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
13374:                                 }
13375:                             } else {
13376:                                 if ($type eq '_LC_adv') {
13377:                                     if ($inconf{$type} eq '0') {
13378:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
13379:                                     } else { 
13380:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
13381:                                     }
13382:                                 } else {
13383:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
13384:                                 }
13385:                             }
13386:                         }
13387:                     }
13388:                     unless ($context eq 'requestauthor') {
13389:                         $resulttext .= '</ul></li>';
13390:                     }
13391:                 }
13392:             }
13393:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
13394:                 if (ref($changes{'notify'}) eq 'HASH') {
13395:                     if ($changes{'notify'}{'approval'}) {
13396:                         if (ref($confhash{'notify'}) eq 'HASH') {
13397:                             if ($confhash{'notify'}{'approval'}) {
13398:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
13399:                             } else {
13400:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
13401:                             }
13402:                         }
13403:                     }
13404:                 }
13405:             }
13406:             if ($action eq 'requestcourses') {
13407:                 my @offon = ('off','on');
13408:                 if ($changes{'uniquecode'}) {
13409:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
13410:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
13411:                         $resulttext .= '<li>'.
13412:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
13413:                                        '</li>';
13414:                     } else {
13415:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
13416:                                        '</li>';
13417:                     }
13418:                 }
13419:                 foreach my $type ('textbooks','templates') {
13420:                     if (ref($changes{$type}) eq 'HASH') {
13421:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
13422:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
13423:                             my %coursehash = &Apache::lonnet::coursedescription($key);
13424:                             my $coursetitle = $coursehash{'description'};
13425:                             my $position = $confhash{$type}{$key}{'order'} + 1;
13426:                             $resulttext .= '<li>';
13427:                             foreach my $item ('subject','title','publisher','author') {
13428:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
13429:                                          ($type eq 'templates'));
13430:                                 my $name = $item.':';
13431:                                 $name =~ s/^(\w)/\U$1/;
13432:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
13433:                             }
13434:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
13435:                             if ($type eq 'textbooks') {
13436:                                 if ($confhash{$type}{$key}{'image'}) {
13437:                                     $resulttext .= ' '.&mt('Image: [_1]',
13438:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
13439:                                                    ' alt="Textbook cover" />').'<br />';
13440:                                 }
13441:                             }
13442:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
13443:                         }
13444:                         $resulttext .= '</ul></li>';
13445:                     }
13446:                 }
13447:                 if (ref($changes{'validation'}) eq 'HASH') {
13448:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
13449:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
13450:                         foreach my $item (@{$validationitemsref}) {
13451:                             if (exists($changes{'validation'}{$item})) {
13452:                                 if ($item eq 'markup') {
13453:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13454:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
13455:                                 } else {
13456:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13457:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
13458:                                 }
13459:                             }
13460:                         }
13461:                         if (exists($changes{'validation'}{'dc'})) {
13462:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
13463:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
13464:                         }
13465:                     }
13466:                 }
13467:             }
13468:             $resulttext .= '</ul>';
13469:             if (keys(%newenv)) {
13470:                 &Apache::lonnet::appenv(\%newenv);
13471:             }
13472:         } else {
13473:             if ($context eq 'requestcourses') {
13474:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
13475:             } elsif ($context eq 'requestauthor') {
13476:                 $resulttext = &mt('No changes made to rights to request author space.');
13477:             } else {
13478:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
13479:             }
13480:         }
13481:     } else {
13482:         $resulttext = '<span class="LC_error">'.
13483: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13484:     }
13485:     if ($errors) {
13486:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
13487:                        '<ul>'.$errors.'</ul></p>';
13488:     }
13489:     return $resulttext;
13490: }
13491: 
13492: sub process_textbook_image {
13493:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
13494:     my $filename = $env{'form.'.$caller.'.filename'};
13495:     my ($error,$url);
13496:     my ($width,$height) = (50,50);
13497:     if ($configuserok eq 'ok') {
13498:         if ($switchserver) {
13499:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
13500:                          $switchserver);
13501:         } elsif ($author_ok eq 'ok') {
13502:             my ($result,$imageurl) =
13503:                 &publishlogo($r,'upload',$caller,$dom,$confname,
13504:                              "$type/$cdom/$cnum/cover",$width,$height);
13505:             if ($result eq 'ok') {
13506:                 $url = $imageurl;
13507:             } else {
13508:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
13509:             }
13510:         } else {
13511:             $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);
13512:         }
13513:     } else {
13514:         $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);
13515:     }
13516:     return ($url,$error);
13517: }
13518: 
13519: sub modify_ltitools {
13520:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13521:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13522:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
13523:     my $confname = $dom.'-domainconfig';
13524:     my $servadm = $r->dir_config('lonAdmEMail');
13525:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13526:     my (%posslti,%possfield);
13527:     my @courseroles = ('cc','in','ta','ep','st');
13528:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
13529:     map { $posslti{$_} = 1; } @ltiroles;
13530:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
13531:     map { $possfield{$_} = 1; } @allfields;
13532:     my %lt = &ltitools_names(); 
13533:     if ($env{'form.ltitools_add'}) {
13534:         my $title = $env{'form.ltitools_add_title'};
13535:         $title =~ s/(`)/'/g;
13536:         ($newid,my $error) = &get_ltitools_id($dom,$title);
13537:         if ($newid) {
13538:             my $position = $env{'form.ltitools_add_pos'};
13539:             $position =~ s/\D+//g;
13540:             if ($position ne '') {
13541:                 $allpos[$position] = $newid;
13542:             }
13543:             $changes{$newid} = 1;
13544:             foreach my $item ('title','url','key','secret','lifetime') {
13545:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
13546:                 if ($item eq 'lifetime') {
13547:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
13548:                 }
13549:                 if ($env{'form.ltitools_add_'.$item}) {
13550:                     if (($item eq 'key') || ($item eq 'secret')) {
13551:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13552:                     } else {
13553:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13554:                     }
13555:                 }
13556:             }
13557:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
13558:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
13559:             }
13560:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
13561:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
13562:             }
13563:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
13564:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
13565:             } else {
13566:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
13567:             }
13568:             foreach my $item ('width','height','linktext','explanation') {
13569:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
13570:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
13571:                 if (($item eq 'width') || ($item eq 'height')) {
13572:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
13573:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
13574:                     }
13575:                 } else {
13576:                     if ($env{'form.ltitools_add_'.$item} ne '') {
13577:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
13578:                     }
13579:                 }
13580:             }
13581:             if ($env{'form.ltitools_add_target'} eq 'window') {
13582:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13583:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
13584:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13585:             } else {
13586:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
13587:             }
13588:             foreach my $item ('passback','roster') {
13589:                 if ($env{'form.ltitools_'.$item.'_add'}) {
13590:                     $confhash{$newid}{$item} = 1;
13591:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
13592:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
13593:                         $lifetime =~ s/^\s+|\s+$//g;
13594:                         if ($lifetime =~ /^\d+\.?\d*$/) {
13595:                             $confhash{$newid}{$item.'valid'} = $lifetime;
13596:                         }
13597:                     }
13598:                 }
13599:             }
13600:             if ($env{'form.ltitools_add_image.filename'} ne '') {
13601:                 my ($imageurl,$error) =
13602:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
13603:                                             $configuserok,$switchserver,$author_ok);
13604:                 if ($imageurl) {
13605:                     $confhash{$newid}{'image'} = $imageurl;
13606:                 }
13607:                 if ($error) {
13608:                     &Apache::lonnet::logthis($error);
13609:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13610:                 }
13611:             }
13612:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
13613:             foreach my $field (@fields) {
13614:                 if ($possfield{$field}) {
13615:                     if ($field eq 'roles') {
13616:                         foreach my $role (@courseroles) {
13617:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
13618:                             if (($choice ne '') && ($posslti{$choice})) {
13619:                                 $confhash{$newid}{'roles'}{$role} = $choice;
13620:                                 if ($role eq 'cc') {
13621:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
13622:                                 }
13623:                             }
13624:                         }
13625:                     } else {
13626:                         $confhash{$newid}{'fields'}{$field} = 1;
13627:                     }
13628:                 }
13629:             }
13630:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
13631:                 if ($confhash{$newid}{'fields'}{'user'}) {
13632:                     if ($env{'form.ltitools_userincdom_add'}) {
13633:                         $confhash{$newid}{'incdom'} = 1;
13634:                     }
13635:                 }
13636:             }
13637:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
13638:             foreach my $item (@courseconfig) {
13639:                 $confhash{$newid}{'crsconf'}{$item} = 1;
13640:             }
13641:             if ($env{'form.ltitools_add_custom'}) {
13642:                 my $name = $env{'form.ltitools_add_custom_name'};
13643:                 my $value = $env{'form.ltitools_add_custom_value'};
13644:                 $value =~ s/(`)/'/g;
13645:                 $name =~ s/(`)/'/g;
13646:                 $confhash{$newid}{'custom'}{$name} = $value;
13647:             }
13648:         } else {
13649:             my $error = &mt('Failed to acquire unique ID for new external tool');   
13650:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13651:         }
13652:     }
13653:     if (ref($domconfig{$action}) eq 'HASH') {
13654:         my %deletions;
13655:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
13656:         if (@todelete) {
13657:             map { $deletions{$_} = 1; } @todelete;
13658:         }
13659:         my %customadds;
13660:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
13661:         if (@newcustom) {
13662:             map { $customadds{$_} = 1; } @newcustom;
13663:         } 
13664:         my %imgdeletions;
13665:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
13666:         if (@todeleteimages) {
13667:             map { $imgdeletions{$_} = 1; } @todeleteimages;
13668:         }
13669:         my $maxnum = $env{'form.ltitools_maxnum'};
13670:         for (my $i=0; $i<=$maxnum; $i++) {
13671:             my $itemid = $env{'form.ltitools_id_'.$i};
13672:             $itemid =~ s/\D+//g;
13673:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13674:                 if ($deletions{$itemid}) {
13675:                     if ($domconfig{$action}{$itemid}{'image'}) {
13676:                         #FIXME need to obsolete item in RES space
13677:                     }
13678:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
13679:                     next;
13680:                 } else {
13681:                     my $newpos = $env{'form.ltitools_'.$itemid};
13682:                     $newpos =~ s/\D+//g;
13683:                     foreach my $item ('title','url','lifetime') {
13684:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13685:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
13686:                             $changes{$itemid} = 1;
13687:                         }
13688:                     }
13689:                     foreach my $item ('key','secret') {
13690:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13691:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
13692:                             $changes{$itemid} = 1;
13693:                         }
13694:                     }
13695:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
13696:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
13697:                     }
13698:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
13699:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
13700:                     }
13701:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
13702:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
13703:                     } else {
13704:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
13705:                     }
13706:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
13707:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
13708:                             $changes{$itemid} = 1;
13709:                         }
13710:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
13711:                         $changes{$itemid} = 1;
13712:                     }
13713:                     foreach my $size ('width','height') {
13714:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
13715:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
13716:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
13717:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
13718:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13719:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
13720:                                     $changes{$itemid} = 1;
13721:                                 }
13722:                             } else {
13723:                                 $changes{$itemid} = 1;
13724:                             }
13725:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13726:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
13727:                                 $changes{$itemid} = 1;
13728:                             }
13729:                         }
13730:                     }
13731:                     foreach my $item ('linktext','explanation') {
13732:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
13733:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
13734:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
13735:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13736:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13737:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
13738:                                     $changes{$itemid} = 1;
13739:                                 }
13740:                             } else {
13741:                                 $changes{$itemid} = 1;
13742:                             }
13743:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13744:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
13745:                                 $changes{$itemid} = 1;
13746:                             }
13747:                         }
13748:                     }
13749:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
13750:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13751:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
13752:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13753:                     } else {
13754:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
13755:                     }
13756:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13757:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
13758:                             $changes{$itemid} = 1;
13759:                         }
13760:                     } else {
13761:                         $changes{$itemid} = 1;
13762:                     }
13763:                     foreach my $extra ('passback','roster') {
13764:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
13765:                             $confhash{$itemid}{$extra} = 1;
13766:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
13767:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
13768:                                 $lifetime =~ s/^\s+|\s+$//g;
13769:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
13770:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
13771:                                 }
13772:                             }
13773:                         }
13774:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
13775:                             $changes{$itemid} = 1;
13776:                         }
13777:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
13778:                             $changes{$itemid} = 1;
13779:                         }
13780:                     }
13781:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
13782:                     foreach my $item ('label','title','target','linktext','explanation','append') {
13783:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
13784:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
13785:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
13786:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
13787:                                     $changes{$itemid} = 1;
13788:                                 }
13789:                             } else {
13790:                                 $changes{$itemid} = 1;
13791:                             }
13792:                         }
13793:                     }
13794:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
13795:                     foreach my $field (@fields) {
13796:                         if ($possfield{$field}) {
13797:                             if ($field eq 'roles') {
13798:                                 foreach my $role (@courseroles) {
13799:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
13800:                                     if (($choice ne '') && ($posslti{$choice})) {
13801:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
13802:                                         if ($role eq 'cc') {
13803:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
13804:                                         }
13805:                                     }
13806:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
13807:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
13808:                                             $changes{$itemid} = 1;
13809:                                         }
13810:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
13811:                                         $changes{$itemid} = 1;
13812:                                     }
13813:                                 }
13814:                             } else {
13815:                                 $confhash{$itemid}{'fields'}{$field} = 1;
13816:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
13817:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
13818:                                         $changes{$itemid} = 1;
13819:                                     }
13820:                                 } else {
13821:                                     $changes{$itemid} = 1;
13822:                                 }
13823:                             }
13824:                         }
13825:                     }
13826:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
13827:                         if ($confhash{$itemid}{'fields'}{'user'}) {
13828:                             if ($env{'form.ltitools_userincdom_'.$i}) {
13829:                                 $confhash{$itemid}{'incdom'} = 1;
13830:                             }
13831:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
13832:                                 $changes{$itemid} = 1;
13833:                             }
13834:                         }
13835:                     }
13836:                     $allpos[$newpos] = $itemid;
13837:                 }
13838:                 if ($imgdeletions{$itemid}) {
13839:                     $changes{$itemid} = 1;
13840:                     #FIXME need to obsolete item in RES space
13841:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
13842:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
13843:                                                                  $itemid,$configuserok,$switchserver,
13844:                                                                  $author_ok);
13845:                     if ($imgurl) {
13846:                         $confhash{$itemid}{'image'} = $imgurl;
13847:                         $changes{$itemid} = 1;
13848:                     }
13849:                     if ($error) {
13850:                         &Apache::lonnet::logthis($error);
13851:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13852:                     }
13853:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
13854:                     $confhash{$itemid}{'image'} =
13855:                        $domconfig{$action}{$itemid}{'image'};
13856:                 }
13857:                 if ($customadds{$i}) {
13858:                     my $name = $env{'form.ltitools_custom_name_'.$i};
13859:                     $name =~ s/(`)/'/g;
13860:                     $name =~ s/^\s+//;
13861:                     $name =~ s/\s+$//;
13862:                     my $value = $env{'form.ltitools_custom_value_'.$i};
13863:                     $value =~ s/(`)/'/g;
13864:                     $value =~ s/^\s+//;
13865:                     $value =~ s/\s+$//;
13866:                     if ($name ne '') {
13867:                         $confhash{$itemid}{'custom'}{$name} = $value;
13868:                         $changes{$itemid} = 1;
13869:                     }
13870:                 }
13871:                 my %customdels;
13872:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
13873:                 if (@customdeletions) {
13874:                     $changes{$itemid} = 1;
13875:                 }
13876:                 map { $customdels{$_} = 1; } @customdeletions;
13877:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
13878:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
13879:                         unless ($customdels{$key}) {
13880:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
13881:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
13882:                             }
13883:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
13884:                                 $changes{$itemid} = 1;
13885:                             }
13886:                         }
13887:                     }
13888:                 }
13889:                 unless ($changes{$itemid}) {
13890:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
13891:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
13892:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
13893:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
13894:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
13895:                                         $changes{$itemid} = 1;
13896:                                         last;
13897:                                     }
13898:                                 }
13899:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
13900:                                 $changes{$itemid} = 1;
13901:                             }
13902:                         }
13903:                         last if ($changes{$itemid});
13904:                     }
13905:                 }
13906:             }
13907:         }
13908:     }
13909:     if (@allpos > 0) {
13910:         my $idx = 0;
13911:         foreach my $itemid (@allpos) {
13912:             if ($itemid ne '') {
13913:                 $confhash{$itemid}{'order'} = $idx;
13914:                 if (ref($domconfig{$action}) eq 'HASH') {
13915:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13916:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
13917:                             $changes{$itemid} = 1;
13918:                         }
13919:                     }
13920:                 }
13921:                 $idx ++;
13922:             }
13923:         }
13924:     }
13925:     my %ltitoolshash = (
13926:                           $action => { %confhash }
13927:                        );
13928:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
13929:                                              $dom);
13930:     if ($putresult eq 'ok') {
13931:         my %ltienchash = (
13932:                              $action => { %encconfig }
13933:                          );
13934:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
13935:         if (keys(%changes) > 0) {
13936:             my $cachetime = 24*60*60;
13937:             my %ltiall = %confhash;
13938:             foreach my $id (keys(%ltiall)) {
13939:                 if (ref($encconfig{$id}) eq 'HASH') {
13940:                     foreach my $item ('key','secret') {
13941:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
13942:                     }
13943:                 }
13944:             }
13945:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
13946:             if (ref($lastactref) eq 'HASH') {
13947:                 $lastactref->{'ltitools'} = 1;
13948:             }
13949:             $resulttext = &mt('Changes made:').'<ul>';
13950:             my %bynum;
13951:             foreach my $itemid (sort(keys(%changes))) {
13952:                 my $position = $confhash{$itemid}{'order'};
13953:                 $bynum{$position} = $itemid;
13954:             }
13955:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13956:                 my $itemid = $bynum{$pos}; 
13957:                 if (ref($confhash{$itemid}) ne 'HASH') {
13958:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13959:                 } else {
13960:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
13961:                     if ($confhash{$itemid}{'image'}) {
13962:                         $resulttext .= '&nbsp;'.
13963:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
13964:                                        ' alt="'.&mt('Tool Provider icon').'" />';
13965:                     }
13966:                     $resulttext .= '</li><ul>';
13967:                     my $position = $pos + 1;
13968:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13969:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
13970:                         if ($confhash{$itemid}{$item} ne '') {
13971:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
13972:                         }
13973:                     }
13974:                     if ($encconfig{$itemid}{'key'} ne '') {
13975:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
13976:                     }
13977:                     if ($encconfig{$itemid}{'secret'} ne '') {
13978:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
13979:                         my $num = length($encconfig{$itemid}{'secret'});
13980:                         $resulttext .= ('*'x$num).'</li>';
13981:                     }
13982:                     $resulttext .= '<li>'.&mt('Configurable in course:');
13983:                     my @possconfig = ('label','title','target','linktext','explanation','append');
13984:                     my $numconfig = 0; 
13985:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
13986:                         foreach my $item (@possconfig) {
13987:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
13988:                                 $numconfig ++;
13989:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
13990:                             }
13991:                         }
13992:                     }
13993:                     if (!$numconfig) {
13994:                         $resulttext .= '&nbsp;'.&mt('None');
13995:                     }
13996:                     $resulttext .= '</li>';
13997:                     foreach my $item ('passback','roster') {
13998:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
13999:                         if ($confhash{$itemid}{$item}) {
14000:                             $resulttext .= &mt('Yes');
14001:                             if ($confhash{$itemid}{$item.'valid'}) {
14002:                                 if ($item eq 'passback') {
14003:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
14004:                                                            $confhash{$itemid}{$item.'valid'});
14005:                                 } else {
14006:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
14007:                                                            $confhash{$itemid}{$item.'valid'});
14008:                                 }
14009:                             }
14010:                         } else {
14011:                             $resulttext .= &mt('No');
14012:                         }
14013:                         $resulttext .= '</li>';
14014:                     }
14015:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
14016:                         my $displaylist;
14017:                         if ($confhash{$itemid}{'display'}{'target'}) {
14018:                             $displaylist = &mt('Display target').':&nbsp;'.
14019:                                            $confhash{$itemid}{'display'}{'target'}.',';
14020:                         }
14021:                         foreach my $size ('width','height') { 
14022:                             if ($confhash{$itemid}{'display'}{$size}) {
14023:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
14024:                                                 $confhash{$itemid}{'display'}{$size}.',';
14025:                             }
14026:                         }
14027:                         if ($displaylist) {
14028:                             $displaylist =~ s/,$//;
14029:                             $resulttext .= '<li>'.$displaylist.'</li>';
14030:                         }
14031:                         foreach my $item ('linktext','explanation') {
14032:                             if ($confhash{$itemid}{'display'}{$item}) {
14033:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
14034:                             }
14035:                         }
14036:                     }
14037:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
14038:                         my $fieldlist;
14039:                         foreach my $field (@allfields) {
14040:                             if ($confhash{$itemid}{'fields'}{$field}) {
14041:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
14042:                             }
14043:                         }
14044:                         if ($fieldlist) {
14045:                             $fieldlist =~ s/,$//;
14046:                             if ($confhash{$itemid}{'fields'}{'user'}) {
14047:                                 if ($confhash{$itemid}{'incdom'}) {
14048:                                     $fieldlist .= ' ('.&mt('username:domain').')';
14049:                                 } else {
14050:                                     $fieldlist .= ' ('.&mt('username').')';
14051:                                 }
14052:                             }
14053:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
14054:                         }
14055:                     }
14056:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
14057:                         my $rolemaps;
14058:                         foreach my $role (@courseroles) {
14059:                             if ($confhash{$itemid}{'roles'}{$role}) {
14060:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
14061:                                              $confhash{$itemid}{'roles'}{$role}.',';
14062:                             }
14063:                         }
14064:                         if ($rolemaps) {
14065:                             $rolemaps =~ s/,$//; 
14066:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14067:                         }
14068:                     }
14069:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
14070:                         my $customlist;
14071:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
14072:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
14073:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
14074:                             } 
14075:                         }
14076:                         if ($customlist) {
14077:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
14078:                         }
14079:                     } 
14080:                     $resulttext .= '</ul></li>';
14081:                 }
14082:             }
14083:             $resulttext .= '</ul>';
14084:         } else {
14085:             $resulttext = &mt('No changes made.');
14086:         }
14087:     } else {
14088:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14089:     }
14090:     if ($errors) {
14091:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14092:                        $errors.'</ul>';
14093:     }
14094:     return $resulttext;
14095: }
14096: 
14097: sub process_ltitools_image {
14098:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
14099:     my $filename = $env{'form.'.$caller.'.filename'};
14100:     my ($error,$url);
14101:     my ($width,$height) = (21,21);
14102:     if ($configuserok eq 'ok') {
14103:         if ($switchserver) {
14104:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
14105:                          $switchserver);
14106:         } elsif ($author_ok eq 'ok') {
14107:             my ($result,$imageurl,$madethumb) =
14108:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14109:                              "ltitools/$itemid/icon",$width,$height);
14110:             if ($result eq 'ok') {
14111:                 if ($madethumb) {
14112:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
14113:                     my $imagethumb = "$path/tn-".$imagefile;
14114:                     $url = $imagethumb;
14115:                 } else {
14116:                     $url = $imageurl;
14117:                 }
14118:             } else {
14119:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14120:             }
14121:         } else {
14122:             $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);
14123:         }
14124:     } else {
14125:         $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);
14126:     }
14127:     return ($url,$error);
14128: }
14129: 
14130: sub get_ltitools_id {
14131:     my ($cdom,$title) = @_;
14132:     # get lock on ltitools db
14133:     my $lockhash = {
14134:                       lock => $env{'user.name'}.
14135:                               ':'.$env{'user.domain'},
14136:                    };
14137:     my $tries = 0;
14138:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
14139:     my ($id,$error);
14140:  
14141:     while (($gotlock ne 'ok') && ($tries<10)) {
14142:         $tries ++;
14143:         sleep (0.1);
14144:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
14145:     }
14146:     if ($gotlock eq 'ok') {
14147:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
14148:         if ($currids{'lock'}) {
14149:             delete($currids{'lock'});
14150:             if (keys(%currids)) {
14151:                 my @curr = sort { $a <=> $b } keys(%currids);
14152:                 if ($curr[-1] =~ /^\d+$/) {
14153:                     $id = 1 + $curr[-1];
14154:                 }
14155:             } else {
14156:                 $id = 1;
14157:             }
14158:             if ($id) {
14159:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
14160:                     $error = 'nostore';
14161:                 }
14162:             } else {
14163:                 $error = 'nonumber';
14164:             }
14165:         }
14166:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
14167:     } else {
14168:         $error = 'nolock';
14169:     }
14170:     return ($id,$error);
14171: }
14172: 
14173: sub modify_proctoring {
14174:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14175:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14176:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
14177:     my $confname = $dom.'-domainconfig';
14178:     my $servadm = $r->dir_config('lonAdmEMail');
14179:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14180:     my %providernames = &proctoring_providernames();
14181:     my $maxnum = scalar(keys(%providernames));
14182: 
14183:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
14184:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
14185:     if (ref($requref) eq 'HASH') {
14186:         %requserfields = %{$requref};
14187:     }
14188:     if (ref($opturef) eq 'HASH') {
14189:         %optuserfields = %{$opturef};
14190:     }
14191:     if (ref($defref) eq 'HASH') {
14192:         %defaults = %{$defref};
14193:     }
14194:     if (ref($extref) eq 'HASH') {
14195:         %extended = %{$extref};
14196:     }
14197:     if (ref($crsref) eq 'HASH') {
14198:         %crsconf = %{$crsref};
14199:     }
14200:     if (ref($rolesref) eq 'ARRAY') {
14201:         @courseroles = @{$rolesref};
14202:     }
14203:     if (ref($ltiref) eq 'ARRAY') {
14204:         @ltiroles = @{$ltiref};
14205:     }
14206: 
14207:     if (ref($domconfig{$action}) eq 'HASH') {
14208:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
14209:         if (@todeleteimages) {
14210:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14211:         }
14212:     }
14213:     my %customadds;
14214:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
14215:     if (@newcustom) {
14216:         map { $customadds{$_} = 1; } @newcustom;
14217:     }
14218:     foreach my $provider (sort(keys(%providernames))) {
14219:         $confhash{$provider} = {};
14220:         my $pos = $env{'form.proctoring_pos_'.$provider};
14221:         $pos =~ s/\D+//g;
14222:         $allpos[$pos] = $provider;
14223:         my (%current,%currentenc);
14224:         my $showroles = 0;
14225:         if (ref($domconfig{$action}) eq 'HASH') {
14226:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14227:                 %current = %{$domconfig{$action}{$provider}};
14228:                 foreach my $item ('key','secret') { 
14229:                     $currentenc{$item} = $current{$item};
14230:                     delete($current{$item});
14231:                 }
14232:             }
14233:         }
14234:         if ($env{'form.proctoring_available_'.$provider}) {
14235:             $confhash{$provider}{'available'} = 1;
14236:             unless ($current{'available'}) {
14237:                 $changes{$provider} = 1;
14238:             }
14239:         } else {
14240:             %{$confhash{$provider}} = %current;
14241:             %{$encconfhash{$provider}} = %currentenc;
14242:             $confhash{$provider}{'available'} = 0;
14243:             if ($current{'available'}) {
14244:                 $changes{$provider} = 1;
14245:             }
14246:         }
14247:         if ($confhash{$provider}{'available'}) {
14248:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
14249:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
14250:                 if ($field eq 'lifetime') {
14251:                     if ($possval =~ /^\d+$/) {
14252:                         $confhash{$provider}{$field} = $possval;
14253:                     }
14254:                 } elsif ($field eq 'version') {
14255:                     if ($possval =~ /^\d+\.\d+$/) {
14256:                         $confhash{$provider}{$field} = $possval;
14257:                     }
14258:                 } elsif ($field eq 'sigmethod') {
14259:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
14260:                         $confhash{$provider}{$field} = $possval;
14261:                     }
14262:                 } elsif ($field eq 'url') {
14263:                     $confhash{$provider}{$field} = $possval;
14264:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
14265:                     $encconfhash{$provider}{$field} = $possval;
14266:                     unless ($currentenc{$field} eq $possval) {
14267:                         $changes{$provider} = 1;
14268:                     }
14269:                 }
14270:                 unless (($field eq 'key') || ($field eq 'secret')) {
14271:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
14272:                         $changes{$provider} = 1;
14273:                     }
14274:                 }
14275:             }
14276:             if ($imgdeletions{$provider}) {
14277:                 $changes{$provider} = 1;
14278:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
14279:                 my ($imageurl,$error) =
14280:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
14281:                                               $configuserok,$switchserver,$author_ok);
14282:                 if ($imageurl) {
14283:                     $confhash{$provider}{'image'} = $imageurl;
14284:                     $changes{$provider} = 1; 
14285:                 }
14286:                 if ($error) {
14287:                     &Apache::lonnet::logthis($error);
14288:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14289:                 }
14290:             } elsif (exists($current{'image'})) {
14291:                 $confhash{$provider}{'image'} = $current{'image'};
14292:             }
14293:             if (ref($requserfields{$provider}) eq 'ARRAY') {
14294:                 if (@{$requserfields{$provider}} > 0) {
14295:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
14296:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
14297:                             $confhash{$provider}{'incdom'} = 1;
14298:                         }
14299:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
14300:                             $changes{$provider} = 1;
14301:                         }
14302:                     }
14303:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
14304:                         $showroles = 1;
14305:                     }
14306:                 }
14307:             }
14308:             $confhash{$provider}{'fields'} = [];
14309:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
14310:                 if (@{$optuserfields{$provider}} > 0) {
14311:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
14312:                     foreach my $field (@{$optuserfields{$provider}}) {
14313:                         if (grep(/^\Q$field\E$/,@optfields)) {
14314:                             push(@{$confhash{$provider}{'fields'}},$field);
14315:                         }
14316:                     }
14317:                 }
14318:                 if (ref($current{'fields'}) eq 'ARRAY') {
14319:                     unless ($changes{$provider}) {
14320:                         my @new = sort(@{$confhash{$provider}{'fields'}});
14321:                         my @old = sort(@{$current{'fields'}}); 
14322:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14323:                         if (@diffs) {
14324:                             $changes{$provider} = 1;
14325:                         }
14326:                     }
14327:                 } elsif (@{$confhash{$provider}{'fields'}}) {
14328:                     $changes{$provider} = 1;
14329:                 }
14330:             }
14331:             if (ref($defaults{$provider}) eq 'ARRAY') {  
14332:                 if (@{$defaults{$provider}} > 0) {
14333:                     my %options;
14334:                     if (ref($extended{$provider}) eq 'HASH') {
14335:                         %options = %{$extended{$provider}};
14336:                     }
14337:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
14338:                     foreach my $field (@{$defaults{$provider}}) {
14339:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
14340:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
14341:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
14342:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
14343:                             }
14344:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
14345:                             foreach my $inner (keys(%{$options{$field}})) {
14346:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
14347:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
14348:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
14349:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
14350:                                     }
14351:                                 } else {
14352:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
14353:                                 }
14354:                             }
14355:                         } else {
14356:                             if (grep(/^\Q$field\E$/,@checked)) {
14357:                                 push(@{$confhash{$provider}{'defaults'}},$field);
14358:                             }
14359:                         }
14360:                     }
14361:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
14362:                         if (ref($current{'defaults'}) eq 'ARRAY') {
14363:                             unless ($changes{$provider}) {
14364:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
14365:                                 my @old = sort(@{$current{'defaults'}});
14366:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14367:                                 if (@diffs) {
14368:                                     $changes{$provider} = 1; 
14369:                                 }
14370:                             }
14371:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
14372:                             if (@{$current{'defaults'}}) {
14373:                                 $changes{$provider} = 1;
14374:                             }
14375:                         }
14376:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
14377:                         if (ref($current{'defaults'}) eq 'HASH') {
14378:                             unless ($changes{$provider}) {
14379:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
14380:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
14381:                                         $changes{$provider} = 1;
14382:                                         last;
14383:                                     }
14384:                                 }
14385:                             }
14386:                             unless ($changes{$provider}) {
14387:                                 foreach my $key (keys(%{$current{'defaults'}})) {
14388:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
14389:                                         $changes{$provider} = 1;
14390:                                         last;
14391:                                     }
14392:                                 }
14393:                             }
14394:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
14395:                             $changes{$provider} = 1;
14396:                         }
14397:                     }
14398:                 }
14399:             }
14400:             if (ref($crsconf{$provider}) eq 'ARRAY') {
14401:                 if (@{$crsconf{$provider}} > 0) {
14402:                     $confhash{$provider}{'crsconf'} = [];
14403:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
14404:                     foreach my $crsfield (@{$crsconf{$provider}}) {
14405:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
14406:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
14407:                         }
14408:                     }
14409:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
14410:                         unless ($changes{$provider}) {  
14411:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
14412:                             my @old = sort(@{$current{'crsconf'}});
14413:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14414:                             if (@diffs) {
14415:                                 $changes{$provider} = 1;
14416:                             }
14417:                         }
14418:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
14419:                         $changes{$provider} = 1;
14420:                     }
14421:                 }
14422:             }
14423:             if ($showroles) {
14424:                 $confhash{$provider}{'roles'} = {};
14425:                 foreach my $role (@courseroles) {
14426:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
14427:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
14428:                         $confhash{$provider}{'roles'}{$role} = $poss;
14429:                     }
14430:                 }
14431:                 unless ($changes{$provider}) {
14432:                     if (ref($current{'roles'}) eq 'HASH') {
14433:                         foreach my $role (keys(%{$current{'roles'}})) {
14434:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
14435:                                 $changes{$provider} = 1;
14436:                                 last
14437:                             }
14438:                         }
14439:                         unless ($changes{$provider}) {
14440:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
14441:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
14442:                                     $changes{$provider} = 1;
14443:                                     last;
14444:                                 }
14445:                             }
14446:                         }
14447:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
14448:                         $changes{$provider} = 1;
14449:                     }
14450:                 }
14451:             }
14452:             if (ref($current{'custom'}) eq 'HASH') {
14453:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
14454:                 foreach my $key (keys(%{$current{'custom'}})) {
14455:                     if (grep(/^\Q$key\E$/,@customdels)) {
14456:                         $changes{$provider} = 1;
14457:                     } else {
14458:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
14459:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
14460:                             $changes{$provider} = 1;
14461:                         }
14462:                     }
14463:                 }
14464:             }
14465:             if ($customadds{$provider}) {
14466:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
14467:                 $name =~ s/(`)/'/g;
14468:                 $name =~ s/^\s+//;
14469:                 $name =~ s/\s+$//;
14470:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
14471:                 $value =~ s/(`)/'/g;
14472:                 $value =~ s/^\s+//;
14473:                 $value =~ s/\s+$//;
14474:                 if ($name ne '') {
14475:                     $confhash{$provider}{'custom'}{$name} = $value;
14476:                     $changes{$provider} = 1;
14477:                 }
14478:             }
14479:         }
14480:     }
14481:     if (@allpos > 0) {
14482:         my $idx = 0;
14483:         foreach my $provider (@allpos) {
14484:             if ($provider ne '') {
14485:                 $confhash{$provider}{'order'} = $idx;
14486:                 unless ($changes{$provider}) {
14487:                     if (ref($domconfig{$action}) eq 'HASH') {
14488:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14489:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
14490:                                 $changes{$provider} = 1;
14491:                             }
14492:                         }
14493:                     }
14494:                 }
14495:                 $idx ++;
14496:             }
14497:         }
14498:     }
14499:     my %proc_hash = (
14500:                           $action => { %confhash }
14501:                        );
14502:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
14503:                                              $dom);
14504:     if ($putresult eq 'ok') {
14505:         my %proc_enchash = (
14506:                              $action => { %encconfhash }
14507:                          );
14508:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
14509:         if (keys(%changes) > 0) {
14510:             my $cachetime = 24*60*60;
14511:             my %procall = %confhash;
14512:             foreach my $provider (keys(%procall)) {
14513:                 if (ref($encconfhash{$provider}) eq 'HASH') {
14514:                     foreach my $key ('key','secret') {
14515:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
14516:                     }
14517:                 }
14518:             }
14519:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
14520:             if (ref($lastactref) eq 'HASH') {
14521:                 $lastactref->{'proctoring'} = 1;
14522:             }
14523:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
14524:             my %bynum;
14525:             foreach my $provider (sort(keys(%changes))) {
14526:                 my $position = $confhash{$provider}{'order'};
14527:                 $bynum{$position} = $provider;
14528:             }
14529:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14530:                 my $provider = $bynum{$pos};
14531:                 my %lt = &proctoring_titles($provider);
14532:                 my %fieldtitles = &proctoring_fieldtitles($provider);
14533:                 if (!$confhash{$provider}{'available'}) {
14534:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
14535:                 } else {
14536:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
14537:                     if ($confhash{$provider}{'image'}) {
14538:                         $resulttext .= '&nbsp;'.
14539:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
14540:                                        ' alt="'.&mt('Proctoring icon').'" />';
14541:                     }
14542:                     $resulttext .= '<ul>';
14543:                     my $position = $pos + 1;
14544:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
14545:                     foreach my $key ('version','sigmethod','url','lifetime') {
14546:                         if ($confhash{$provider}{$key} ne '') {
14547:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
14548:                         }
14549:                     }
14550:                     if ($encconfhash{$provider}{'key'} ne '') {
14551:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
14552:                     }
14553:                     if ($encconfhash{$provider}{'secret'} ne '') {
14554:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
14555:                         my $num = length($encconfhash{$provider}{'secret'});
14556:                         $resulttext .= ('*'x$num).'</li>';
14557:                     }
14558:                     my (@fields,$showroles);
14559:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14560:                         push(@fields,@{$requserfields{$provider}});
14561:                     }
14562:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
14563:                         push(@fields,@{$confhash{$provider}{'fields'}});
14564:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
14565:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
14566:                     }
14567:                     if (@fields) {
14568:                         if (grep(/^roles$/,@fields)) {
14569:                             $showroles = 1;
14570:                         }
14571:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
14572:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
14573:                     }
14574:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14575:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
14576:                             if ($confhash{$provider}{'incdom'}) {
14577:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
14578:                             } else { 
14579:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
14580:                             }
14581:                         }
14582:                     }
14583:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
14584:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
14585:                             $resulttext .= '<li>'.$lt{'defa'};
14586:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
14587:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
14588:                             }
14589:                             $resulttext =~ s/,$//;
14590:                             $resulttext .= '</li>';
14591:                         }
14592:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
14593:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
14594:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
14595:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
14596:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
14597:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
14598:                                 }
14599:                             }
14600:                             $resulttext .= '</ul></li>';
14601:                         }
14602:                     }
14603:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
14604:                         if (@{$crsconf{$provider}} > 0) {
14605:                             $resulttext .= '<li>'.&mt('Configurable in course:');
14606:                             my $numconfig = 0;
14607:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
14608:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
14609:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
14610:                                         $numconfig ++;
14611:                                         if ($provider eq 'examity') {
14612:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
14613:                                         } else {
14614:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
14615:                                         }
14616:                                     }
14617:                                     $resulttext =~ s/,$//;
14618:                                 }
14619:                             }
14620:                             if (!$numconfig) {
14621:                                 $resulttext .= '&nbsp;'.&mt('None');
14622:                             }
14623:                             $resulttext .= '</li>';
14624:                         }
14625:                     }
14626:                     if ($showroles) {
14627:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
14628:                             my $rolemaps;
14629:                             foreach my $role (@courseroles) {
14630:                                 if ($confhash{$provider}{'roles'}{$role}) {
14631:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
14632:                                                  $confhash{$provider}{'roles'}{$role}.',';
14633:                                 }
14634:                             }
14635:                             if ($rolemaps) {
14636:                                 $rolemaps =~ s/,$//;
14637:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14638:                             }
14639:                         }
14640:                     }
14641:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
14642:                         my $customlist;
14643:                         if (keys(%{$confhash{$provider}{'custom'}})) {
14644:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
14645:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
14646:                             }
14647:                             $customlist =~ s/,$//;
14648:                         }
14649:                         if ($customlist) {
14650:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
14651:                         }
14652:                     } 
14653:                     $resulttext .= '</ul></li>';
14654:                 }
14655:             }
14656:             $resulttext .= '</ul>';
14657:         } else {
14658:             $resulttext = &mt('No changes made.');
14659:         }
14660:     } else {
14661:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14662:     }
14663:     if ($errors) {
14664:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14665:                        $errors.'</ul>';
14666:     }
14667:     return $resulttext;
14668: }
14669: 
14670: sub process_proctoring_image {
14671:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
14672:     my $filename = $env{'form.'.$caller.'.filename'};
14673:     my ($error,$url);
14674:     my ($width,$height) = (21,21);
14675:     if ($configuserok eq 'ok') {
14676:         if ($switchserver) {
14677:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
14678:                          $switchserver);
14679:         } elsif ($author_ok eq 'ok') {
14680:             my ($result,$imageurl,$madethumb) =
14681:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14682:                              "proctoring/$provider/icon",$width,$height);
14683:             if ($result eq 'ok') {
14684:                 if ($madethumb) {
14685:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
14686:                     my $imagethumb = "$path/tn-".$imagefile;
14687:                     $url = $imagethumb;
14688:                 } else {
14689:                     $url = $imageurl;
14690:                 }
14691:             } else {
14692:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14693:             }
14694:         } else {
14695:             $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);
14696:         }
14697:     } else {
14698:         $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);
14699:     }
14700:     return ($url,$error);
14701: }
14702: 
14703: sub modify_lti {
14704:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14705:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14706:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14707:     my (%posslti,%posslticrs,%posscrstype);
14708:     my @courseroles = ('cc','in','ta','ep','st');
14709:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
14710:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
14711:     my @coursetypes = ('official','unofficial','community','textbook','placement');
14712:     my %coursetypetitles = &Apache::lonlocal::texthash (
14713:                                official   => 'Official',
14714:                                unofficial => 'Unofficial',
14715:                                community  => 'Community',
14716:                                textbook   => 'Textbook',
14717:                                placement  => 'Placement Test',
14718:     );
14719:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14720:     my %lt = &lti_names();
14721:     map { $posslti{$_} = 1; } @ltiroles;
14722:     map { $posslticrs{$_} = 1; } @lticourseroles;
14723:     map { $posscrstype{$_} = 1; } @coursetypes;
14724: 
14725:     my %menutitles = &ltimenu_titles();
14726: 
14727:     my (@items,%deletions,%itemids);
14728:     if ($env{'form.lti_add'}) {
14729:         my $consumer = $env{'form.lti_consumer_add'};
14730:         $consumer =~ s/(`)/'/g;
14731:         ($newid,my $error) = &get_lti_id($dom,$consumer);
14732:         if ($newid) {
14733:             $itemids{'add'} = $newid;
14734:             push(@items,'add');
14735:             $changes{$newid} = 1;
14736:         } else {
14737:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
14738:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14739:         }
14740:     }
14741:     if (ref($domconfig{$action}) eq 'HASH') {
14742:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
14743:         if (@todelete) {
14744:             map { $deletions{$_} = 1; } @todelete;
14745:         }
14746:         my $maxnum = $env{'form.lti_maxnum'};
14747:         for (my $i=0; $i<=$maxnum; $i++) {
14748:             my $itemid = $env{'form.lti_id_'.$i};
14749:             $itemid =~ s/\D+//g;
14750:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14751:                 if ($deletions{$itemid}) {
14752:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
14753:                 } else {
14754:                    push(@items,$i);
14755:                    $itemids{$i} = $itemid;
14756:                 }
14757:             }
14758:         }
14759:     }
14760:     foreach my $idx (@items) {
14761:         my $itemid = $itemids{$idx};
14762:         next unless ($itemid);
14763:         my $position = $env{'form.lti_pos_'.$idx};
14764:         $position =~ s/\D+//g;
14765:         if ($position ne '') {
14766:             $allpos[$position] = $itemid;
14767:         }
14768:         foreach my $item ('consumer','key','secret','lifetime','requser') {
14769:             my $formitem = 'form.lti_'.$item.'_'.$idx;
14770:             $env{$formitem} =~ s/(`)/'/g;
14771:             if ($item eq 'lifetime') {
14772:                 $env{$formitem} =~ s/[^\d.]//g;
14773:             }
14774:             if ($env{$formitem} ne '') {
14775:                 if (($item eq 'key') || ($item eq 'secret')) {
14776:                     $encconfig{$itemid}{$item} = $env{$formitem};
14777:                 } else {
14778:                     $confhash{$itemid}{$item} = $env{$formitem};
14779:                     unless (($idx eq 'add') || ($changes{$itemid})) {
14780:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14781:                             $changes{$itemid} = 1;
14782:                         }
14783:                     }
14784:                 }
14785:             }
14786:         }
14787:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
14788:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
14789:         }
14790:         if ($confhash{$itemid}{'requser'}) {
14791:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
14792:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid'; 
14793:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
14794:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
14795:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
14796:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
14797:                 $mapuser =~ s/(`)/'/g;
14798:                 $mapuser =~ s/^\s+|\s+$//g; 
14799:                 $confhash{$itemid}{'mapuser'} = $mapuser; 
14800:             }
14801:             foreach my $ltirole (@lticourseroles) {
14802:                 my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
14803:                 if (grep(/^\Q$possrole\E$/,@courseroles)) {
14804:                     $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
14805:                 }
14806:             }
14807:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
14808:             my @makeuser;
14809:             foreach my $ltirole (sort(@possmakeuser)) {
14810:                 if ($posslti{$ltirole}) {
14811:                     push(@makeuser,$ltirole);
14812:                 }
14813:             }
14814:             $confhash{$itemid}{'makeuser'} = \@makeuser;
14815:             if (@makeuser) {
14816:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
14817:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
14818:                     $confhash{$itemid}{'lcauth'} = $lcauth;
14819:                     if ($lcauth ne 'internal') {
14820:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
14821:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
14822:                         $lcauthparm =~ s/`//g;
14823:                         if ($lcauthparm ne '') {
14824:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
14825:                         }
14826:                     }
14827:                 } else {
14828:                     $confhash{$itemid}{'lcauth'} = 'lti';
14829:                 }
14830:             }
14831:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
14832:             if (@possinstdata) {
14833:                 foreach my $field (@possinstdata) {
14834:                     if (exists($fieldtitles{$field})) {
14835:                         push(@{$confhash{$itemid}{'instdata'}});
14836:                     }
14837:                 }
14838:             }
14839:             if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
14840:                 ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
14841:                 $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
14842:             } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
14843:                 my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
14844:                 $mapcrs =~ s/(`)/'/g;
14845:                 $mapcrs =~ s/^\s+|\s+$//g;
14846:                 $confhash{$itemid}{'mapcrs'} = $mapcrs;
14847:             }
14848:             my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
14849:             my @crstypes;
14850:             foreach my $type (sort(@posstypes)) {
14851:                 if ($posscrstype{$type}) {
14852:                     push(@crstypes,$type);
14853:                 }
14854:             }
14855:             $confhash{$itemid}{'mapcrstype'} = \@crstypes;
14856:             if ($env{'form.lti_makecrs_'.$idx}) {
14857:                 $confhash{$itemid}{'makecrs'} = 1;
14858:             }
14859:             my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
14860:             my @selfenroll;
14861:             foreach my $type (sort(@possenroll)) {
14862:                 if ($posslticrs{$type}) {
14863:                     push(@selfenroll,$type);
14864:                 }
14865:             }
14866:             $confhash{$itemid}{'selfenroll'} = \@selfenroll;
14867:             if ($env{'form.lti_crssec_'.$idx}) {
14868:                 if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
14869:                     $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
14870:                 } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
14871:                     my $section = $env{'form.lti_customsection_'.$idx};
14872:                     $section =~ s/(`)/'/g;
14873:                     $section =~ s/^\s+|\s+$//g;
14874:                     if ($section ne '') {
14875:                         $confhash{$itemid}{'section'} = $section;
14876:                     }
14877:                 }
14878:             }
14879:             if ($env{'form.lti_callback_'.$idx}) {
14880:                 if ($env{'form.lti_callbackparam_'.$idx}) {
14881:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
14882:                     $callback =~ s/^\s+|\s+$//g;
14883:                     $confhash{$itemid}{'callback'} = $callback;
14884:                 }
14885:             }
14886:             foreach my $field ('passback','roster','topmenu','inlinemenu') {
14887:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
14888:                     $confhash{$itemid}{$field} = 1;
14889:                 }
14890:             }
14891:             if ($env{'form.lti_passback_'.$idx}) {
14892:                 if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
14893:                     $confhash{$itemid}{'passbackformat'} = '1.0';
14894:                 } else {
14895:                     $confhash{$itemid}{'passbackformat'} = '1.1';
14896:                 }
14897:             }
14898:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
14899:                 $confhash{$itemid}{lcmenu} = [];
14900:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
14901:                 foreach my $field (@possmenu) {
14902:                     if (exists($menutitles{$field})) {
14903:                         if ($field eq 'grades') {
14904:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
14905:                         }
14906:                         push(@{$confhash{$itemid}{lcmenu}},$field);
14907:                     }
14908:                 }
14909:             }
14910:             unless (($idx eq 'add') || ($changes{$itemid})) {
14911:                 foreach my $field ('mapuser','mapcrs','makecrs','section','passback','roster','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
14912:                     if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
14913:                         $changes{$itemid} = 1;
14914:                     }
14915:                 }
14916:                 unless ($changes{$itemid}) {
14917:                     if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
14918:                         if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
14919:                             $changes{$itemid} = 1;
14920:                         }
14921:                     }
14922:                 }
14923:                 foreach my $field ('makeuser','mapcrstype','selfenroll','instdata','lcmenu') {
14924:                     unless ($changes{$itemid}) {
14925:                         if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
14926:                             if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14927:                                 my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
14928:                                                                                $confhash{$itemid}{$field});
14929:                                 if (@diffs) {
14930:                                     $changes{$itemid} = 1;
14931:                                 }
14932:                             } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
14933:                                 $changes{$itemid} = 1;
14934:                             }
14935:                         } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14936:                             if (@{$confhash{$itemid}{$field}} > 0) {
14937:                                 $changes{$itemid} = 1;
14938:                             }
14939:                         }
14940:                     }
14941:                 }
14942:                 unless ($changes{$itemid}) {
14943:                     if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
14944:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14945:                             foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
14946:                                 if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
14947:                                     $confhash{$itemid}{'maproles'}{$ltirole}) {
14948:                                     $changes{$itemid} = 1;
14949:                                     last;
14950:                                 }
14951:                             }
14952:                             unless ($changes{$itemid}) {
14953:                                 foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
14954:                                     if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
14955:                                         $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
14956:                                         $changes{$itemid} = 1;
14957:                                         last;
14958:                                     }
14959:                                 }
14960:                             }
14961:                         } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
14962:                             $changes{$itemid} = 1;
14963:                         }
14964:                     } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14965:                         unless ($changes{$itemid}) {
14966:                             if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
14967:                                 $changes{$itemid} = 1;
14968:                             }
14969:                         }
14970:                     }
14971:                 }
14972:             }
14973:         }
14974:     }
14975:     if (@allpos > 0) {
14976:         my $idx = 0;
14977:         foreach my $itemid (@allpos) {
14978:             if ($itemid ne '') {
14979:                 $confhash{$itemid}{'order'} = $idx;
14980:                 if (ref($domconfig{$action}) eq 'HASH') {
14981:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14982:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
14983:                             $changes{$itemid} = 1;
14984:                         }
14985:                     }
14986:                 }
14987:                 $idx ++;
14988:             }
14989:         }
14990:     }
14991:     my %ltihash = (
14992:                           $action => { %confhash }
14993:                        );
14994:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,
14995:                                              $dom);
14996:     if ($putresult eq 'ok') {
14997:         my %ltienchash = (
14998:                              $action => { %encconfig }
14999:                          );
15000:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
15001:         if (keys(%changes) > 0) {
15002:             my $cachetime = 24*60*60;
15003:             my %ltiall = %confhash;
15004:             foreach my $id (keys(%ltiall)) {
15005:                 if (ref($encconfig{$id}) eq 'HASH') {
15006:                     foreach my $item ('key','secret') {
15007:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
15008:                     }
15009:                 }
15010:             }
15011:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
15012:             if (ref($lastactref) eq 'HASH') {
15013:                 $lastactref->{'lti'} = 1;
15014:             }
15015:             $resulttext = &mt('Changes made:').'<ul>';
15016:             my %bynum;
15017:             foreach my $itemid (sort(keys(%changes))) {
15018:                 my $position = $confhash{$itemid}{'order'};
15019:                 $bynum{$position} = $itemid;
15020:             }
15021:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15022:                 my $itemid = $bynum{$pos};
15023:                 if (ref($confhash{$itemid}) ne 'HASH') {
15024:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
15025:                 } else {
15026:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b></li><ul>';
15027:                     my $position = $pos + 1;
15028:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15029:                     foreach my $item ('version','lifetime') {
15030:                         if ($confhash{$itemid}{$item} ne '') {
15031:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15032:                         }
15033:                     }
15034:                     if ($encconfig{$itemid}{'key'} ne '') {
15035:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
15036:                     }
15037:                     if ($encconfig{$itemid}{'secret'} ne '') {
15038:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15039:                         my $num = length($encconfig{$itemid}{'secret'});
15040:                         $resulttext .= ('*'x$num).'</li>';
15041:                     }
15042:                     if ($confhash{$itemid}{'requser'}) {
15043:                         if ($confhash{$itemid}{'mapuser'}) {
15044:                             my $shownmapuser;
15045:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
15046:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
15047:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
15048:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
15049:                             } else {
15050:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
15051:                             }
15052:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
15053:                         }
15054:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
15055:                             my $rolemaps;
15056:                             foreach my $role (@ltiroles) {
15057:                                 if ($confhash{$itemid}{'maproles'}{$role}) {
15058:                                     $rolemaps .= ('&nbsp;'x2).$role.'='.
15059:                                                  &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
15060:                                                                             'Course').',';
15061:                                 }
15062:                             }
15063:                             if ($rolemaps) {
15064:                                 $rolemaps =~ s/,$//;
15065:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15066:                             }
15067:                         }
15068:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
15069:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
15070:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
15071:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
15072:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
15073:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
15074:                                 } else {
15075:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
15076:                                                        $confhash{$itemid}{'lcauth'});
15077:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
15078:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
15079:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
15080:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
15081:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
15082:                                         }
15083:                                     } else {
15084:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
15085:                                     }
15086:                                 }
15087:                                 $resulttext .= '</li>';
15088:                             } else {
15089:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
15090:                             }
15091:                         }
15092:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
15093:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
15094:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
15095:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
15096:                             } else {
15097:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
15098:                             }
15099:                         }
15100:                         if ($confhash{$itemid}{'mapcrs'}) {
15101:                             $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
15102:                         }
15103:                         if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
15104:                             if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
15105:                                 $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
15106:                                                join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
15107:                                                '</li>';
15108:                             } else {
15109:                                 $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
15110:                             }
15111:                         }
15112:                         if ($confhash{$itemid}{'makecrs'}) {
15113:                             $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
15114:                         } else {
15115:                             $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
15116:                         }
15117:                         if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
15118:                             if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
15119:                                 $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
15120:                                                           join(', ',@{$confhash{$itemid}{'selfenroll'}})).
15121:                                                '</li>';
15122:                             } else {
15123:                                 $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
15124:                             }
15125:                         }
15126:                         if ($confhash{$itemid}{'section'}) {
15127:                             if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
15128:                                 $resulttext .= '<li>'.&mt('User section from standard field:').
15129:                                                      ' (course_section_sourcedid)'.'</li>';  
15130:                             } else {
15131:                                 $resulttext .= '<li>'.&mt('User section from:').' '.
15132:                                                       $confhash{$itemid}{'section'}.'</li>';
15133:                             }
15134:                         } else {
15135:                             $resulttext .= '<li>'.&mt('No section assignment').'</li>';
15136:                         }
15137:                         if ($confhash{$itemid}{'callback'}) {
15138:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
15139:                         } else {
15140:                             $resulttext .= '<li>'.&mt('No callback to logout LON-CAPA session when user logs out of Comsumer');
15141:                         }
15142:                         foreach my $item ('passback','roster','topmenu','inlinemenu') {
15143:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
15144:                             if ($confhash{$itemid}{$item}) {
15145:                                 $resulttext .= &mt('Yes');
15146:                                 if ($item eq 'passback') {
15147:                                     if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
15148:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
15149:                                     } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
15150:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
15151:                                     }
15152:                                 }
15153:                             } else {
15154:                                 $resulttext .= &mt('No');
15155:                             }
15156:                             $resulttext .= '</li>';
15157:                         }
15158:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
15159:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
15160:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
15161:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
15162:                             } else {
15163:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
15164:                             }
15165:                         }
15166:                     }
15167:                     $resulttext .= '</ul></li>';
15168:                 }
15169:             }
15170:             $resulttext .= '</ul>';
15171:         } else {
15172:             $resulttext = &mt('No changes made.');
15173:         }
15174:     } else {
15175:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15176:     }
15177:     if ($errors) {
15178:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15179:                        $errors.'</ul>';
15180:     }
15181:     return $resulttext;
15182: }
15183: 
15184: sub get_lti_id {
15185:     my ($domain,$consumer) = @_;
15186:     # get lock on lti db
15187:     my $lockhash = {
15188:                       lock => $env{'user.name'}.
15189:                               ':'.$env{'user.domain'},
15190:                    };
15191:     my $tries = 0;
15192:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
15193:     my ($id,$error);
15194: 
15195:     while (($gotlock ne 'ok') && ($tries<10)) {
15196:         $tries ++;
15197:         sleep (0.1);
15198:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
15199:     }
15200:     if ($gotlock eq 'ok') {
15201:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
15202:         if ($currids{'lock'}) {
15203:             delete($currids{'lock'});
15204:             if (keys(%currids)) {
15205:                 my @curr = sort { $a <=> $b } keys(%currids);
15206:                 if ($curr[-1] =~ /^\d+$/) {
15207:                     $id = 1 + $curr[-1];
15208:                 }
15209:             } else {
15210:                 $id = 1;
15211:             }
15212:             if ($id) {
15213:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
15214:                     $error = 'nostore';
15215:                 }
15216:             } else {
15217:                 $error = 'nonumber';
15218:             }
15219:         }
15220:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
15221:     } else {
15222:         $error = 'nolock';
15223:     }
15224:     return ($id,$error);
15225: }
15226: 
15227: sub modify_autoenroll {
15228:     my ($dom,$lastactref,%domconfig) = @_;
15229:     my ($resulttext,%changes);
15230:     my %currautoenroll;
15231:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
15232:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
15233:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
15234:         }
15235:     }
15236:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
15237:     my %title = ( run => 'Auto-enrollment active',
15238:                   sender => 'Sender for notification messages',
15239:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
15240:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
15241:     my @offon = ('off','on');
15242:     my $sender_uname = $env{'form.sender_uname'};
15243:     my $sender_domain = $env{'form.sender_domain'};
15244:     if ($sender_domain eq '') {
15245:         $sender_uname = '';
15246:     } elsif ($sender_uname eq '') {
15247:         $sender_domain = '';
15248:     }
15249:     my $coowners = $env{'form.autoassign_coowners'};
15250:     my $failsafe = $env{'form.autoenroll_failsafe'};
15251:     $failsafe =~ s{^\s+|\s+$}{}g;
15252:     if ($failsafe =~ /\D/) {
15253:         undef($failsafe);
15254:     }
15255:     my %autoenrollhash =  (
15256:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
15257:                                        'sender_uname' => $sender_uname,
15258:                                        'sender_domain' => $sender_domain,
15259:                                        'co-owners' => $coowners,
15260:                                        'autofailsafe' => $failsafe,
15261:                                 }
15262:                      );
15263:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
15264:                                              $dom);
15265:     if ($putresult eq 'ok') {
15266:         if (exists($currautoenroll{'run'})) {
15267:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
15268:                  $changes{'run'} = 1;
15269:              }
15270:         } elsif ($autorun) {
15271:             if ($env{'form.autoenroll_run'} ne '1') {
15272:                  $changes{'run'} = 1;
15273:             }
15274:         }
15275:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
15276:             $changes{'sender'} = 1;
15277:         }
15278:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
15279:             $changes{'sender'} = 1;
15280:         }
15281:         if ($currautoenroll{'co-owners'} ne '') {
15282:             if ($currautoenroll{'co-owners'} ne $coowners) {
15283:                 $changes{'coowners'} = 1;
15284:             }
15285:         } elsif ($coowners) {
15286:             $changes{'coowners'} = 1;
15287:         }
15288:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
15289:             $changes{'autofailsafe'} = 1;
15290:         }
15291:         if (keys(%changes) > 0) {
15292:             $resulttext = &mt('Changes made:').'<ul>';
15293:             if ($changes{'run'}) {
15294:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
15295:             }
15296:             if ($changes{'sender'}) {
15297:                 if ($sender_uname eq '' || $sender_domain eq '') {
15298:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
15299:                 } else {
15300:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
15301:                 }
15302:             }
15303:             if ($changes{'coowners'}) {
15304:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
15305:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
15306:                 if (ref($lastactref) eq 'HASH') {
15307:                     $lastactref->{'domainconfig'} = 1;
15308:                 }
15309:             }
15310:             if ($changes{'autofailsafe'}) {
15311:                 if ($failsafe ne '') {
15312:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
15313:                 } else {
15314:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
15315:                 }
15316:                 &Apache::lonnet::get_domain_defaults($dom,1);
15317:                 if (ref($lastactref) eq 'HASH') {
15318:                     $lastactref->{'domdefaults'} = 1;
15319:                 }
15320:             }
15321:             $resulttext .= '</ul>';
15322:         } else {
15323:             $resulttext = &mt('No changes made to auto-enrollment settings');
15324:         }
15325:     } else {
15326:         $resulttext = '<span class="LC_error">'.
15327: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
15328:     }
15329:     return $resulttext;
15330: }
15331: 
15332: sub modify_autoupdate {
15333:     my ($dom,%domconfig) = @_;
15334:     my ($resulttext,%currautoupdate,%fields,%changes);
15335:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
15336:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
15337:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
15338:         }
15339:     }
15340:     my @offon = ('off','on');
15341:     my %title = &Apache::lonlocal::texthash (
15342:                     run        => 'Auto-update:',
15343:                     classlists => 'Updates to user information in classlists?',
15344:                     unexpired  => 'Skip updates for users without active or future roles?',
15345:                     lastactive => 'Skip updates for inactive users?',
15346:                 );
15347:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15348:     my %fieldtitles = &Apache::lonlocal::texthash (
15349:                         id => 'Student/Employee ID',
15350:                         permanentemail => 'E-mail address',
15351:                         lastname => 'Last Name',
15352:                         firstname => 'First Name',
15353:                         middlename => 'Middle Name',
15354:                         generation => 'Generation',
15355:                       );
15356:     $othertitle = &mt('All users');
15357:     if (keys(%{$usertypes}) >  0) {
15358:         $othertitle = &mt('Other users');
15359:     }
15360:     foreach my $key (keys(%env)) {
15361:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
15362:             my ($usertype,$item) = ($1,$2);
15363:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
15364:                 if ($usertype eq 'default') {   
15365:                     push(@{$fields{$1}},$2);
15366:                 } elsif (ref($types) eq 'ARRAY') {
15367:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
15368:                         push(@{$fields{$1}},$2);
15369:                     }
15370:                 }
15371:             }
15372:         }
15373:     }
15374:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
15375:     @lockablenames = sort(@lockablenames);
15376:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
15377:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
15378:         if (@changed) {
15379:             $changes{'lockablenames'} = 1;
15380:         }
15381:     } else {
15382:         if (@lockablenames) {
15383:             $changes{'lockablenames'} = 1;
15384:         }
15385:     }
15386:     my %updatehash = (
15387:                       autoupdate => { run => $env{'form.autoupdate_run'},
15388:                                       classlists => $env{'form.classlists'},
15389:                                       unexpired  => $env{'form.unexpired'},
15390:                                       fields => {%fields},
15391:                                       lockablenames => \@lockablenames,
15392:                                     }
15393:                      );
15394:     my $lastactivedays;
15395:     if ($env{'form.lastactive'}) {
15396:         $lastactivedays = $env{'form.lastactivedays'};
15397:         $lastactivedays =~ s/^\s+|\s+$//g;
15398:         unless ($lastactivedays =~ /^\d+$/) {
15399:             undef($lastactivedays);
15400:             $env{'form.lastactive'} = 0;
15401:         }
15402:     }
15403:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
15404:     foreach my $key (keys(%currautoupdate)) {
15405:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
15406:             if (exists($updatehash{autoupdate}{$key})) {
15407:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
15408:                     $changes{$key} = 1;
15409:                 }
15410:             }
15411:         } elsif ($key eq 'fields') {
15412:             if (ref($currautoupdate{$key}) eq 'HASH') {
15413:                 foreach my $item (@{$types},'default') {
15414:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
15415:                         my $change = 0;
15416:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
15417:                             if (!exists($fields{$item})) {
15418:                                 $change = 1;
15419:                                 last;
15420:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
15421:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
15422:                                     $change = 1;
15423:                                     last;
15424:                                 }
15425:                             }
15426:                         }
15427:                         if ($change) {
15428:                             push(@{$changes{$key}},$item);
15429:                         }
15430:                     } 
15431:                 }
15432:             }
15433:         } elsif ($key eq 'lockablenames') {
15434:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
15435:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
15436:                 if (@changed) {
15437:                     $changes{'lockablenames'} = 1;
15438:                 }
15439:             } else {
15440:                 if (@lockablenames) {
15441:                     $changes{'lockablenames'} = 1;
15442:                 }
15443:             }
15444:         }
15445:     }
15446:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
15447:         if (@lockablenames) {
15448:             $changes{'lockablenames'} = 1;
15449:         }
15450:     }
15451:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
15452:         if ($updatehash{'autoupdate'}{'unexpired'}) {
15453:             $changes{'unexpired'} = 1;
15454:         }
15455:     }
15456:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
15457:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
15458:             $changes{'lastactive'} = 1;
15459:         }
15460:     }
15461:     foreach my $item (@{$types},'default') {
15462:         if (defined($fields{$item})) {
15463:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
15464:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
15465:                     my $change = 0;
15466:                     if (ref($fields{$item}) eq 'ARRAY') {
15467:                         foreach my $type (@{$fields{$item}}) {
15468:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
15469:                                 $change = 1;
15470:                                 last;
15471:                             }
15472:                         }
15473:                     }
15474:                     if ($change) {
15475:                         push(@{$changes{'fields'}},$item);
15476:                     }
15477:                 } else {
15478:                     push(@{$changes{'fields'}},$item);
15479:                 }
15480:             } else {
15481:                 push(@{$changes{'fields'}},$item);
15482:             }
15483:         }
15484:     }
15485:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
15486:                                              $dom);
15487:     if ($putresult eq 'ok') {
15488:         if (keys(%changes) > 0) {
15489:             $resulttext = &mt('Changes made:').'<ul>';
15490:             foreach my $key (sort(keys(%changes))) {
15491:                 if ($key eq 'lockablenames') {
15492:                     $resulttext .= '<li>';
15493:                     if (@lockablenames) {
15494:                         $usertypes->{'default'} = $othertitle;
15495:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
15496:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
15497:                     } else {
15498:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
15499:                     }
15500:                     $resulttext .= '</li>';
15501:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
15502:                     foreach my $item (@{$changes{$key}}) {
15503:                         my @newvalues;
15504:                         foreach my $type (@{$fields{$item}}) {
15505:                             push(@newvalues,$fieldtitles{$type});
15506:                         }
15507:                         my $newvaluestr;
15508:                         if (@newvalues > 0) {
15509:                             $newvaluestr = join(', ',@newvalues);
15510:                         } else {
15511:                             $newvaluestr = &mt('none');
15512:                         }
15513:                         if ($item eq 'default') {
15514:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
15515:                         } else {
15516:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
15517:                         }
15518:                     }
15519:                 } else {
15520:                     my $newvalue;
15521:                     if ($key eq 'run') {
15522:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
15523:                     } elsif ($key eq 'lastactive') {
15524:                         $newvalue = $offon[$env{'form.lastactive'}];
15525:                         unless ($lastactivedays eq '') {
15526:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
15527:                         }
15528:                     } else {
15529:                         $newvalue = $offon[$env{'form.'.$key}];
15530:                     }
15531:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
15532:                 }
15533:             }
15534:             $resulttext .= '</ul>';
15535:         } else {
15536:             $resulttext = &mt('No changes made to autoupdates');
15537:         }
15538:     } else {
15539:         $resulttext = '<span class="LC_error">'.
15540: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
15541:     }
15542:     return $resulttext;
15543: }
15544: 
15545: sub modify_autocreate {
15546:     my ($dom,%domconfig) = @_;
15547:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
15548:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
15549:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
15550:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
15551:         }
15552:     }
15553:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
15554:                  req => 'Auto-creation of validated requests for official courses',
15555:                  xmldc => 'Identity of course creator of courses from XML files',
15556:                );
15557:     my @types = ('xml','req');
15558:     foreach my $item (@types) {
15559:         $newvals{$item} = $env{'form.autocreate_'.$item};
15560:         $newvals{$item} =~ s/\D//g;
15561:         $newvals{$item} = 0 if ($newvals{$item} eq '');
15562:     }
15563:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
15564:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
15565:     unless (exists($domcoords{$newvals{'xmldc'}})) {
15566:         $newvals{'xmldc'} = '';
15567:     } 
15568:     %autocreatehash =  (
15569:                         autocreate => { xml => $newvals{'xml'},
15570:                                         req => $newvals{'req'},
15571:                                       }
15572:                        );
15573:     if ($newvals{'xmldc'} ne '') {
15574:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
15575:     }
15576:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
15577:                                              $dom);
15578:     if ($putresult eq 'ok') {
15579:         my @items = @types;
15580:         if ($newvals{'xml'}) {
15581:             push(@items,'xmldc');
15582:         }
15583:         foreach my $item (@items) {
15584:             if (exists($currautocreate{$item})) {
15585:                 if ($currautocreate{$item} ne $newvals{$item}) {
15586:                     $changes{$item} = 1;
15587:                 }
15588:             } elsif ($newvals{$item}) {
15589:                 $changes{$item} = 1;
15590:             }
15591:         }
15592:         if (keys(%changes) > 0) {
15593:             my @offon = ('off','on'); 
15594:             $resulttext = &mt('Changes made:').'<ul>';
15595:             foreach my $item (@types) {
15596:                 if ($changes{$item}) {
15597:                     my $newtxt = $offon[$newvals{$item}];
15598:                     $resulttext .= '<li>'.
15599:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
15600:                                        '<b>','</b>').
15601:                                    '</li>';
15602:                 }
15603:             }
15604:             if ($changes{'xmldc'}) {
15605:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
15606:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
15607:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
15608:             }
15609:             $resulttext .= '</ul>';
15610:         } else {
15611:             $resulttext = &mt('No changes made to auto-creation settings');
15612:         }
15613:     } else {
15614:         $resulttext = '<span class="LC_error">'.
15615:             &mt('An error occurred: [_1]',$putresult).'</span>';
15616:     }
15617:     return $resulttext;
15618: }
15619: 
15620: sub modify_directorysrch {
15621:     my ($dom,$lastactref,%domconfig) = @_;
15622:     my ($resulttext,%changes);
15623:     my %currdirsrch;
15624:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
15625:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
15626:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
15627:         }
15628:     }
15629:     my %title = ( available => 'Institutional directory search available',
15630:                   localonly => 'Other domains can search institution',
15631:                   lcavailable => 'LON-CAPA directory search available',
15632:                   lclocalonly => 'Other domains can search LON-CAPA domain',
15633:                   searchby => 'Search types',
15634:                   searchtypes => 'Search latitude');
15635:     my @offon = ('off','on');
15636:     my @otherdoms = ('Yes','No');
15637: 
15638:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
15639:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
15640:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
15641: 
15642:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15643:     if (keys(%{$usertypes}) == 0) {
15644:         @cansearch = ('default');
15645:     } else {
15646:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
15647:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
15648:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
15649:                     push(@{$changes{'cansearch'}},$type);
15650:                 }
15651:             }
15652:             foreach my $type (@cansearch) {
15653:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
15654:                     push(@{$changes{'cansearch'}},$type);
15655:                 }
15656:             }
15657:         } else {
15658:             push(@{$changes{'cansearch'}},@cansearch);
15659:         }
15660:     }
15661: 
15662:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
15663:         foreach my $by (@{$currdirsrch{'searchby'}}) {
15664:             if (!grep(/^\Q$by\E$/,@searchby)) {
15665:                 push(@{$changes{'searchby'}},$by);
15666:             }
15667:         }
15668:         foreach my $by (@searchby) {
15669:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
15670:                 push(@{$changes{'searchby'}},$by);
15671:             }
15672:         }
15673:     } else {
15674:         push(@{$changes{'searchby'}},@searchby);
15675:     }
15676: 
15677:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
15678:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
15679:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
15680:                 push(@{$changes{'searchtypes'}},$type);
15681:             }
15682:         }
15683:         foreach my $type (@searchtypes) {
15684:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
15685:                 push(@{$changes{'searchtypes'}},$type);
15686:             }
15687:         }
15688:     } else {
15689:         if (exists($currdirsrch{'searchtypes'})) {
15690:             foreach my $type (@searchtypes) {  
15691:                 if ($type ne $currdirsrch{'searchtypes'}) { 
15692:                     push(@{$changes{'searchtypes'}},$type);
15693:                 }
15694:             }
15695:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
15696:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
15697:             }   
15698:         } else {
15699:             push(@{$changes{'searchtypes'}},@searchtypes); 
15700:         }
15701:     }
15702: 
15703:     my %dirsrch_hash =  (
15704:             directorysrch => { available => $env{'form.dirsrch_available'},
15705:                                cansearch => \@cansearch,
15706:                                localonly => $env{'form.dirsrch_instlocalonly'},
15707:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
15708:                                lcavailable => $env{'form.dirsrch_domavailable'},
15709:                                searchby => \@searchby,
15710:                                searchtypes => \@searchtypes,
15711:                              }
15712:             );
15713:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
15714:                                              $dom);
15715:     if ($putresult eq 'ok') {
15716:         if (exists($currdirsrch{'available'})) {
15717:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
15718:                  $changes{'available'} = 1;
15719:              }
15720:         } else {
15721:             if ($env{'form.dirsrch_available'} eq '1') {
15722:                 $changes{'available'} = 1;
15723:             }
15724:         }
15725:         if (exists($currdirsrch{'lcavailable'})) {
15726:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
15727:                 $changes{'lcavailable'} = 1;
15728:             }
15729:         } else {
15730:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
15731:                 $changes{'lcavailable'} = 1;
15732:             }
15733:         }
15734:         if (exists($currdirsrch{'localonly'})) {
15735:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
15736:                 $changes{'localonly'} = 1;
15737:             }
15738:         } else {
15739:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
15740:                 $changes{'localonly'} = 1;
15741:             }
15742:         }
15743:         if (exists($currdirsrch{'lclocalonly'})) {
15744:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
15745:                 $changes{'lclocalonly'} = 1;
15746:             }
15747:         } else {
15748:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
15749:                 $changes{'lclocalonly'} = 1;
15750:             }
15751:         }
15752:         if (keys(%changes) > 0) {
15753:             $resulttext = &mt('Changes made:').'<ul>';
15754:             if ($changes{'available'}) {
15755:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
15756:             }
15757:             if ($changes{'lcavailable'}) {
15758:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
15759:             }
15760:             if ($changes{'localonly'}) {
15761:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
15762:             }
15763:             if ($changes{'lclocalonly'}) {
15764:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
15765:             }
15766:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
15767:                 my $chgtext;
15768:                 if (ref($usertypes) eq 'HASH') {
15769:                     if (keys(%{$usertypes}) > 0) {
15770:                         foreach my $type (@{$types}) {
15771:                             if (grep(/^\Q$type\E$/,@cansearch)) {
15772:                                 $chgtext .= $usertypes->{$type}.'; ';
15773:                             }
15774:                         }
15775:                         if (grep(/^default$/,@cansearch)) {
15776:                             $chgtext .= $othertitle;
15777:                         } else {
15778:                             $chgtext =~ s/\; $//;
15779:                         }
15780:                         $resulttext .=
15781:                             '<li>'.
15782:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
15783:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
15784:                             '</li>';
15785:                     }
15786:                 }
15787:             }
15788:             if (ref($changes{'searchby'}) eq 'ARRAY') {
15789:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
15790:                 my $chgtext;
15791:                 foreach my $type (@{$titleorder}) {
15792:                     if (grep(/^\Q$type\E$/,@searchby)) {
15793:                         if (defined($searchtitles->{$type})) {
15794:                             $chgtext .= $searchtitles->{$type}.'; ';
15795:                         }
15796:                     }
15797:                 }
15798:                 $chgtext =~ s/\; $//;
15799:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
15800:             }
15801:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
15802:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
15803:                 my $chgtext;
15804:                 foreach my $type (@{$srchtypeorder}) {
15805:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
15806:                         if (defined($srchtypes_desc->{$type})) {
15807:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
15808:                         }
15809:                     }
15810:                 }
15811:                 $chgtext =~ s/\; $//;
15812:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
15813:             }
15814:             $resulttext .= '</ul>';
15815:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
15816:             if (ref($lastactref) eq 'HASH') {
15817:                 $lastactref->{'directorysrch'} = 1;
15818:             }
15819:         } else {
15820:             $resulttext = &mt('No changes made to directory search settings');
15821:         }
15822:     } else {
15823:         $resulttext = '<span class="LC_error">'.
15824:                       &mt('An error occurred: [_1]',$putresult).'</span>';
15825:     }
15826:     return $resulttext;
15827: }
15828: 
15829: sub modify_contacts {
15830:     my ($dom,$lastactref,%domconfig) = @_;
15831:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
15832:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15833:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
15834:             $currsetting{$key} = $domconfig{'contacts'}{$key};
15835:         }
15836:     }
15837:     my (%others,%to,%bcc,%includestr,%includeloc);
15838:     my @contacts = ('supportemail','adminemail');
15839:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
15840:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
15841:     my @toggles = ('reporterrors','reportupdates','reportstatus');
15842:     my @lonstatus = ('threshold','sysmail','weights','excluded');
15843:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
15844:     foreach my $type (@mailings) {
15845:         @{$newsetting{$type}} = 
15846:             &Apache::loncommon::get_env_multiple('form.'.$type);
15847:         foreach my $item (@contacts) {
15848:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
15849:                 $contacts_hash{contacts}{$type}{$item} = 1;
15850:             } else {
15851:                 $contacts_hash{contacts}{$type}{$item} = 0;
15852:             }
15853:         }
15854:         $others{$type} = $env{'form.'.$type.'_others'};
15855:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
15856:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15857:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
15858:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
15859:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
15860:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
15861:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
15862:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15863:             }
15864:         }
15865:     }
15866:     foreach my $item (@contacts) {
15867:         $to{$item} = $env{'form.'.$item};
15868:         $contacts_hash{'contacts'}{$item} = $to{$item};
15869:     }
15870:     foreach my $item (@toggles) {
15871:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
15872:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
15873:         }
15874:     }
15875:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
15876:     foreach my $item (@lonstatus) {
15877:         if ($item eq 'excluded') {
15878:             my (%serverhomes,@excluded);
15879:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
15880:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
15881:             if (@possexcluded) {
15882:                 foreach my $id (sort(@possexcluded)) {
15883:                     if ($serverhomes{$id}) {
15884:                         push(@excluded,$id);
15885:                     }
15886:                 }
15887:             }
15888:             if (@excluded) {
15889:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
15890:             }
15891:         } elsif ($item eq 'weights') {
15892:             foreach my $type ('E','W','N','U') {
15893:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
15894:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
15895:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
15896:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
15897:                             $env{'form.error'.$item.'_'.$type};
15898:                     }
15899:                 }
15900:             }
15901:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
15902:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
15903:             if ($env{'form.error'.$item} =~ /^\d+$/) {
15904:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
15905:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
15906:                 }
15907:             }
15908:         }
15909:     }
15910:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
15911:         foreach my $field (@{$fields}) {
15912:             if (ref($possoptions->{$field}) eq 'ARRAY') {
15913:                 my $value = $env{'form.helpform_'.$field};
15914:                 $value =~ s/^\s+|\s+$//g;
15915:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
15916:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
15917:                     if ($field eq 'screenshot') {
15918:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
15919:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
15920:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
15921:                         }
15922:                     }
15923:                 }
15924:             }
15925:         }
15926:     }
15927:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15928:     my (@statuses,%usertypeshash,@overrides);
15929:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
15930:         @statuses = @{$types};
15931:         if (ref($usertypes) eq 'HASH') {
15932:             %usertypeshash = %{$usertypes};
15933:         }
15934:     }
15935:     if (@statuses) {
15936:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
15937:         foreach my $type (@possoverrides) {
15938:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
15939:                 push(@overrides,$type);
15940:             }
15941:         }
15942:         if (@overrides) {
15943:             foreach my $type (@overrides) {
15944:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
15945:                 foreach my $item (@contacts) {
15946:                     if (grep(/^\Q$item\E$/,@standard)) {
15947:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
15948:                         $newsetting{'override_'.$type}{$item} = 1;
15949:                     } else {
15950:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
15951:                         $newsetting{'override_'.$type}{$item} = 0;
15952:                     }
15953:                 }
15954:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
15955:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15956:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
15957:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15958:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
15959:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
15960:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
15961:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15962:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
15963:                 }
15964:             }     
15965:         }
15966:     }
15967:     if (keys(%currsetting) > 0) {
15968:         foreach my $item (@contacts) {
15969:             if ($to{$item} ne $currsetting{$item}) {
15970:                 $changes{$item} = 1;
15971:             }
15972:         }
15973:         foreach my $type (@mailings) {
15974:             foreach my $item (@contacts) {
15975:                 if (ref($currsetting{$type}) eq 'HASH') {
15976:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
15977:                         push(@{$changes{$type}},$item);
15978:                     }
15979:                 } else {
15980:                     push(@{$changes{$type}},@{$newsetting{$type}});
15981:                 }
15982:             }
15983:             if ($others{$type} ne $currsetting{$type}{'others'}) {
15984:                 push(@{$changes{$type}},'others');
15985:             }
15986:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15987:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
15988:                     push(@{$changes{$type}},'bcc'); 
15989:                 }
15990:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
15991:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
15992:                     push(@{$changes{$type}},'include');
15993:                 }
15994:             }
15995:         }
15996:         if (ref($fields) eq 'ARRAY') {
15997:             if (ref($currsetting{'helpform'}) eq 'HASH') {
15998:                 foreach my $field (@{$fields}) {
15999:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
16000:                         push(@{$changes{'helpform'}},$field);
16001:                     }
16002:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
16003:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
16004:                             push(@{$changes{'helpform'}},'maxsize');
16005:                         }
16006:                     }
16007:                 }
16008:             } else {
16009:                 foreach my $field (@{$fields}) {
16010:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
16011:                         push(@{$changes{'helpform'}},$field);
16012:                     }
16013:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
16014:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
16015:                             push(@{$changes{'helpform'}},'maxsize');
16016:                         }
16017:                     }
16018:                 }
16019:             }
16020:         }
16021:         if (@statuses) {
16022:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
16023:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
16024:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
16025:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
16026:                             foreach my $item (@contacts,'bcc','others','include') {
16027:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
16028:                                     push(@{$changes{'overrides'}},$key);
16029:                                     last;
16030:                                 }
16031:                             }
16032:                         } else {
16033:                             push(@{$changes{'overrides'}},$key);
16034:                         }
16035:                     }
16036:                 }
16037:                 foreach my $key (@overrides) {
16038:                     unless (exists($currsetting{'overrides'}{$key})) {
16039:                         push(@{$changes{'overrides'}},$key);
16040:                     }
16041:                 }
16042:             } else {
16043:                 foreach my $key (@overrides) {
16044:                     push(@{$changes{'overrides'}},$key); 
16045:                 }
16046:             }
16047:         }
16048:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
16049:             foreach my $key ('excluded','weights','threshold','sysmail') {
16050:                 if ($key eq 'excluded') {
16051:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
16052:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
16053:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
16054:                             (@{$currsetting{'lonstatus'}{$key}})) {
16055:                             my @diffs =
16056:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
16057:                                                                    $currsetting{'lonstatus'}{$key});
16058:                             if (@diffs) {
16059:                                 push(@{$changes{'lonstatus'}},$key);
16060:                             }
16061:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
16062:                             push(@{$changes{'lonstatus'}},$key);
16063:                         }
16064:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
16065:                              (@{$currsetting{'lonstatus'}{$key}})) {
16066:                         push(@{$changes{'lonstatus'}},$key);
16067:                     }
16068:                 } elsif ($key eq 'weights') {
16069:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
16070:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
16071:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
16072:                             foreach my $type ('E','W','N','U') {
16073:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
16074:                                         $currsetting{'lonstatus'}{$key}{$type}) {
16075:                                     push(@{$changes{'lonstatus'}},$key);
16076:                                     last;
16077:                                 }
16078:                             }
16079:                         } else {
16080:                             foreach my $type ('E','W','N','U') {
16081:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
16082:                                     push(@{$changes{'lonstatus'}},$key);
16083:                                     last;
16084:                                 }
16085:                             }
16086:                         }
16087:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
16088:                         foreach my $type ('E','W','N','U') {
16089:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
16090:                                 push(@{$changes{'lonstatus'}},$key);
16091:                                 last;
16092:                             }
16093:                         }
16094:                     }
16095:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
16096:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16097:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
16098:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
16099:                                 push(@{$changes{'lonstatus'}},$key);
16100:                             }
16101:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
16102:                             push(@{$changes{'lonstatus'}},$key);
16103:                         }
16104:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
16105:                         push(@{$changes{'lonstatus'}},$key);
16106:                     }
16107:                 }
16108:             }
16109:         } else {
16110:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16111:                 foreach my $key ('excluded','weights','threshold','sysmail') {
16112:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
16113:                         push(@{$changes{'lonstatus'}},$key);
16114:                     }
16115:                 }
16116:             }
16117:         }
16118:     } else {
16119:         my %default;
16120:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
16121:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
16122:         $default{'errormail'} = 'adminemail';
16123:         $default{'packagesmail'} = 'adminemail';
16124:         $default{'helpdeskmail'} = 'supportemail';
16125:         $default{'otherdomsmail'} = 'supportemail';
16126:         $default{'lonstatusmail'} = 'adminemail';
16127:         $default{'requestsmail'} = 'adminemail';
16128:         $default{'updatesmail'} = 'adminemail';
16129:         $default{'hostipmail'} = 'adminemail';
16130:         foreach my $item (@contacts) {
16131:            if ($to{$item} ne $default{$item}) {
16132:                $changes{$item} = 1;
16133:            }
16134:         }
16135:         foreach my $type (@mailings) {
16136:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
16137:                 push(@{$changes{$type}},@{$newsetting{$type}});
16138:             }
16139:             if ($others{$type} ne '') {
16140:                 push(@{$changes{$type}},'others');
16141:             }
16142:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16143:                 if ($bcc{$type} ne '') {
16144:                     push(@{$changes{$type}},'bcc');
16145:                 }
16146:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
16147:                     push(@{$changes{$type}},'include');
16148:                 }
16149:             }
16150:         }
16151:         if (ref($fields) eq 'ARRAY') {
16152:             foreach my $field (@{$fields}) {
16153:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
16154:                     push(@{$changes{'helpform'}},$field);
16155:                 }
16156:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
16157:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
16158:                         push(@{$changes{'helpform'}},'maxsize');
16159:                     }
16160:                 }
16161:             }
16162:         }
16163:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
16164:             foreach my $key ('excluded','weights','threshold','sysmail') {
16165:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
16166:                     push(@{$changes{'lonstatus'}},$key);
16167:                 }
16168:             }
16169:         }
16170:     }
16171:     foreach my $item (@toggles) {
16172:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
16173:             $changes{$item} = 1;
16174:         } elsif ((!$env{'form.'.$item}) &&
16175:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
16176:             $changes{$item} = 1;
16177:         }
16178:     }
16179:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
16180:                                              $dom);
16181:     if ($putresult eq 'ok') {
16182:         if (keys(%changes) > 0) {
16183:             &Apache::loncommon::devalidate_domconfig_cache($dom);
16184:             if (ref($lastactref) eq 'HASH') {
16185:                 $lastactref->{'domainconfig'} = 1;
16186:             }
16187:             my ($titles,$short_titles)  = &contact_titles();
16188:             $resulttext = &mt('Changes made:').'<ul>';
16189:             foreach my $item (@contacts) {
16190:                 if ($changes{$item}) {
16191:                     $resulttext .= '<li>'.$titles->{$item}.
16192:                                     &mt(' set to: ').
16193:                                     '<span class="LC_cusr_emph">'.
16194:                                     $to{$item}.'</span></li>';
16195:                 }
16196:             }
16197:             foreach my $type (@mailings) {
16198:                 if (ref($changes{$type}) eq 'ARRAY') {
16199:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16200:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
16201:                     } else {
16202:                         $resulttext .= '<li>'.$titles->{$type}.': ';
16203:                     }
16204:                     my @text;
16205:                     foreach my $item (@{$newsetting{$type}}) {
16206:                         push(@text,$short_titles->{$item});
16207:                     }
16208:                     if ($others{$type} ne '') {
16209:                         push(@text,$others{$type});
16210:                     }
16211:                     if (@text) {
16212:                         $resulttext .= '<span class="LC_cusr_emph">'.
16213:                                        join(', ',@text).'</span>';
16214:                     }
16215:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
16216:                         if ($bcc{$type} ne '') {
16217:                             my $bcctext;
16218:                             if (@text) {
16219:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
16220:                             } else {
16221:                                 $bcctext = '(Bcc)';
16222:                             }
16223:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
16224:                         } elsif (!@text) {
16225:                             $resulttext .= &mt('No one');
16226:                         }   
16227:                         if ($includestr{$type} ne '') {
16228:                             if ($includeloc{$type} eq 'b') {
16229:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
16230:                             } elsif ($includeloc{$type} eq 's') {
16231:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
16232:                             }
16233:                         }
16234:                     } elsif (!@text) {
16235:                         $resulttext .= &mt('No recipients');
16236:                     }
16237:                     $resulttext .= '</li>';
16238:                 }
16239:             }
16240:             if (ref($changes{'overrides'}) eq 'ARRAY') {
16241:                 my @deletions;
16242:                 foreach my $type (@{$changes{'overrides'}}) {
16243:                     if ($usertypeshash{$type}) {
16244:                         if (grep(/^\Q$type\E/,@overrides)) {
16245:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
16246:                                                       $usertypeshash{$type}).'<ul><li>';
16247:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
16248:                                 my @text;
16249:                                 foreach my $item (@contacts) {
16250:                                     if ($newsetting{'override_'.$type}{$item}) { 
16251:                                         push(@text,$short_titles->{$item});
16252:                                     }
16253:                                 }
16254:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
16255:                                     push(@text,$newsetting{'override_'.$type}{'others'});
16256:                                 }
16257:   
16258:                                 if (@text) {
16259:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
16260:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
16261:                                 }
16262:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
16263:                                     my $bcctext;
16264:                                     if (@text) {
16265:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
16266:                                     } else {
16267:                                         $bcctext = '(Bcc)';
16268:                                     }
16269:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
16270:                                 } elsif (!@text) {
16271:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
16272:                                 }
16273:                                 $resulttext .= '</li>';
16274:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
16275:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
16276:                                     if ($loc eq 'b') {
16277:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
16278:                                     } elsif ($loc eq 's') {
16279:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
16280:                                     }
16281:                                 }
16282:                             }
16283:                             $resulttext .= '</li></ul></li>';
16284:                         } else {
16285:                             push(@deletions,$usertypeshash{$type});
16286:                         }
16287:                     }
16288:                 }
16289:                 if (@deletions) {
16290:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
16291:                                               join(', ',@deletions)).'</li>';
16292:                 }
16293:             }
16294:             my @offon = ('off','on');
16295:             my $corelink = &core_link_msu();
16296:             if ($changes{'reporterrors'}) {
16297:                 $resulttext .= '<li>'.
16298:                                &mt('E-mail error reports to [_1] set to "'.
16299:                                    $offon[$env{'form.reporterrors'}].'".',
16300:                                    $corelink).
16301:                                '</li>';
16302:             }
16303:             if ($changes{'reportupdates'}) {
16304:                 $resulttext .= '<li>'.
16305:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
16306:                                     $offon[$env{'form.reportupdates'}].'".',
16307:                                     $corelink).
16308:                                 '</li>';
16309:             }
16310:             if ($changes{'reportstatus'}) {
16311:                 $resulttext .= '<li>'.
16312:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
16313:                                     $offon[$env{'form.reportstatus'}].'".',
16314:                                     $corelink).
16315:                                 '</li>';
16316:             }
16317:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
16318:                 $resulttext .= '<li>'.
16319:                                &mt('Nightly status check e-mail settings').':<ul>';
16320:                 my (%defval,%use_def,%shown);
16321:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
16322:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
16323:                 $defval{'weights'} =
16324:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
16325:                 $defval{'excluded'} = &mt('None');
16326:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
16327:                     foreach my $item ('threshold','sysmail','weights','excluded') {
16328:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
16329:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
16330:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
16331:                             } elsif ($item eq 'weights') {
16332:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
16333:                                     foreach my $type ('E','W','N','U') {
16334:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
16335:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
16336:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
16337:                                         } else {
16338:                                             $shown{$item} .= $lonstatus_defs->{$type};
16339:                                         }
16340:                                         $shown{$item} .= ', ';
16341:                                     }
16342:                                     $shown{$item} =~ s/, $//;
16343:                                 } else {
16344:                                     $shown{$item} = $defval{$item};
16345:                                 }
16346:                             } elsif ($item eq 'excluded') {
16347:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
16348:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
16349:                                 } else {
16350:                                     $shown{$item} = $defval{$item};
16351:                                 }
16352:                             }
16353:                         } else {
16354:                             $shown{$item} = $defval{$item};
16355:                         }
16356:                     }
16357:                 } else {
16358:                     foreach my $item ('threshold','weights','excluded','sysmail') {
16359:                         $shown{$item} = $defval{$item};
16360:                     }
16361:                 }
16362:                 foreach my $item ('threshold','weights','excluded','sysmail') {
16363:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
16364:                                           $shown{$item}).'</li>';
16365:                 }
16366:                 $resulttext .= '</ul></li>';
16367:             }
16368:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
16369:                 my (@optional,@required,@unused,$maxsizechg);
16370:                 foreach my $field (@{$changes{'helpform'}}) {
16371:                     if ($field eq 'maxsize') {
16372:                         $maxsizechg = 1;
16373:                         next;
16374:                     }
16375:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
16376:                         push(@optional,$field);
16377:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
16378:                         push(@unused,$field);
16379:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
16380:                         push(@required,$field);
16381:                     }
16382:                 }
16383:                 if (@optional) {
16384:                     $resulttext .= '<li>'.
16385:                                    &mt('Help form fields changed to "Optional": [_1].',
16386:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
16387:                                    '</li>';
16388:                 }
16389:                 if (@required) {
16390:                     $resulttext .= '<li>'.
16391:                                    &mt('Help form fields changed to "Required": [_1].',
16392:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
16393:                                    '</li>';
16394:                 }
16395:                 if (@unused) {
16396:                     $resulttext .= '<li>'.
16397:                                    &mt('Help form fields changed to "Not shown": [_1].',
16398:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
16399:                                    '</li>';
16400:                 }
16401:                 if ($maxsizechg) {
16402:                     $resulttext .= '<li>'.
16403:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
16404:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
16405:                                    '</li>';
16406:                 }
16407:             }
16408:             $resulttext .= '</ul>';
16409:         } else {
16410:             $resulttext = &mt('No changes made to contacts and form settings');
16411:         }
16412:     } else {
16413:         $resulttext = '<span class="LC_error">'.
16414:             &mt('An error occurred: [_1].',$putresult).'</span>';
16415:     }
16416:     return $resulttext;
16417: }
16418: 
16419: sub modify_privacy {
16420:     my ($dom,%domconfig) = @_;
16421:     my ($resulttext,%current,%changes);
16422:     if (ref($domconfig{'privacy'}) eq 'HASH') {
16423:         %current = %{$domconfig{'privacy'}};
16424:     }
16425:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
16426:     my @items = ('domain','author','course','community');
16427:     my %names = &Apache::lonlocal::texthash (
16428:                    domain => 'Assigned domain role(s)',
16429:                    author => 'Assigned co-author role(s)',
16430:                    course => 'Assigned course role(s)',
16431:                    community => 'Assigned community role',
16432:                 );
16433:     my %roles = &Apache::lonlocal::texthash (
16434:                    domain => 'Domain role',
16435:                    author => 'Co-author role',
16436:                    course => 'Course role',
16437:                    community => 'Community role',
16438:                 );
16439:     my %titles = &Apache::lonlocal::texthash (
16440:                   approval => 'Approval for role in different domain',
16441:                   othdom   => 'User information available in other domain',
16442:                   priv     => 'Information viewable by privileged user in same domain',
16443:                   unpriv   => 'Information viewable by unprivileged user in same domain',
16444:                   instdom  => 'Other domain shares institution/provider',
16445:                   extdom   => 'Other domain has different institution/provider',
16446:                   none     => 'Not allowed',
16447:                   user     => 'User authorizes',
16448:                   domain   => 'Domain Coordinator authorizes',
16449:                   auto     => 'Unrestricted',
16450:     );
16451:     my %fieldnames = &Apache::lonlocal::texthash (
16452:                         id => 'Student/Employee ID',
16453:                         permanentemail => 'E-mail address',
16454:                         lastname => 'Last Name',
16455:                         firstname => 'First Name',
16456:                         middlename => 'Middle Name',
16457:                         generation => 'Generation',
16458:     );
16459:     my ($othertitle,$usertypes,$types) =
16460:         &Apache::loncommon::sorted_inst_types($dom);
16461:     my (%by_ip,%by_location,@intdoms,@instdoms);
16462:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
16463: 
16464:     my %privacyhash = (
16465:                        'approval' => {
16466:                                        instdom => {},
16467:                                        extdom  => {},
16468:                                      },
16469:                        'othdom'   => {},
16470:                        'priv'     => {},
16471:                        'unpriv'   => {},
16472:                       );
16473:     foreach my $item (@items) {
16474:         if (@instdoms > 1) {
16475:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
16476:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
16477:             }
16478:             if (ref($current{'approval'}) eq 'HASH') {
16479:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
16480:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
16481:                         $changes{'approval'} = 1;
16482:                     }
16483:                 }
16484:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
16485:                 $changes{'approval'} = 1;
16486:             }
16487:         }
16488:         if (keys(%by_location) > 0) {
16489:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
16490:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
16491:             }
16492:             if (ref($current{'approval'}) eq 'HASH') {
16493:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
16494:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
16495:                         $changes{'approval'} = 1;
16496:                     }
16497:                 }
16498:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
16499:                 $changes{'approval'} = 1;
16500:             }
16501:         }
16502:         foreach my $status ('priv','unpriv') {
16503:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
16504:             my @newvalues;
16505:             foreach my $field (@possibles) {
16506:                 if (grep(/^\Q$field\E$/,@fields)) {
16507:                     $privacyhash{$status}{$item}{$field} = 1;
16508:                     push(@newvalues,$field);
16509:                 }
16510:             }
16511:             @newvalues = sort(@newvalues);
16512:             if (ref($current{$status}) eq 'HASH') {
16513:                 if (ref($current{$status}{$item}) eq 'HASH') {
16514:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
16515:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16516:                     if (@diffs > 0) {
16517:                         $changes{$status} = 1;
16518:                     }
16519:                 }
16520:             } else {
16521:                 my @stdfields;
16522:                 foreach my $field (@fields) {
16523:                     if ($field eq 'id') {
16524:                         next if ($status eq 'unpriv');
16525:                         next if (($status eq 'priv') && ($item eq 'community'));
16526:                     }
16527:                     push(@stdfields,$field);
16528:                 }
16529:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16530:                 if (@diffs > 0) {
16531:                     $changes{$status} = 1;
16532:                 }
16533:             }
16534:         }
16535:     }
16536:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
16537:         my @statuses;
16538:         if (ref($types) eq 'ARRAY') {
16539:             @statuses = @{$types};
16540:         }
16541:         foreach my $type (@statuses,'default') {
16542:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
16543:             my @newvalues;
16544:             foreach my $field (sort(@possfields)) {
16545:                 if (grep(/^\Q$field\E$/,@fields)) {
16546:                     $privacyhash{'othdom'}{$type}{$field} = 1;
16547:                     push(@newvalues,$field);
16548:                 }
16549:             }
16550:             @newvalues = sort(@newvalues);
16551:             if (ref($current{'othdom'}) eq 'HASH') {
16552:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
16553:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
16554:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16555:                     if (@diffs > 0) {
16556:                         $changes{'othdom'} = 1;
16557:                     }
16558:                 }
16559:             } else {
16560:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
16561:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16562:                 if (@diffs > 0) {
16563:                     $changes{'othdom'} = 1;
16564:                 }
16565:             }
16566:         }
16567:     }
16568:     my %confighash = (
16569:                         privacy => \%privacyhash,
16570:                      );
16571:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16572:     if ($putresult eq 'ok') {
16573:         if (keys(%changes) > 0) {
16574:             $resulttext = &mt('Changes made: ').'<ul>';
16575:             foreach my $key ('approval','othdom','priv','unpriv') {
16576:                 if ($changes{$key}) {
16577:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16578:                     if ($key eq 'approval') {
16579:                         if (keys(%{$privacyhash{$key}{instdom}})) {
16580:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
16581:                             foreach my $item (@items) {
16582:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
16583:                             }
16584:                             $resulttext .= '</ul></li>';
16585:                         }
16586:                         if (keys(%{$privacyhash{$key}{extdom}})) {
16587:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
16588:                             foreach my $item (@items) {
16589:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
16590:                             }
16591:                             $resulttext .= '</ul></li>';
16592:                         }
16593:                     } elsif ($key eq 'othdom') {
16594:                         my @statuses;
16595:                         if (ref($types) eq 'ARRAY') {
16596:                             @statuses = @{$types};
16597:                         }
16598:                         if (ref($privacyhash{$key}) eq 'HASH') {
16599:                             foreach my $status (@statuses,'default') {
16600:                                 if ($status eq 'default') {
16601:                                     $resulttext .= '<li>'.$othertitle.': ';
16602:                                 } elsif (ref($usertypes) eq 'HASH') {
16603:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
16604:                                 } else {
16605:                                     next;
16606:                                 }
16607:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
16608:                                     if (keys(%{$privacyhash{$key}{$status}})) {
16609:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
16610:                                     } else {
16611:                                         $resulttext .= &mt('none');
16612:                                     }
16613:                                 }
16614:                                 $resulttext .= '</li>';
16615:                             }
16616:                         }
16617:                     } else {
16618:                         foreach my $item (@items) {
16619:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
16620:                                 $resulttext .= '<li>'.$names{$item}.': ';
16621:                                 if (keys(%{$privacyhash{$key}{$item}})) {
16622:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
16623:                                 } else {
16624:                                     $resulttext .= &mt('none');
16625:                                 }
16626:                                 $resulttext .= '</li>';
16627:                             }
16628:                         }
16629:                     }
16630:                     $resulttext .= '</ul></li>';
16631:                 }
16632:             }
16633:         } else {
16634:             $resulttext = &mt('No changes made to user information settings');
16635:         }
16636:     } else {
16637:         $resulttext = '<span class="LC_error">'.
16638:             &mt('An error occurred: [_1]',$putresult).'</span>';
16639:     }
16640:     return $resulttext;
16641: }
16642: 
16643: sub modify_passwords {
16644:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16645:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
16646:         $updatedefaults,$updateconf);
16647:     my $customfn = 'resetpw.html';
16648:     if (ref($domconfig{'passwords'}) eq 'HASH') {
16649:         %current = %{$domconfig{'passwords'}};
16650:     }
16651:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16652:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16653:     if (ref($types) eq 'ARRAY') {
16654:         @oktypes = @{$types};
16655:     }
16656:     push(@oktypes,'default');
16657: 
16658:     my %titles = &Apache::lonlocal::texthash (
16659:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
16660:         intauth_check  => 'Check bcrypt cost if authenticated',
16661:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
16662:         permanent      => 'Permanent e-mail address',
16663:         critical       => 'Critical notification address',
16664:         notify         => 'Notification address',
16665:         min            => 'Minimum password length',
16666:         max            => 'Maximum password length',
16667:         chars          => 'Required characters',
16668:         expire         => 'Password expiration (days)',
16669:         numsaved       => 'Number of previous passwords to save',
16670:         reset          => 'Resetting Forgotten Password',
16671:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
16672:         rules          => 'Rules for LON-CAPA Passwords',
16673:         crsownerchg    => 'Course Owner Changing Student Passwords',
16674:         username       => 'Username',
16675:         email          => 'E-mail address',
16676:     );
16677: 
16678: #
16679: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
16680: #
16681:     my (%curr_defaults,%save_defaults);
16682:     if (ref($domconfig{'defaults'}) eq 'HASH') {
16683:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
16684:             if ($key =~ /^intauth_(cost|check|switch)$/) {
16685:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
16686:             } else {
16687:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
16688:             }
16689:         }
16690:     }
16691:     my %staticdefaults = (
16692:         'resetlink'      => 2,
16693:         'resetcase'      => \@oktypes,
16694:         'resetprelink'   => 'both',
16695:         'resetemail'     => ['critical','notify','permanent'],
16696:         'intauth_cost'   => 10,
16697:         'intauth_check'  => 0,
16698:         'intauth_switch' => 0,
16699:     );
16700:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
16701:     foreach my $type (@oktypes) {
16702:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
16703:     }
16704:     my $linklife = $env{'form.passwords_link'};
16705:     $linklife =~ s/^\s+|\s+$//g;
16706:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
16707:         $newvalues{'resetlink'} = $linklife;
16708:         if ($current{'resetlink'}) {
16709:             if ($current{'resetlink'} ne $linklife) {
16710:                 $changes{'reset'} = 1;
16711:             }
16712:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16713:             if ($staticdefaults{'resetlink'} ne $linklife) {
16714:                 $changes{'reset'} = 1;
16715:             }
16716:         }
16717:     } elsif ($current{'resetlink'}) {
16718:         $changes{'reset'} = 1;
16719:     }
16720:     my @casesens;
16721:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
16722:     foreach my $case (sort(@posscase)) {
16723:         if (grep(/^\Q$case\E$/,@oktypes)) {
16724:             push(@casesens,$case);
16725:         }
16726:     }
16727:     $newvalues{'resetcase'} = \@casesens;
16728:     if (ref($current{'resetcase'}) eq 'ARRAY') {
16729:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
16730:         if (@diffs > 0) {
16731:             $changes{'reset'} = 1;
16732:         }
16733:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16734:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
16735:         if (@diffs > 0) {
16736:             $changes{'reset'} = 1;
16737:         }
16738:     }
16739:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
16740:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
16741:         if (exists($current{'resetprelink'})) {
16742:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
16743:                 $changes{'reset'} = 1;
16744:             }
16745:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16746:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
16747:                 $changes{'reset'} = 1;
16748:             }
16749:         }
16750:     } elsif ($current{'resetprelink'}) {
16751:         $changes{'reset'} = 1;
16752:     }
16753:     foreach my $type (@oktypes) {
16754:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
16755:         my @postlink;
16756:         foreach my $item (sort(@possplink)) {
16757:             if ($item =~ /^(email|username)$/) {
16758:                 push(@postlink,$item);
16759:             }
16760:         }
16761:         $newvalues{'resetpostlink'}{$type} = \@postlink;
16762:         unless ($changes{'reset'}) {
16763:             if (ref($current{'resetpostlink'}) eq 'HASH') {
16764:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
16765:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
16766:                     if (@diffs > 0) {
16767:                         $changes{'reset'} = 1;
16768:                     }
16769:                 } else {
16770:                     $changes{'reset'} = 1;
16771:                 }
16772:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16773:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
16774:                 if (@diffs > 0) {
16775:                     $changes{'reset'} = 1;
16776:                 }
16777:             }
16778:         }
16779:     }
16780:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
16781:     my @resetemail;
16782:     foreach my $item (sort(@possemailsrc)) {
16783:         if ($item =~ /^(permanent|critical|notify)$/) {
16784:             push(@resetemail,$item);
16785:         }
16786:     }
16787:     $newvalues{'resetemail'} = \@resetemail;
16788:     unless ($changes{'reset'}) {
16789:         if (ref($current{'resetemail'}) eq 'ARRAY') {
16790:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
16791:             if (@diffs > 0) {
16792:                 $changes{'reset'} = 1;
16793:             }
16794:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16795:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
16796:             if (@diffs > 0) {
16797:                 $changes{'reset'} = 1;
16798:             }
16799:         }
16800:     }
16801:     if ($env{'form.passwords_stdtext'} == 0) {
16802:         $newvalues{'resetremove'} = 1;
16803:         unless ($current{'resetremove'}) {
16804:             $changes{'reset'} = 1;
16805:         }
16806:     } elsif ($current{'resetremove'}) {
16807:         $changes{'reset'} = 1;
16808:     }
16809:     if ($env{'form.passwords_customfile.filename'} ne '') {
16810:         my $servadm = $r->dir_config('lonAdmEMail');
16811:         my ($configuserok,$author_ok,$switchserver) =
16812:             &config_check($dom,$confname,$servadm);
16813:         my $error;
16814:         if ($configuserok eq 'ok') {
16815:             if ($switchserver) {
16816:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
16817:             } else {
16818:                 if ($author_ok eq 'ok') {
16819:                     my ($result,$customurl) =
16820:                         &publishlogo($r,'upload','passwords_customfile',$dom,
16821:                                      $confname,'customtext/resetpw','','',$customfn);
16822:                     if ($result eq 'ok') {
16823:                         $newvalues{'resetcustom'} = $customurl;
16824:                         $changes{'reset'} = 1;
16825:                     } else {
16826:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
16827:                     }
16828:                 } else {
16829:                     $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);
16830:                 }
16831:             }
16832:         } else {
16833:             $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);
16834:         }
16835:         if ($error) {
16836:             &Apache::lonnet::logthis($error);
16837:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16838:         }
16839:     } elsif ($current{'resetcustom'}) {
16840:         if ($env{'form.passwords_custom_del'}) {
16841:             $changes{'reset'} = 1;
16842:         } else {
16843:             $newvalues{'resetcustom'} = $current{'resetcustom'};
16844:         }
16845:     }
16846:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
16847:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
16848:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
16849:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
16850:             $changes{'intauth'} = 1;
16851:         }
16852:     } else {
16853:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
16854:     }
16855:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
16856:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
16857:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
16858:             $changes{'intauth'} = 1;
16859:         }
16860:     } else {
16861:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16862:     }
16863:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
16864:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
16865:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
16866:             $changes{'intauth'} = 1;
16867:         }
16868:     } else {
16869:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16870:     }
16871:     foreach my $item ('cost','check','switch') {
16872:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
16873:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
16874:             $updatedefaults = 1;
16875:         }
16876:     }
16877:     foreach my $rule ('min','max','expire','numsaved') {
16878:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
16879:         my $ruleok;
16880:         if ($rule eq 'expire') {
16881:             if (($env{'form.passwords_'.$rule} =~ /^\d+(|\.\d*)$/) &&
16882:                 ($env{'form.passwords_'.$rule} ne '0')) {
16883:                 $ruleok = 1;
16884:             }
16885:         } elsif ($rule eq 'min') {
16886:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
16887:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
16888:                     $ruleok = 1;
16889:                 }
16890:             }
16891:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
16892:                  ($env{'form.passwords_'.$rule} ne '0')) {
16893:             $ruleok = 1;
16894:         }
16895:         if ($ruleok) {
16896:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
16897:             if (exists($current{$rule})) {
16898:                 if ($newvalues{$rule} ne $current{$rule}) {
16899:                     $changes{'rules'} = 1;
16900:                 }
16901:             } elsif ($rule eq 'min') {
16902:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
16903:                     $changes{'rules'} = 1;
16904:                 }
16905:             } else {
16906:                 $changes{'rules'} = 1;
16907:             }
16908:         } elsif (exists($current{$rule})) {
16909:             $changes{'rules'} = 1;
16910:         }
16911:     }
16912:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
16913:     my @chars;
16914:     foreach my $item (sort(@posschars)) {
16915:         if ($item =~ /^(uc|lc|num|spec)$/) {
16916:             push(@chars,$item);
16917:         }
16918:     }
16919:     $newvalues{'chars'} = \@chars;
16920:     unless ($changes{'rules'}) {
16921:         if (ref($current{'chars'}) eq 'ARRAY') {
16922:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
16923:             if (@diffs > 0) {
16924:                 $changes{'rules'} = 1;
16925:             }
16926:         } else {
16927:             if (@chars > 0) {
16928:                 $changes{'rules'} = 1;
16929:             }
16930:         }
16931:     }
16932:     my %crsownerchg = (
16933:                         by => [],
16934:                         for => [],
16935:                       );
16936:     foreach my $item ('by','for') {
16937:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
16938:         foreach my $type (sort(@posstypes)) {
16939:             if (grep(/^\Q$type\E$/,@oktypes)) {
16940:                 push(@{$crsownerchg{$item}},$type);
16941:             }
16942:         }
16943:     }
16944:     $newvalues{'crsownerchg'} = \%crsownerchg;
16945:     if (ref($current{'crsownerchg'}) eq 'HASH') {
16946:         foreach my $item ('by','for') {
16947:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
16948:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
16949:                 if (@diffs > 0) {
16950:                     $changes{'crsownerchg'} = 1;
16951:                     last;
16952:                 }
16953:             }
16954:         }
16955:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
16956:         foreach my $item ('by','for') {
16957:             if (@{$crsownerchg{$item}} > 0) {
16958:                 $changes{'crsownerchg'} = 1;
16959:                 last;
16960:             }
16961:         }
16962:     }
16963: 
16964:     my %confighash = (
16965:                         defaults  => \%save_defaults,
16966:                         passwords => \%newvalues,
16967:                      );
16968:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
16969: 
16970:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16971:     if ($putresult eq 'ok') {
16972:         if (keys(%changes) > 0) {
16973:             $resulttext = &mt('Changes made: ').'<ul>';
16974:             foreach my $key ('reset','intauth','rules','crsownerchg') {
16975:                 if ($changes{$key}) {
16976:                     unless ($key eq 'intauth') {
16977:                         $updateconf = 1;
16978:                     }
16979:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16980:                     if ($key eq 'reset') {
16981:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
16982:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
16983:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
16984:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
16985:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
16986:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
16987:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
16988:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
16989:                             }
16990:                         } else {
16991:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
16992:                         }
16993:                         if ($confighash{'passwords'}{'resetlink'}) {
16994:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
16995:                         } else {
16996:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
16997:                                                   &mt('Will default to 2 hours').'</li>';
16998:                         }
16999:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
17000:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
17001:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
17002:                             } else {
17003:                                 my $casesens;
17004:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
17005:                                     if ($type eq 'default') {
17006:                                         $casesens .= $othertitle.', ';
17007:                                     } elsif ($usertypes->{$type} ne '') {
17008:                                         $casesens .= $usertypes->{$type}.', ';
17009:                                     }
17010:                                 }
17011:                                 $casesens =~ s/\Q, \E$//;
17012:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
17013:                             }
17014:                         } else {
17015:                             $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>';
17016:                         }
17017:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
17018:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
17019:                         } else {
17020:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
17021:                         }
17022:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
17023:                             my $output;
17024:                             if (ref($types) eq 'ARRAY') {
17025:                                 foreach my $type (@{$types}) {
17026:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
17027:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
17028:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
17029:                                         } else {
17030:                                             $output .= $usertypes->{$type}.' -- '.
17031:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
17032:                                         }
17033:                                     }
17034:                                 }
17035:                             }
17036:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
17037:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
17038:                                     $output .= $othertitle.' -- '.&mt('none');
17039:                                 } else {
17040:                                     $output .= $othertitle.' -- '.
17041:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
17042:                                 }
17043:                             }
17044:                             if ($output) {
17045:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
17046:                             } else {
17047:                                 $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>';
17048:                             }
17049:                         } else {
17050:                             $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>';
17051:                         }
17052:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
17053:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
17054:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
17055:                             } else {
17056:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
17057:                             }
17058:                         } else {
17059:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
17060:                         }
17061:                         if ($confighash{'passwords'}{'resetremove'}) {
17062:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
17063:                         } else {
17064:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
17065:                         }
17066:                         if ($confighash{'passwords'}{'resetcustom'}) {
17067:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
17068:                                                                             &mt('custom text'),600,500,undef,undef,
17069:                                                                             undef,undef,'background-color:#ffffff');
17070:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
17071:                         } else {
17072:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
17073:                         }
17074:                     } elsif ($key eq 'intauth') {
17075:                         foreach my $item ('cost','switch','check') {
17076:                             my $value = $save_defaults{$key.'_'.$item};
17077:                             if ($item eq 'switch') {
17078:                                 my %optiondesc = &Apache::lonlocal::texthash (
17079:                                                      0 => 'No',
17080:                                                      1 => 'Yes',
17081:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
17082:                                                  );
17083:                                 if ($value =~ /^(0|1|2)$/) {
17084:                                     $value = $optiondesc{$value};
17085:                                 } else {
17086:                                     $value = &mt('none -- defaults to No');
17087:                                 }
17088:                             } elsif ($item eq 'check') {
17089:                                 my %optiondesc = &Apache::lonlocal::texthash (
17090:                                                      0 => 'No',
17091:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
17092:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
17093:                                                  );
17094:                                 if ($value =~ /^(0|1|2)$/) {
17095:                                     $value = $optiondesc{$value};
17096:                                 } else {
17097:                                     $value = &mt('none -- defaults to No');
17098:                                 }
17099:                             }
17100:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
17101:                         }
17102:                     } elsif ($key eq 'rules') {
17103:                         foreach my $rule ('min','max','expire','numsaved') {
17104:                             if ($confighash{'passwords'}{$rule} eq '') {
17105:                                 if ($rule eq 'min') {
17106:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
17107:                                                    ' '.&mt('Default of [_1] will be used',
17108:                                                            $Apache::lonnet::passwdmin).'</li>';
17109:                                 } else {
17110:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
17111:                                 }
17112:                             } else {
17113:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
17114:                             }
17115:                         }
17116:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
17117:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
17118:                                 my %rulenames = &Apache::lonlocal::texthash(
17119:                                                      uc => 'At least one upper case letter',
17120:                                                      lc => 'At least one lower case letter',
17121:                                                      num => 'At least one number',
17122:                                                      spec => 'At least one non-alphanumeric',
17123:                                                    );
17124:                                 my $needed = '<ul><li>'.
17125:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
17126:                                              '</li></ul>'; 
17127:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
17128:                             } else {
17129:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
17130:                             }
17131:                         } else {
17132:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
17133:                         }
17134:                     } elsif ($key eq 'crsownerchg') {
17135:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
17136:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
17137:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
17138:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
17139:                             } else {
17140:                                 my %crsownerstr;
17141:                                 foreach my $item ('by','for') {
17142:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
17143:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
17144:                                             if ($type eq 'default') {
17145:                                                 $crsownerstr{$item} .= $othertitle.', ';
17146:                                             } elsif ($usertypes->{$type} ne '') {
17147:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
17148:                                             }
17149:                                         }
17150:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
17151:                                     }
17152:                                 }
17153:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
17154:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
17155:                             }
17156:                         } else {
17157:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
17158:                         }
17159:                     }
17160:                     $resulttext .= '</ul></li>';
17161:                 }
17162:             }
17163:             $resulttext .= '</ul>';
17164:         } else {
17165:             $resulttext = &mt('No changes made to password settings');
17166:         }
17167:         my $cachetime = 24*60*60;
17168:         if ($updatedefaults) {
17169:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17170:             if (ref($lastactref) eq 'HASH') {
17171:                 $lastactref->{'domdefaults'} = 1;
17172:             }
17173:         }
17174:         if ($updateconf) {
17175:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
17176:             if (ref($lastactref) eq 'HASH') {
17177:                 $lastactref->{'passwdconf'} = 1;
17178:             }
17179:         }
17180:     } else {
17181:         $resulttext = '<span class="LC_error">'.
17182:             &mt('An error occurred: [_1]',$putresult).'</span>';
17183:     }
17184:     if ($errors) {
17185:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
17186:                        $errors.'</ul></p>';
17187:     }
17188:     return $resulttext;
17189: }
17190: 
17191: sub modify_usercreation {
17192:     my ($dom,%domconfig) = @_;
17193:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
17194:     my $warningmsg;
17195:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
17196:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
17197:             if ($key eq 'cancreate') {
17198:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
17199:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
17200:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
17201:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17202:                         } else {
17203:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17204:                         }
17205:                     }
17206:                 }
17207:             } elsif ($key eq 'email_rule') {
17208:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
17209:             } else {
17210:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
17211:             }
17212:         }
17213:     }
17214:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
17215:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
17216:     my @contexts = ('author','course','requestcrs');
17217:     foreach my $item(@contexts) {
17218:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
17219:     }
17220:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17221:         foreach my $item (@contexts) {
17222:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
17223:                 push(@{$changes{'cancreate'}},$item);
17224:             }
17225:         }
17226:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
17227:         foreach my $item (@contexts) {
17228:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
17229:                 if ($cancreate{$item} ne 'any') {
17230:                     push(@{$changes{'cancreate'}},$item);
17231:                 }
17232:             } else {
17233:                 if ($cancreate{$item} ne 'none') {
17234:                     push(@{$changes{'cancreate'}},$item);
17235:                 }
17236:             }
17237:         }
17238:     } else {
17239:         foreach my $item (@contexts)  {
17240:             push(@{$changes{'cancreate'}},$item);
17241:         }
17242:     }
17243: 
17244:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
17245:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
17246:             if (!grep(/^\Q$type\E$/,@username_rule)) {
17247:                 push(@{$changes{'username_rule'}},$type);
17248:             }
17249:         }
17250:         foreach my $type (@username_rule) {
17251:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
17252:                 push(@{$changes{'username_rule'}},$type);
17253:             }
17254:         }
17255:     } else {
17256:         push(@{$changes{'username_rule'}},@username_rule);
17257:     }
17258: 
17259:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
17260:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
17261:             if (!grep(/^\Q$type\E$/,@id_rule)) {
17262:                 push(@{$changes{'id_rule'}},$type);
17263:             }
17264:         }
17265:         foreach my $type (@id_rule) {
17266:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
17267:                 push(@{$changes{'id_rule'}},$type);
17268:             }
17269:         }
17270:     } else {
17271:         push(@{$changes{'id_rule'}},@id_rule);
17272:     }
17273: 
17274:     my @authen_contexts = ('author','course','domain');
17275:     my @authtypes = ('int','krb4','krb5','loc','lti');
17276:     my %authhash;
17277:     foreach my $item (@authen_contexts) {
17278:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
17279:         foreach my $auth (@authtypes) {
17280:             if (grep(/^\Q$auth\E$/,@authallowed)) {
17281:                 $authhash{$item}{$auth} = 1;
17282:             } else {
17283:                 $authhash{$item}{$auth} = 0;
17284:             }
17285:         }
17286:     }
17287:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
17288:         foreach my $item (@authen_contexts) {
17289:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
17290:                 foreach my $auth (@authtypes) {
17291:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
17292:                         push(@{$changes{'authtypes'}},$item);
17293:                         last;
17294:                     }
17295:                 }
17296:             }
17297:         }
17298:     } else {
17299:         foreach my $item (@authen_contexts) {
17300:             push(@{$changes{'authtypes'}},$item);
17301:         }
17302:     }
17303: 
17304:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
17305:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
17306:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
17307:     $save_usercreate{'id_rule'} = \@id_rule;
17308:     $save_usercreate{'username_rule'} = \@username_rule,
17309:     $save_usercreate{'authtypes'} = \%authhash;
17310: 
17311:     my %usercreation_hash =  (
17312:         usercreation     => \%save_usercreate,
17313:     );
17314: 
17315:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
17316:                                              $dom);
17317: 
17318:     if ($putresult eq 'ok') {
17319:         if (keys(%changes) > 0) {
17320:             $resulttext = &mt('Changes made:').'<ul>';
17321:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
17322:                 my %lt = &usercreation_types();
17323:                 foreach my $type (@{$changes{'cancreate'}}) {
17324:                     my $chgtext = $lt{$type}.', ';
17325:                     if ($cancreate{$type} eq 'none') {
17326:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
17327:                     } elsif ($cancreate{$type} eq 'any') {
17328:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
17329:                     } elsif ($cancreate{$type} eq 'official') {
17330:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
17331:                     } elsif ($cancreate{$type} eq 'unofficial') {
17332:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
17333:                     }
17334:                     $resulttext .= '<li>'.$chgtext.'</li>';
17335:                 }
17336:             }
17337:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
17338:                 my ($rules,$ruleorder) = 
17339:                     &Apache::lonnet::inst_userrules($dom,'username');
17340:                 my $chgtext = '<ul>';
17341:                 foreach my $type (@username_rule) {
17342:                     if (ref($rules->{$type}) eq 'HASH') {
17343:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
17344:                     }
17345:                 }
17346:                 $chgtext .= '</ul>';
17347:                 if (@username_rule > 0) {
17348:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
17349:                 } else {
17350:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
17351:                 }
17352:             }
17353:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
17354:                 my ($idrules,$idruleorder) = 
17355:                     &Apache::lonnet::inst_userrules($dom,'id');
17356:                 my $chgtext = '<ul>';
17357:                 foreach my $type (@id_rule) {
17358:                     if (ref($idrules->{$type}) eq 'HASH') {
17359:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
17360:                     }
17361:                 }
17362:                 $chgtext .= '</ul>';
17363:                 if (@id_rule > 0) {
17364:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
17365:                 } else {
17366:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
17367:                 }
17368:             }
17369:             my %authname = &authtype_names();
17370:             my %context_title = &context_names();
17371:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
17372:                 my $chgtext = '<ul>';
17373:                 foreach my $type (@{$changes{'authtypes'}}) {
17374:                     my @allowed;
17375:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
17376:                     foreach my $auth (@authtypes) {
17377:                         if ($authhash{$type}{$auth}) {
17378:                             push(@allowed,$authname{$auth});
17379:                         }
17380:                     }
17381:                     if (@allowed > 0) {
17382:                         $chgtext .= join(', ',@allowed).'</li>';
17383:                     } else {
17384:                         $chgtext .= &mt('none').'</li>';
17385:                     }
17386:                 }
17387:                 $chgtext .= '</ul>';
17388:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
17389:                 $resulttext .= '</li>';
17390:             }
17391:             $resulttext .= '</ul>';
17392:         } else {
17393:             $resulttext = &mt('No changes made to user creation settings');
17394:         }
17395:     } else {
17396:         $resulttext = '<span class="LC_error">'.
17397:             &mt('An error occurred: [_1]',$putresult).'</span>';
17398:     }
17399:     if ($warningmsg ne '') {
17400:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
17401:     }
17402:     return $resulttext;
17403: }
17404: 
17405: sub modify_selfcreation {
17406:     my ($dom,$lastactref,%domconfig) = @_;
17407:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
17408:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
17409:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17410:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
17411:     if (ref($typesref) eq 'ARRAY') {
17412:         @types = @{$typesref};
17413:     }
17414:     if (ref($usertypesref) eq 'HASH') {
17415:         %usertypes = %{$usertypesref};
17416:     }
17417:     $usertypes{'default'} = $othertitle;
17418: #
17419: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
17420: #
17421:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
17422:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
17423:             if ($key eq 'cancreate') {
17424:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
17425:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
17426:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
17427:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
17428:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
17429:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
17430:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
17431:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
17432:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17433:                         } else {
17434:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17435:                         }
17436:                     }
17437:                 }
17438:             } elsif ($key eq 'email_rule') {
17439:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
17440:             } else {
17441:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
17442:             }
17443:         }
17444:     }
17445: #
17446: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
17447: #
17448:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
17449:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
17450:             if ($key eq 'selfcreate') {
17451:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
17452:             } else {
17453:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
17454:             }
17455:         }
17456:     }
17457: #
17458: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
17459: #
17460:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
17461:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
17462:             if ($key eq 'inststatusguest') {
17463:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
17464:             } else {
17465:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
17466:             }
17467:         }
17468:     }
17469: 
17470:     my @contexts = ('selfcreate');
17471:     @{$cancreate{'selfcreate'}} = ();
17472:     %{$cancreate{'emailusername'}} = ();
17473:     if (@types) {
17474:         @{$cancreate{'statustocreate'}} = ();
17475:     }
17476:     %{$cancreate{'selfcreateprocessing'}} = ();
17477:     %{$cancreate{'shibenv'}} = ();
17478:     %{$cancreate{'emailverified'}} = ();
17479:     %{$cancreate{'emailoptions'}} = ();
17480:     %{$cancreate{'emaildomain'}} = ();
17481:     my %selfcreatetypes = (
17482:                              sso   => 'users authenticated by institutional single sign on',
17483:                              login => 'users authenticated by institutional log-in',
17484:                              email => 'users verified by e-mail',
17485:                           );
17486: #
17487: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
17488: # is permitted.
17489: #
17490:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
17491: 
17492:     my (@statuses,%email_rule);
17493:     foreach my $item ('login','sso','email') {
17494:         if ($item eq 'email') {
17495:             if ($env{'form.cancreate_email'}) {
17496:                 if (@types) {
17497:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
17498:                     foreach my $status (@poss_statuses) {
17499:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
17500:                             push(@statuses,$status);
17501:                         }
17502:                     }
17503:                     $save_inststatus{'inststatusguest'} = \@statuses;
17504:                 } else {
17505:                     push(@statuses,'default');
17506:                 }
17507:                 if (@statuses) {
17508:                     my %curr_rule;
17509:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
17510:                         foreach my $type (@statuses) {
17511:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
17512:                         }
17513:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
17514:                         foreach my $type (@statuses) {
17515:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
17516:                         }
17517:                     }
17518:                     push(@{$cancreate{'selfcreate'}},'email');
17519:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
17520:                     my %curremaildom;
17521:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
17522:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
17523:                     }
17524:                     foreach my $type (@statuses) {
17525:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
17526:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
17527:                         }
17528:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
17529:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
17530:                         }
17531:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
17532: #
17533: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
17534: #
17535:                             my $chosen = $1;
17536:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
17537:                                 my $emaildom;
17538:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
17539:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
17540:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
17541:                                     if (ref($curremaildom{$type}) eq 'HASH') {
17542:                                         if (exists($curremaildom{$type}{$chosen})) {
17543:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
17544:                                                 push(@{$changes{'cancreate'}},'emaildomain');
17545:                                             }
17546:                                         } elsif ($emaildom ne '') {
17547:                                             push(@{$changes{'cancreate'}},'emaildomain');
17548:                                         }
17549:                                     } elsif ($emaildom ne '') {
17550:                                         push(@{$changes{'cancreate'}},'emaildomain');
17551:                                     } 
17552:                                 }
17553:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17554:                             } elsif ($chosen eq 'custom') {
17555:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
17556:                                 $email_rule{$type} = [];
17557:                                 if (ref($emailrules) eq 'HASH') {
17558:                                     foreach my $rule (@possemail_rules) {
17559:                                         if (exists($emailrules->{$rule})) {
17560:                                             push(@{$email_rule{$type}},$rule);
17561:                                         }
17562:                                     }
17563:                                 }
17564:                                 if (@{$email_rule{$type}}) {
17565:                                     $cancreate{'emailoptions'}{$type} = 'custom';
17566:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
17567:                                         if (@{$curr_rule{$type}} > 0) {
17568:                                             foreach my $rule (@{$curr_rule{$type}}) {
17569:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
17570:                                                     push(@{$changes{'email_rule'}},$type);
17571:                                                 }
17572:                                             }
17573:                                         }
17574:                                         foreach my $type (@{$email_rule{$type}}) {
17575:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
17576:                                                 push(@{$changes{'email_rule'}},$type);
17577:                                             }
17578:                                         }
17579:                                     } else {
17580:                                         push(@{$changes{'email_rule'}},$type);
17581:                                     }
17582:                                 }
17583:                             } else {
17584:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17585:                             }
17586:                         }
17587:                     }
17588:                     if (@types) {
17589:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17590:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
17591:                             if (@changed) {
17592:                                 push(@{$changes{'inststatus'}},'inststatusguest');
17593:                             }
17594:                         } else {
17595:                             push(@{$changes{'inststatus'}},'inststatusguest');
17596:                         }
17597:                     }
17598:                 } else {
17599:                     delete($env{'form.cancreate_email'});
17600:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17601:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17602:                             push(@{$changes{'inststatus'}},'inststatusguest');
17603:                         }
17604:                     }
17605:                 }
17606:             } else {
17607:                 $save_inststatus{'inststatusguest'} = [];
17608:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17609:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17610:                         push(@{$changes{'inststatus'}},'inststatusguest');
17611:                     }
17612:                 }
17613:             }
17614:         } else {
17615:             if ($env{'form.cancreate_'.$item}) {
17616:                 push(@{$cancreate{'selfcreate'}},$item);
17617:             }
17618:         }
17619:     }
17620:     my (%userinfo,%savecaptcha);
17621:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
17622: #
17623: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
17624: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
17625: #
17626: 
17627:     if ($env{'form.cancreate_email'}) {
17628:         push(@contexts,'emailusername');
17629:         if (@statuses) {
17630:             foreach my $type (@statuses) {
17631:                 if (ref($infofields) eq 'ARRAY') {
17632:                     foreach my $field (@{$infofields}) {
17633:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
17634:                             $cancreate{'emailusername'}{$type}{$field} = $1;
17635:                         }
17636:                     }
17637:                 }
17638:             }
17639:         }
17640: #
17641: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
17642: # queued requests for self-creation of account verified by e-mail.
17643: #
17644: 
17645:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
17646:         @approvalnotify = sort(@approvalnotify);
17647:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
17648:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17649:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
17650:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
17651:                     push(@{$changes{'cancreate'}},'notify');
17652:                 }
17653:             } else {
17654:                 if ($cancreate{'notify'}{'approval'}) {
17655:                     push(@{$changes{'cancreate'}},'notify');
17656:                 }
17657:             }
17658:         } elsif ($cancreate{'notify'}{'approval'}) {
17659:             push(@{$changes{'cancreate'}},'notify');
17660:         }
17661: 
17662:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
17663:     }
17664: #  
17665: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
17666: # institutional log-in.
17667: #
17668:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
17669:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
17670:                ($domdefaults{'auth_def'} eq 'localauth'))) {
17671:             $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.').' '.
17672:                           &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.');
17673:         }
17674:     }
17675:     my @fields = ('lastname','firstname','middlename','generation',
17676:                   'permanentemail','id');
17677:     my @shibfields = (@fields,'inststatus');
17678:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17679: #
17680: # Where usernames may created for institutional log-in and/or institutional single sign on:
17681: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
17682: # may self-create accounts 
17683: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
17684: # which the user may supply, if institutional data is unavailable.
17685: #
17686:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
17687:         if (@types) {
17688:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
17689:             push(@contexts,'statustocreate');
17690:             foreach my $type (@types) {
17691:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
17692:                 foreach my $field (@fields) {
17693:                     if (grep(/^\Q$field\E$/,@modifiable)) {
17694:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
17695:                     } else {
17696:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
17697:                     }
17698:                 }
17699:             }
17700:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
17701:                 foreach my $type (@types) {
17702:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
17703:                         foreach my $field (@fields) {
17704:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
17705:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
17706:                                 push(@{$changes{'selfcreate'}},$type);
17707:                                 last;
17708:                             }
17709:                         }
17710:                     }
17711:                 }
17712:             } else {
17713:                 foreach my $type (@types) {
17714:                     push(@{$changes{'selfcreate'}},$type);
17715:                 }
17716:             }
17717:         }
17718:         foreach my $field (@shibfields) {
17719:             if ($env{'form.shibenv_'.$field} ne '') {
17720:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
17721:             }
17722:         }
17723:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17724:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
17725:                 foreach my $field (@shibfields) {
17726:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
17727:                         push(@{$changes{'cancreate'}},'shibenv');
17728:                     }
17729:                 }
17730:             } else {
17731:                 foreach my $field (@shibfields) {
17732:                     if ($env{'form.shibenv_'.$field}) {
17733:                         push(@{$changes{'cancreate'}},'shibenv');
17734:                         last;
17735:                     }
17736:                 }
17737:             }
17738:         }
17739:     }
17740:     foreach my $item (@contexts) {
17741:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
17742:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
17743:                 if (ref($cancreate{$item}) eq 'ARRAY') {
17744:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
17745:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17746:                             push(@{$changes{'cancreate'}},$item);
17747:                         }
17748:                     }
17749:                 }
17750:             }
17751:             if (ref($cancreate{$item}) eq 'ARRAY') {
17752:                 foreach my $type (@{$cancreate{$item}}) {
17753:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
17754:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17755:                             push(@{$changes{'cancreate'}},$item);
17756:                         }
17757:                     }
17758:                 }
17759:             }
17760:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
17761:             if (ref($cancreate{$item}) eq 'HASH') {
17762:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
17763:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17764:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
17765:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17766:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17767:                                     push(@{$changes{'cancreate'}},$item);
17768:                                 }
17769:                             }
17770:                         }
17771:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17772:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17773:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17774:                                 push(@{$changes{'cancreate'}},$item);
17775:                             }
17776:                         }
17777:                     }
17778:                 }
17779:                 foreach my $type (keys(%{$cancreate{$item}})) {
17780:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17781:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17782:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17783:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17784:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17785:                                         push(@{$changes{'cancreate'}},$item);
17786:                                     }
17787:                                 }
17788:                             } else {
17789:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17790:                                     push(@{$changes{'cancreate'}},$item);
17791:                                 }
17792:                             }
17793:                         }
17794:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17795:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17796:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17797:                                 push(@{$changes{'cancreate'}},$item);
17798:                             }
17799:                         }
17800:                     }
17801:                 }
17802:             }
17803:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
17804:             if (ref($cancreate{$item}) eq 'ARRAY') {
17805:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
17806:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17807:                         push(@{$changes{'cancreate'}},$item);
17808:                     }
17809:                 }
17810:             }
17811:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17812:             if (ref($cancreate{$item}) eq 'HASH') {
17813:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17814:                     push(@{$changes{'cancreate'}},$item);
17815:                 }
17816:             }
17817:         } elsif ($item eq 'emailusername') {
17818:             if (ref($cancreate{$item}) eq 'HASH') {
17819:                 foreach my $type (keys(%{$cancreate{$item}})) {
17820:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17821:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17822:                             if ($cancreate{$item}{$type}{$field}) {
17823:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17824:                                     push(@{$changes{'cancreate'}},$item);
17825:                                 }
17826:                                 last;
17827:                             }
17828:                         }
17829:                     }
17830:                 }
17831:             }
17832:         }
17833:     }
17834: #
17835: # Populate %save_usercreate hash with updates to self-creation configuration.
17836: #
17837:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
17838:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
17839:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
17840:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
17841:     if (ref($cancreate{'notify'}) eq 'HASH') {
17842:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
17843:     }
17844:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
17845:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
17846:     }
17847:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
17848:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
17849:     }
17850:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
17851:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
17852:     }
17853:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
17854:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
17855:     }
17856:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17857:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
17858:     }
17859:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
17860:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
17861:     }
17862:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
17863:     $save_usercreate{'email_rule'} = \%email_rule;
17864: 
17865:     my %userconfig_hash = (
17866:             usercreation     => \%save_usercreate,
17867:             usermodification => \%save_usermodify,
17868:             inststatus       => \%save_inststatus,
17869:     );
17870: 
17871:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
17872:                                              $dom);
17873: #
17874: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
17875: #
17876:     if ($putresult eq 'ok') {
17877:         if (keys(%changes) > 0) {
17878:             $resulttext = &mt('Changes made:').'<ul>';
17879:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
17880:                 my %lt = &selfcreation_types();
17881:                 foreach my $type (@{$changes{'cancreate'}}) {
17882:                     my $chgtext = '';
17883:                     if ($type eq 'selfcreate') {
17884:                         if (@{$cancreate{$type}} == 0) {
17885:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
17886:                         } else {
17887:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
17888:                                         '<ul>';
17889:                             foreach my $case (@{$cancreate{$type}}) {
17890:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
17891:                             }
17892:                             $chgtext .= '</ul>';
17893:                             if (ref($cancreate{$type}) eq 'ARRAY') {
17894:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
17895:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17896:                                         if (@{$cancreate{'statustocreate'}} == 0) {
17897:                                             $chgtext .= '<span class="LC_warning">'.
17898:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
17899:                                                         '</span><br />';
17900:                                         }
17901:                                     }
17902:                                 }
17903:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
17904:                                     if (!@statuses) {
17905:                                         $chgtext .= '<span class="LC_warning">'.
17906:                                                     &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.").
17907:                                                     '</span><br />';
17908: 
17909:                                     }
17910:                                 }
17911:                             }
17912:                         }
17913:                     } elsif ($type eq 'shibenv') {
17914:                         if (keys(%{$cancreate{$type}}) == 0) {
17915:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
17916:                         } else {
17917:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
17918:                                         '<ul>';
17919:                             foreach my $field (@shibfields) {
17920:                                 next if ($cancreate{$type}{$field} eq '');
17921:                                 if ($field eq 'inststatus') {
17922:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
17923:                                 } else {
17924:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
17925:                                 }
17926:                             }
17927:                             $chgtext .= '</ul>';
17928:                         }
17929:                     } elsif ($type eq 'statustocreate') {
17930:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
17931:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
17932:                             if (@{$cancreate{'selfcreate'}} > 0) {
17933:                                 if (@{$cancreate{'statustocreate'}} == 0) {
17934:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
17935:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
17936:                                         $chgtext .= '<br />'.
17937:                                                     '<span class="LC_warning">'.
17938:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
17939:                                                     '</span>';
17940:                                     }
17941:                                 } elsif (keys(%usertypes) > 0) {
17942:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17943:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
17944:                                     } else {
17945:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
17946:                                     }
17947:                                     $chgtext .= '<ul>';
17948:                                     foreach my $case (@{$cancreate{$type}}) {
17949:                                         if ($case eq 'default') {
17950:                                             $chgtext .= '<li>'.$othertitle.'</li>';
17951:                                         } else {
17952:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
17953:                                         }
17954:                                     }
17955:                                     $chgtext .= '</ul>';
17956:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17957:                                         $chgtext .= '<span class="LC_warning">'.
17958:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
17959:                                                     '</span>';
17960:                                     }
17961:                                 }
17962:                             } else {
17963:                                 if (@{$cancreate{$type}} == 0) {
17964:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
17965:                                 } else {
17966:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
17967:                                 }
17968:                             }
17969:                             $chgtext .= '<br />';
17970:                         }
17971:                     } elsif ($type eq 'selfcreateprocessing') {
17972:                         my %choices = &Apache::lonlocal::texthash (
17973:                                                                     automatic => 'Automatic approval',
17974:                                                                     approval  => 'Queued for approval',
17975:                                                                   );
17976:                         if (@types) {
17977:                             if (@statuses) {
17978:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
17979:                                             '<ul>';
17980:                                 foreach my $status (@statuses) {
17981:                                     if ($status eq 'default') {
17982:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17983:                                     } else {
17984:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17985:                                     }
17986:                                 }
17987:                                 $chgtext .= '</ul>';
17988:                             }
17989:                         } else {
17990:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
17991:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
17992:                         }
17993:                     } elsif ($type eq 'emailverified') {
17994:                         my %options = &Apache::lonlocal::texthash (
17995:                                                                     all   => 'Same as e-mail',
17996:                                                                     first => 'Omit @domain',
17997:                                                                     free  => 'Free to choose',
17998:                                                                   );
17999:                         if (@types) {
18000:                             if (@statuses) {
18001:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
18002:                                             '<ul>';
18003:                                 foreach my $status (@statuses) {
18004:                                     if ($status eq 'default') {
18005:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
18006:                                     } else {
18007:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
18008:                                     }
18009:                                 }
18010:                                 $chgtext .= '</ul>';
18011:                             }
18012:                         } else {
18013:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
18014:                                             $options{$cancreate{'emailverified'}{'default'}});
18015:                         }
18016:                     } elsif ($type eq 'emailoptions') {
18017:                         my %options = &Apache::lonlocal::texthash (
18018:                                                                     any     => 'Any e-mail',
18019:                                                                     inst    => 'Institutional only',
18020:                                                                     noninst => 'Non-institutional only',
18021:                                                                     custom  => 'Custom restrictions',
18022:                                                                   );
18023:                         if (@types) {
18024:                             if (@statuses) {
18025:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
18026:                                             '<ul>';
18027:                                 foreach my $status (@statuses) {
18028:                                     if ($type eq 'default') {
18029:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
18030:                                     } else {
18031:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
18032:                                     }
18033:                                 }
18034:                                 $chgtext .= '</ul>';
18035:                             }
18036:                         } else {
18037:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
18038:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
18039:                             } else {
18040:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
18041:                                                 $options{$cancreate{'emailoptions'}{'default'}});
18042:                             }
18043:                         }
18044:                     } elsif ($type eq 'emaildomain') {
18045:                         my $output;
18046:                         if (@statuses) {
18047:                             foreach my $type (@statuses) {
18048:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
18049:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
18050:                                         if ($type eq 'default') {
18051:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18052:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
18053:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
18054:                                             } else {
18055:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
18056:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
18057:                                             }
18058:                                         } else {
18059:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18060:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
18061:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
18062:                                             } else {
18063:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
18064:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
18065:                                             }
18066:                                         }
18067:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
18068:                                         if ($type eq 'default') {
18069:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18070:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
18071:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
18072:                                             } else {
18073:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
18074:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
18075:                                             }
18076:                                         } else {
18077:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
18078:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
18079:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
18080:                                             } else {
18081:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
18082:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
18083:                                             }
18084:                                         }
18085:                                     }
18086:                                 }
18087:                             }
18088:                         }
18089:                         if ($output ne '') {
18090:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
18091:                                         '<ul>'.$output.'</ul>';
18092:                         }
18093:                     } elsif ($type eq 'captcha') {
18094:                         if ($savecaptcha{$type} eq 'notused') {
18095:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
18096:                         } else {
18097:                             my %captchas = &captcha_phrases();
18098:                             if ($captchas{$savecaptcha{$type}}) {
18099:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
18100:                             } else {
18101:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
18102:                             }
18103:                         }
18104:                     } elsif ($type eq 'recaptchakeys') {
18105:                         my ($privkey,$pubkey);
18106:                         if (ref($savecaptcha{$type}) eq 'HASH') {
18107:                             $pubkey = $savecaptcha{$type}{'public'};
18108:                             $privkey = $savecaptcha{$type}{'private'};
18109:                         }
18110:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
18111:                         if (!$pubkey) {
18112:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
18113:                         } else {
18114:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
18115:                         }
18116:                         if (!$privkey) {
18117:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
18118:                         } else {
18119:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
18120:                         }
18121:                         $chgtext .= '</ul>';
18122:                     } elsif ($type eq 'recaptchaversion') {
18123:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
18124:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
18125:                         }
18126:                     } elsif ($type eq 'emailusername') {
18127:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
18128:                             if (@statuses) {
18129:                                 foreach my $type (@statuses) {
18130:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
18131:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
18132:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
18133:                                                     '<ul>';
18134:                                             foreach my $field (@{$infofields}) {
18135:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
18136:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
18137:                                                 }
18138:                                             }
18139:                                             $chgtext .= '</ul>';
18140:                                         } else {
18141:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
18142:                                         }
18143:                                     } else {
18144:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
18145:                                     }
18146:                                 }
18147:                             }
18148:                         }
18149:                     } elsif ($type eq 'notify') {
18150:                         my $numapprove = 0;
18151:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
18152:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
18153:                                 if ($cancreate{'notify'}{'approval'}) {
18154:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
18155:                                     $numapprove ++;
18156:                                 }
18157:                             }
18158:                         }
18159:                         unless ($numapprove) {
18160:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
18161:                         }
18162:                     }
18163:                     if ($chgtext) {
18164:                         $resulttext .= '<li>'.$chgtext.'</li>';
18165:                     }
18166:                 }
18167:             }
18168:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
18169:                 my ($emailrules,$emailruleorder) =
18170:                     &Apache::lonnet::inst_userrules($dom,'email');
18171:                 foreach my $type (@{$changes{'email_rule'}}) {
18172:                     if (ref($email_rule{$type}) eq 'ARRAY') {
18173:                         my $chgtext = '<ul>';
18174:                         foreach my $rule (@{$email_rule{$type}}) {
18175:                             if (ref($emailrules->{$rule}) eq 'HASH') {
18176:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
18177:                             }
18178:                         }
18179:                         $chgtext .= '</ul>';
18180:                         my $typename;
18181:                         if (@types) {
18182:                             if ($type eq 'default') {
18183:                                 $typename = $othertitle;
18184:                             } else {
18185:                                 $typename = $usertypes{$type};
18186:                             } 
18187:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
18188:                         }
18189:                         if (@{$email_rule{$type}} > 0) {
18190:                             $resulttext .= '<li>'.
18191:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
18192:                                                $usertypes{$type}).
18193:                                            $chgtext.
18194:                                            '</li>';
18195:                         } else {
18196:                             $resulttext .= '<li>'.
18197:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
18198:                                            '</li>'.
18199:                                            &mt('(Affiliation: [_1])',$typename);
18200:                         }
18201:                     }
18202:                 }
18203:             }
18204:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
18205:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
18206:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
18207:                         my $chgtext = '<ul>';
18208:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
18209:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
18210:                         }
18211:                         $chgtext .= '</ul>';
18212:                         $resulttext .= '<li>'.
18213:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
18214:                                           $chgtext.
18215:                                        '</li>';
18216:                     } else {
18217:                         $resulttext .= '<li>'.
18218:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
18219:                                        '</li>';
18220:                     }
18221:                 }
18222:             }
18223:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
18224:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
18225:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
18226:                 foreach my $type (@{$changes{'selfcreate'}}) {
18227:                     my $typename = $type;
18228:                     if (keys(%usertypes) > 0) {
18229:                         if ($usertypes{$type} ne '') {
18230:                             $typename = $usertypes{$type};
18231:                         }
18232:                     }
18233:                     my @modifiable;
18234:                     $resulttext .= '<li>'.
18235:                                     &mt('Self-creation of account by users with status: [_1]',
18236:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
18237:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
18238:                     foreach my $field (@fields) {
18239:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
18240:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
18241:                         }
18242:                     }
18243:                     if (@modifiable > 0) {
18244:                         $resulttext .= join(', ',@modifiable);
18245:                     } else {
18246:                         $resulttext .= &mt('none');
18247:                     }
18248:                     $resulttext .= '</li>';
18249:                 }
18250:                 $resulttext .= '</ul></li>';
18251:             }
18252:             $resulttext .= '</ul>';
18253:             my $cachetime = 24*60*60;
18254:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
18255:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18256:             if (ref($lastactref) eq 'HASH') {
18257:                 $lastactref->{'domdefaults'} = 1;
18258:             }
18259:         } else {
18260:             $resulttext = &mt('No changes made to self-creation settings');
18261:         }
18262:     } else {
18263:         $resulttext = '<span class="LC_error">'.
18264:             &mt('An error occurred: [_1]',$putresult).'</span>';
18265:     }
18266:     if ($warningmsg ne '') {
18267:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18268:     }
18269:     return $resulttext;
18270: }
18271: 
18272: sub process_captcha {
18273:     my ($container,$changes,$newsettings,$currsettings) = @_;
18274:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
18275:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
18276:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
18277:         $newsettings->{'captcha'} = 'original';
18278:     }
18279:     my %current;
18280:     if (ref($currsettings) eq 'HASH') {
18281:         %current = %{$currsettings};
18282:     }
18283:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
18284:         if ($container eq 'cancreate') {
18285:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
18286:                 push(@{$changes->{'cancreate'}},'captcha');
18287:             } elsif (!defined($changes->{'cancreate'})) {
18288:                 $changes->{'cancreate'} = ['captcha'];
18289:             }
18290:         } elsif ($container eq 'passwords') {
18291:             $changes->{'reset'} = 1;
18292:         } else {
18293:             $changes->{'captcha'} = 1;
18294:         }
18295:     }
18296:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
18297:     if ($newsettings->{'captcha'} eq 'recaptcha') {
18298:         $newpub = $env{'form.'.$container.'_recaptchapub'};
18299:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
18300:         $newpub =~ s/[^\w\-]//g;
18301:         $newpriv =~ s/[^\w\-]//g;
18302:         $newsettings->{'recaptchakeys'} = {
18303:                                              public  => $newpub,
18304:                                              private => $newpriv,
18305:                                           };
18306:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
18307:         $newversion =~ s/\D//g;
18308:         if ($newversion ne '2') {
18309:             $newversion = 1;
18310:         }
18311:         $newsettings->{'recaptchaversion'} = $newversion;
18312:     }
18313:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
18314:         $currpub = $current{'recaptchakeys'}{'public'};
18315:         $currpriv = $current{'recaptchakeys'}{'private'};
18316:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
18317:             $newsettings->{'recaptchakeys'} = {
18318:                                                  public  => '',
18319:                                                  private => '',
18320:                                               }
18321:         }
18322:     }
18323:     if ($current{'captcha'} eq 'recaptcha') {
18324:         $currversion = $current{'recaptchaversion'};
18325:         if ($currversion ne '2') {
18326:             $currversion = 1;
18327:         }
18328:     }
18329:     if ($currversion ne $newversion) {
18330:         if ($container eq 'cancreate') {
18331:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
18332:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
18333:             } elsif (!defined($changes->{'cancreate'})) {
18334:                 $changes->{'cancreate'} = ['recaptchaversion'];
18335:             }
18336:         } elsif ($container eq 'passwords') {
18337:             $changes->{'reset'} = 1;
18338:         } else {
18339:             $changes->{'recaptchaversion'} = 1;
18340:         }
18341:     }
18342:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
18343:         if ($container eq 'cancreate') {
18344:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
18345:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
18346:             } elsif (!defined($changes->{'cancreate'})) {
18347:                 $changes->{'cancreate'} = ['recaptchakeys'];
18348:             }
18349:         } elsif ($container eq 'passwords') {
18350:             $changes->{'reset'} = 1;
18351:         } else {
18352:             $changes->{'recaptchakeys'} = 1;
18353:         }
18354:     }
18355:     return;
18356: }
18357: 
18358: sub modify_usermodification {
18359:     my ($dom,%domconfig) = @_;
18360:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
18361:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
18362:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
18363:             if ($key eq 'selfcreate') {
18364:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
18365:             } else {  
18366:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
18367:             }
18368:         }
18369:     }
18370:     my @contexts = ('author','course');
18371:     my %context_title = (
18372:                            author => 'In author context',
18373:                            course => 'In course context',
18374:                         );
18375:     my @fields = ('lastname','firstname','middlename','generation',
18376:                   'permanentemail','id');
18377:     my %roles = (
18378:                   author => ['ca','aa'],
18379:                   course => ['st','ep','ta','in','cr'],
18380:                 );
18381:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
18382:     foreach my $context (@contexts) {
18383:         foreach my $role (@{$roles{$context}}) {
18384:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
18385:             foreach my $item (@fields) {
18386:                 if (grep(/^\Q$item\E$/,@modifiable)) {
18387:                     $modifyhash{$context}{$role}{$item} = 1;
18388:                 } else {
18389:                     $modifyhash{$context}{$role}{$item} = 0;
18390:                 }
18391:             }
18392:         }
18393:         if (ref($curr_usermodification{$context}) eq 'HASH') {
18394:             foreach my $role (@{$roles{$context}}) {
18395:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
18396:                     foreach my $field (@fields) {
18397:                         if ($modifyhash{$context}{$role}{$field} ne 
18398:                                 $curr_usermodification{$context}{$role}{$field}) {
18399:                             push(@{$changes{$context}},$role);
18400:                             last;
18401:                         }
18402:                     }
18403:                 }
18404:             }
18405:         } else {
18406:             foreach my $context (@contexts) {
18407:                 foreach my $role (@{$roles{$context}}) {
18408:                     push(@{$changes{$context}},$role);
18409:                 }
18410:             }
18411:         }
18412:     }
18413:     my %usermodification_hash =  (
18414:                                    usermodification => \%modifyhash,
18415:                                  );
18416:     my $putresult = &Apache::lonnet::put_dom('configuration',
18417:                                              \%usermodification_hash,$dom);
18418:     if ($putresult eq 'ok') {
18419:         if (keys(%changes) > 0) {
18420:             $resulttext = &mt('Changes made: ').'<ul>';
18421:             foreach my $context (@contexts) {
18422:                 if (ref($changes{$context}) eq 'ARRAY') {
18423:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
18424:                     if (ref($changes{$context}) eq 'ARRAY') {
18425:                         foreach my $role (@{$changes{$context}}) {
18426:                             my $rolename;
18427:                             if ($role eq 'cr') {
18428:                                 $rolename = &mt('Custom');
18429:                             } else {
18430:                                 $rolename = &Apache::lonnet::plaintext($role);
18431:                             }
18432:                             my @modifiable;
18433:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
18434:                             foreach my $field (@fields) {
18435:                                 if ($modifyhash{$context}{$role}{$field}) {
18436:                                     push(@modifiable,$fieldtitles{$field});
18437:                                 }
18438:                             }
18439:                             if (@modifiable > 0) {
18440:                                 $resulttext .= join(', ',@modifiable);
18441:                             } else {
18442:                                 $resulttext .= &mt('none'); 
18443:                             }
18444:                             $resulttext .= '</li>';
18445:                         }
18446:                         $resulttext .= '</ul></li>';
18447:                     }
18448:                 }
18449:             }
18450:             $resulttext .= '</ul>';
18451:         } else {
18452:             $resulttext = &mt('No changes made to user modification settings');
18453:         }
18454:     } else {
18455:         $resulttext = '<span class="LC_error">'.
18456:             &mt('An error occurred: [_1]',$putresult).'</span>';
18457:     }
18458:     return $resulttext;
18459: }
18460: 
18461: sub modify_defaults {
18462:     my ($dom,$lastactref,%domconfig) = @_;
18463:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
18464:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18465:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
18466:                  'portal_def');
18467:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
18468:     foreach my $item (@items) {
18469:         $newvalues{$item} = $env{'form.'.$item};
18470:         if ($item eq 'auth_def') {
18471:             if ($newvalues{$item} ne '') {
18472:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
18473:                     push(@errors,$item);
18474:                 }
18475:             }
18476:         } elsif ($item eq 'lang_def') {
18477:             if ($newvalues{$item} ne '') {
18478:                 if ($newvalues{$item} =~ /^(\w+)/) {
18479:                     my $langcode = $1;
18480:                     if ($langcode ne 'x_chef') {
18481:                         if (code2language($langcode) eq '') {
18482:                             push(@errors,$item);
18483:                         }
18484:                     }
18485:                 } else {
18486:                     push(@errors,$item);
18487:                 }
18488:             }
18489:         } elsif ($item eq 'timezone_def') {
18490:             if ($newvalues{$item} ne '') {
18491:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
18492:                     push(@errors,$item);   
18493:                 }
18494:             }
18495:         } elsif ($item eq 'datelocale_def') {
18496:             if ($newvalues{$item} ne '') {
18497:                 my @datelocale_ids = DateTime::Locale->ids();
18498:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
18499:                     push(@errors,$item);
18500:                 }
18501:             }
18502:         } elsif ($item eq 'portal_def') {
18503:             if ($newvalues{$item} ne '') {
18504:                 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])\/?$/) {
18505:                     push(@errors,$item);
18506:                 }
18507:             }
18508:         }
18509:         if (grep(/^\Q$item\E$/,@errors)) {
18510:             $newvalues{$item} = $domdefaults{$item};
18511:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
18512:             $changes{$item} = 1;
18513:         }
18514:         $domdefaults{$item} = $newvalues{$item};
18515:     }
18516:     my %staticdefaults = (
18517:                            'intauth_cost'   => 10,
18518:                            'intauth_check'  => 0,
18519:                            'intauth_switch' => 0,
18520:                          );
18521:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
18522:         if (exists($domdefaults{$item})) {
18523:             $newvalues{$item} = $domdefaults{$item};
18524:         } else {
18525:             $newvalues{$item} = $staticdefaults{$item};
18526:         }
18527:     }
18528:     my %defaults_hash = (
18529:                          defaults => \%newvalues,
18530:                         );
18531:     my $title = &defaults_titles();
18532: 
18533:     my $currinststatus;
18534:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18535:         $currinststatus = $domconfig{'inststatus'};
18536:     } else {
18537:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18538:         $currinststatus = {
18539:                              inststatustypes => $usertypes,
18540:                              inststatusorder => $types,
18541:                              inststatusguest => [],
18542:                           };
18543:     }
18544:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
18545:     my @allpos;
18546:     my %alltypes;
18547:     my @inststatusguest;
18548:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
18549:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
18550:             unless (grep(/^\Q$type\E$/,@todelete)) {
18551:                 push(@inststatusguest,$type);
18552:             }
18553:         }
18554:     }
18555:     my ($currtitles,$currorder);
18556:     if (ref($currinststatus) eq 'HASH') {
18557:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
18558:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
18559:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
18560:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
18561:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
18562:                     }
18563:                 }
18564:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
18565:                     my $position = $env{'form.inststatus_pos_'.$type};
18566:                     $position =~ s/\D+//g;
18567:                     $allpos[$position] = $type;
18568:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
18569:                     $alltypes{$type} =~ s/`//g;
18570:                 }
18571:             }
18572:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
18573:             $currtitles =~ s/,$//;
18574:         }
18575:     }
18576:     if ($env{'form.addinststatus'}) {
18577:         my $newtype = $env{'form.addinststatus'};
18578:         $newtype =~ s/\W//g;
18579:         unless (exists($alltypes{$newtype})) {
18580:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
18581:             $alltypes{$newtype} =~ s/`//g; 
18582:             my $position = $env{'form.addinststatus_pos'};
18583:             $position =~ s/\D+//g;
18584:             if ($position ne '') {
18585:                 $allpos[$position] = $newtype;
18586:             }
18587:         }
18588:     }
18589:     my @orderedstatus;
18590:     foreach my $type (@allpos) {
18591:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
18592:             push(@orderedstatus,$type);
18593:         }
18594:     }
18595:     foreach my $type (keys(%alltypes)) {
18596:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
18597:             delete($alltypes{$type});
18598:         }
18599:     }
18600:     $defaults_hash{'inststatus'} = {
18601:                                      inststatustypes => \%alltypes,
18602:                                      inststatusorder => \@orderedstatus,
18603:                                      inststatusguest => \@inststatusguest,
18604:                                    };
18605:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
18606:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
18607:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
18608:         }
18609:     }
18610:     if ($currorder ne join(',',@orderedstatus)) {
18611:         $changes{'inststatus'}{'inststatusorder'} = 1;
18612:     }
18613:     my $newtitles;
18614:     foreach my $item (@orderedstatus) {
18615:         $newtitles .= $alltypes{$item}.',';
18616:     }
18617:     $newtitles =~ s/,$//;
18618:     if ($currtitles ne $newtitles) {
18619:         $changes{'inststatus'}{'inststatustypes'} = 1;
18620:     }
18621:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
18622:                                              $dom);
18623:     if ($putresult eq 'ok') {
18624:         if (keys(%changes) > 0) {
18625:             $resulttext = &mt('Changes made:').'<ul>';
18626:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
18627:             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";
18628:             foreach my $item (sort(keys(%changes))) {
18629:                 if ($item eq 'inststatus') {
18630:                     if (ref($changes{'inststatus'}) eq 'HASH') {
18631:                         if (@orderedstatus) {
18632:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
18633:                             foreach my $type (@orderedstatus) { 
18634:                                 $resulttext .= $alltypes{$type}.', ';
18635:                             }
18636:                             $resulttext =~ s/, $//;
18637:                             $resulttext .= '</li>';
18638:                         } else {
18639:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
18640:                         }
18641:                     }
18642:                 } else {
18643:                     my $value = $env{'form.'.$item};
18644:                     if ($value eq '') {
18645:                         $value = &mt('none');
18646:                     } elsif ($item eq 'auth_def') {
18647:                         my %authnames = &authtype_names();
18648:                         my %shortauth = (
18649:                                           internal   => 'int',
18650:                                           krb4       => 'krb4',
18651:                                           krb5       => 'krb5',
18652:                                           localauth  => 'loc',
18653:                                           lti        => 'lti',
18654:                         );
18655:                         $value = $authnames{$shortauth{$value}};
18656:                     }
18657:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
18658:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
18659:                 }
18660:             }
18661:             $resulttext .= '</ul>';
18662:             $mailmsgtext .= "\n";
18663:             my $cachetime = 24*60*60;
18664:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18665:             if (ref($lastactref) eq 'HASH') {
18666:                 $lastactref->{'domdefaults'} = 1;
18667:             }
18668:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
18669:                 my $notify = 1;
18670:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
18671:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
18672:                         $notify = 0;
18673:                     }
18674:                 }
18675:                 if ($notify) {
18676:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
18677:                                                "LON-CAPA Domain Settings Change - $dom",
18678:                                                $mailmsgtext);
18679:                 }
18680:             }
18681:         } else {
18682:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
18683:         }
18684:     } else {
18685:         $resulttext = '<span class="LC_error">'.
18686:             &mt('An error occurred: [_1]',$putresult).'</span>';
18687:     }
18688:     if (@errors > 0) {
18689:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
18690:         foreach my $item (@errors) {
18691:             $resulttext .= ' "'.$title->{$item}.'",';
18692:         }
18693:         $resulttext =~ s/,$//;
18694:     }
18695:     return $resulttext;
18696: }
18697: 
18698: sub modify_scantron {
18699:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18700:     my ($resulttext,%confhash,%changes,$errors);
18701:     my $custom = 'custom.tab';
18702:     my $default = 'default.tab';
18703:     my $servadm = $r->dir_config('lonAdmEMail');
18704:     my ($configuserok,$author_ok,$switchserver) =
18705:         &config_check($dom,$confname,$servadm);
18706:     if ($env{'form.scantronformat.filename'} ne '') {
18707:         my $error;
18708:         if ($configuserok eq 'ok') {
18709:             if ($switchserver) {
18710:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
18711:             } else {
18712:                 if ($author_ok eq 'ok') {
18713:                     my ($result,$scantronurl) =
18714:                         &publishlogo($r,'upload','scantronformat',$dom,
18715:                                      $confname,'scantron','','',$custom);
18716:                     if ($result eq 'ok') {
18717:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
18718:                         $changes{'scantronformat'} = 1;
18719:                     } else {
18720:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
18721:                     }
18722:                 } else {
18723:                     $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);
18724:                 }
18725:             }
18726:         } else {
18727:             $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);
18728:         }
18729:         if ($error) {
18730:             &Apache::lonnet::logthis($error);
18731:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18732:         }
18733:     }
18734:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18735:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
18736:             if ($env{'form.scantronformat_del'}) {
18737:                 $confhash{'scantron'}{'scantronformat'} = '';
18738:                 $changes{'scantronformat'} = 1;
18739:             } else {
18740:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
18741:             }
18742:         }
18743:     }
18744:     my @options = ('hdr','pad','rem');
18745:     my @fields = &scantroncsv_fields();
18746:     my %titles = &scantronconfig_titles();
18747:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
18748:     my ($newdat,$currdat,%newcol,%currcol);
18749:     if (grep(/^dat$/,@formats)) {
18750:         $confhash{'scantron'}{config}{dat} = 1;
18751:         $newdat = 1;
18752:     } else {
18753:         $newdat = 0;
18754:     }
18755:     if (grep(/^csv$/,@formats)) {
18756:         my %bynum;
18757:         foreach my $field (@fields) {
18758:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
18759:                 my $posscol = $1;
18760:                 if (($posscol < 20) && (!$bynum{$posscol})) {
18761:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
18762:                     $bynum{$posscol} = $field;
18763:                     $newcol{$field} = $posscol;
18764:                 }
18765:             }
18766:         }
18767:         if (keys(%newcol)) {
18768:             foreach my $option (@options) {
18769:                 if ($env{'form.scantroncsv_'.$option}) {
18770:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
18771:                 }
18772:             }
18773:         }
18774:     }
18775:     $currdat = 1;
18776:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18777:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
18778:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
18779:                 $currdat = 0;
18780:             }
18781:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18782:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18783:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
18784:                 }
18785:             }
18786:         }
18787:     }
18788:     if ($currdat != $newdat) {
18789:         $changes{'config'} = 1;
18790:     } else {
18791:         foreach my $field (@fields) {
18792:             if ($currcol{$field} ne '') {
18793:                 if ($currcol{$field} ne $newcol{$field}) {
18794:                     $changes{'config'} = 1;
18795:                     last;
18796:                 }
18797:             } elsif ($newcol{$field} ne '') {
18798:                 $changes{'config'} = 1;
18799:                 last;
18800:             }
18801:         }
18802:     }
18803:     if (keys(%confhash) > 0) {
18804:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
18805:                                                  $dom);
18806:         if ($putresult eq 'ok') {
18807:             if (keys(%changes) > 0) {
18808:                 if (ref($confhash{'scantron'}) eq 'HASH') {
18809:                     $resulttext = &mt('Changes made:').'<ul>';
18810:                     if ($changes{'scantronformat'}) {
18811:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
18812:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
18813:                         } else {
18814:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
18815:                         }
18816:                     }
18817:                     if ($changes{'config'}) {
18818:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
18819:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
18820:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
18821:                             }
18822:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18823:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18824:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
18825:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
18826:                                         foreach my $field (@fields) {
18827:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
18828:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
18829:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
18830:                                             }
18831:                                         }
18832:                                         $resulttext .= '</ul></li>';
18833:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
18834:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
18835:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
18836:                                                 foreach my $option (@options) {
18837:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
18838:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
18839:                                                     }
18840:                                                 }
18841:                                                 $resulttext .= '</ul></li>';
18842:                                             }
18843:                                         }
18844:                                     }
18845:                                 }
18846:                             }
18847:                         } else {
18848:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
18849:                         }
18850:                     }
18851:                     $resulttext .= '</ul>';
18852:                 } else {
18853:                     $resulttext = &mt('Changes made to bubblesheet format file.');
18854:                 }
18855:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
18856:                 if (ref($lastactref) eq 'HASH') {
18857:                     $lastactref->{'domainconfig'} = 1;
18858:                 }
18859:             } else {
18860:                 $resulttext = &mt('No changes made to bubblesheet format settings');
18861:             }
18862:         } else {
18863:             $resulttext = '<span class="LC_error">'.
18864:                 &mt('An error occurred: [_1]',$putresult).'</span>';
18865:         }
18866:     } else {
18867:         $resulttext = &mt('No changes made to bubblesheet format file'); 
18868:     }
18869:     if ($errors) {
18870:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18871:                        $errors.'</ul></p>';
18872:     }
18873:     return $resulttext;
18874: }
18875: 
18876: sub modify_coursecategories {
18877:     my ($dom,$lastactref,%domconfig) = @_;
18878:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
18879:         $cathash);
18880:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
18881:     my @catitems = ('unauth','auth');
18882:     my @cattypes = ('std','domonly','codesrch','none');
18883:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
18884:         $cathash = $domconfig{'coursecategories'}{'cats'};
18885:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
18886:             $changes{'togglecats'} = 1;
18887:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
18888:         }
18889:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
18890:             $changes{'categorize'} = 1;
18891:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
18892:         }
18893:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
18894:             $changes{'togglecatscomm'} = 1;
18895:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
18896:         }
18897:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
18898:             $changes{'categorizecomm'} = 1;
18899:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
18900: 
18901:         }
18902:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
18903:             $changes{'togglecatsplace'} = 1;
18904:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
18905:         }
18906:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
18907:             $changes{'categorizeplace'} = 1;
18908:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
18909:         }
18910:         foreach my $item (@catitems) {
18911:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18912:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
18913:                     $changes{$item} = 1;
18914:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18915:                 }
18916:             }
18917:         }
18918:     } else {
18919:         $changes{'togglecats'} = 1;
18920:         $changes{'categorize'} = 1;
18921:         $changes{'togglecatscomm'} = 1;
18922:         $changes{'categorizecomm'} = 1;
18923:         $changes{'togglecatsplace'} = 1;
18924:         $changes{'categorizeplace'} = 1;
18925:         $domconfig{'coursecategories'} = {
18926:                                              togglecats => $env{'form.togglecats'},
18927:                                              categorize => $env{'form.categorize'},
18928:                                              togglecatscomm => $env{'form.togglecatscomm'},
18929:                                              categorizecomm => $env{'form.categorizecomm'},
18930:                                              togglecatsplace => $env{'form.togglecatsplace'},
18931:                                              categorizeplace => $env{'form.categorizeplace'},
18932:                                          };
18933:         foreach my $item (@catitems) {
18934:             if ($env{'form.coursecat_'.$item} ne 'std') {
18935:                 $changes{$item} = 1;
18936:             }
18937:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18938:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18939:             }
18940:         }
18941:     }
18942:     if (ref($cathash) eq 'HASH') {
18943:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
18944:             push (@deletecategory,'instcode::0');
18945:         }
18946:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
18947:             push(@deletecategory,'communities::0');
18948:         }
18949:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
18950:             push(@deletecategory,'placement::0');
18951:         }
18952:     }
18953:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
18954:     if (ref($cathash) eq 'HASH') {
18955:         if (@deletecategory > 0) {
18956:             #FIXME Need to remove category from all courses using a deleted category 
18957:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
18958:             foreach my $item (@deletecategory) {
18959:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
18960:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
18961:                     $deletions{$item} = 1;
18962:                     &recurse_cat_deletes($item,$cathash,\%deletions);
18963:                 }
18964:             }
18965:         }
18966:         foreach my $item (keys(%{$cathash})) {
18967:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
18968:             if ($cathash->{$item} ne $env{'form.'.$item}) {
18969:                 $reorderings{$item} = 1;
18970:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
18971:             }
18972:             if ($env{'form.addcategory_name_'.$item} ne '') {
18973:                 my $newcat = $env{'form.addcategory_name_'.$item};
18974:                 my $newdepth = $depth+1;
18975:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18976:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
18977:                 $adds{$newitem} = 1; 
18978:             }
18979:             if ($env{'form.subcat_'.$item} ne '') {
18980:                 my $newcat = $env{'form.subcat_'.$item};
18981:                 my $newdepth = $depth+1;
18982:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18983:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
18984:                 $adds{$newitem} = 1;
18985:             }
18986:         }
18987:     }
18988:     if ($env{'form.instcode'} eq '1') {
18989:         if (ref($cathash) eq 'HASH') {
18990:             my $newitem = 'instcode::0';
18991:             if ($cathash->{$newitem} eq '') {  
18992:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18993:                 $adds{$newitem} = 1;
18994:             }
18995:         } else {
18996:             my $newitem = 'instcode::0';
18997:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18998:             $adds{$newitem} = 1;
18999:         }
19000:     }
19001:     if ($env{'form.communities'} eq '1') {
19002:         if (ref($cathash) eq 'HASH') {
19003:             my $newitem = 'communities::0';
19004:             if ($cathash->{$newitem} eq '') {
19005:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
19006:                 $adds{$newitem} = 1;
19007:             }
19008:         } else {
19009:             my $newitem = 'communities::0';
19010:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
19011:             $adds{$newitem} = 1;
19012:         }
19013:     }
19014:     if ($env{'form.placement'} eq '1') {
19015:         if (ref($cathash) eq 'HASH') {
19016:             my $newitem = 'placement::0';
19017:             if ($cathash->{$newitem} eq '') {
19018:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
19019:                 $adds{$newitem} = 1;
19020:             }
19021:         } else {
19022:             my $newitem = 'placement::0';
19023:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
19024:             $adds{$newitem} = 1;
19025:         }
19026:     }
19027:     if ($env{'form.addcategory_name'} ne '') {
19028:         if (($env{'form.addcategory_name'} ne 'instcode') &&
19029:             ($env{'form.addcategory_name'} ne 'communities') &&
19030:             ($env{'form.addcategory_name'} ne 'placement')) {
19031:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
19032:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
19033:             $adds{$newitem} = 1;
19034:         }
19035:     }
19036:     my $putresult;
19037:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19038:         if (keys(%deletions) > 0) {
19039:             foreach my $key (keys(%deletions)) {
19040:                 if ($predelallitems{$key} ne '') {
19041:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
19042:                 }
19043:             }
19044:         }
19045:         my (@chkcats,@chktrails,%chkallitems);
19046:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
19047:         if (ref($chkcats[0]) eq 'ARRAY') {
19048:             my $depth = 0;
19049:             my $chg = 0;
19050:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
19051:                 my $name = $chkcats[0][$i];
19052:                 my $item;
19053:                 if ($name eq '') {
19054:                     $chg ++;
19055:                 } else {
19056:                     $item = &escape($name).'::0';
19057:                     if ($chg) {
19058:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
19059:                     }
19060:                     $depth ++; 
19061:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
19062:                     $depth --;
19063:                 }
19064:             }
19065:         }
19066:     }
19067:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19068:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
19069:         if ($putresult eq 'ok') {
19070:             my %title = (
19071:                          togglecats     => 'Show/Hide a course in catalog',
19072:                          categorize     => 'Assign a category to a course',
19073:                          togglecatscomm => 'Show/Hide a community in catalog',
19074:                          categorizecomm => 'Assign a category to a community',
19075:                         );
19076:             my %level = (
19077:                          dom  => 'set in Domain ("Modify Course/Community")',
19078:                          crs  => 'set in Course ("Course Configuration")',
19079:                          comm => 'set in Community ("Community Configuration")',
19080:                          none     => 'No catalog',
19081:                          std      => 'Standard catalog',
19082:                          domonly  => 'Domain-only catalog',
19083:                          codesrch => 'Code search form',
19084:                         );
19085:             $resulttext = &mt('Changes made:').'<ul>';
19086:             if ($changes{'togglecats'}) {
19087:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
19088:             }
19089:             if ($changes{'categorize'}) {
19090:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
19091:             }
19092:             if ($changes{'togglecatscomm'}) {
19093:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
19094:             }
19095:             if ($changes{'categorizecomm'}) {
19096:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
19097:             }
19098:             if ($changes{'unauth'}) {
19099:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
19100:             }
19101:             if ($changes{'auth'}) {
19102:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
19103:             }
19104:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
19105:                 my $cathash;
19106:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
19107:                     $cathash = $domconfig{'coursecategories'}{'cats'};
19108:                 } else {
19109:                     $cathash = {};
19110:                 } 
19111:                 my (@cats,@trails,%allitems);
19112:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
19113:                 if (keys(%deletions) > 0) {
19114:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
19115:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
19116:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
19117:                     }
19118:                     $resulttext .= '</ul></li>';
19119:                 }
19120:                 if (keys(%reorderings) > 0) {
19121:                     my %sort_by_trail;
19122:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
19123:                     foreach my $key (keys(%reorderings)) {
19124:                         if ($allitems{$key} ne '') {
19125:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
19126:                         }
19127:                     }
19128:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
19129:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
19130:                     }
19131:                     $resulttext .= '</ul></li>';
19132:                 }
19133:                 if (keys(%adds) > 0) {
19134:                     my %sort_by_trail;
19135:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
19136:                     foreach my $key (keys(%adds)) {
19137:                         if ($allitems{$key} ne '') {
19138:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
19139:                         }
19140:                     }
19141:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
19142:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
19143:                     }
19144:                     $resulttext .= '</ul></li>';
19145:                 }
19146:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
19147:                 if (ref($lastactref) eq 'HASH') {
19148:                     $lastactref->{'cats'} = 1;
19149:                 }
19150:             }
19151:             $resulttext .= '</ul>';
19152:             if ($changes{'unauth'} || $changes{'auth'}) {
19153:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
19154:                 if ($changes{'auth'}) {
19155:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
19156:                 }
19157:                 if ($changes{'unauth'}) {
19158:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
19159:                 }
19160:                 my $cachetime = 24*60*60;
19161:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19162:                 if (ref($lastactref) eq 'HASH') {
19163:                     $lastactref->{'domdefaults'} = 1;
19164:                 }
19165:             }
19166:         } else {
19167:             $resulttext = '<span class="LC_error">'.
19168:                           &mt('An error occurred: [_1]',$putresult).'</span>';
19169:         }
19170:     } else {
19171:         $resulttext = &mt('No changes made to course and community categories');
19172:     }
19173:     return $resulttext;
19174: }
19175: 
19176: sub modify_serverstatuses {
19177:     my ($dom,%domconfig) = @_;
19178:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
19179:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
19180:         %currserverstatus = %{$domconfig{'serverstatuses'}};
19181:     }
19182:     my @pages = &serverstatus_pages();
19183:     foreach my $type (@pages) {
19184:         $newserverstatus{$type}{'namedusers'} = '';
19185:         $newserverstatus{$type}{'machines'} = '';
19186:         if (defined($env{'form.'.$type.'_namedusers'})) {
19187:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
19188:             my @okusers;
19189:             foreach my $user (@users) {
19190:                 my ($uname,$udom) = split(/:/,$user);
19191:                 if (($udom =~ /^$match_domain$/) &&   
19192:                     (&Apache::lonnet::domain($udom)) &&
19193:                     ($uname =~ /^$match_username$/)) {
19194:                     if (!grep(/^\Q$user\E/,@okusers)) {
19195:                         push(@okusers,$user);
19196:                     }
19197:                 }
19198:             }
19199:             if (@okusers > 0) {
19200:                  @okusers = sort(@okusers);
19201:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
19202:             }
19203:         }
19204:         if (defined($env{'form.'.$type.'_machines'})) {
19205:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
19206:             my @okmachines;
19207:             foreach my $ip (@machines) {
19208:                 my @parts = split(/\./,$ip);
19209:                 next if (@parts < 4);
19210:                 my $badip = 0;
19211:                 for (my $i=0; $i<4; $i++) {
19212:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
19213:                         $badip = 1;
19214:                         last;
19215:                     }
19216:                 }
19217:                 if (!$badip) {
19218:                     push(@okmachines,$ip);     
19219:                 }
19220:             }
19221:             @okmachines = sort(@okmachines);
19222:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
19223:         }
19224:     }
19225:     my %serverstatushash =  (
19226:                                 serverstatuses => \%newserverstatus,
19227:                             );
19228:     foreach my $type (@pages) {
19229:         foreach my $setting ('namedusers','machines') {
19230:             my (@current,@new);
19231:             if (ref($currserverstatus{$type}) eq 'HASH') {
19232:                 if ($currserverstatus{$type}{$setting} ne '') { 
19233:                     @current = split(/,/,$currserverstatus{$type}{$setting});
19234:                 }
19235:             }
19236:             if ($newserverstatus{$type}{$setting} ne '') {
19237:                 @new = split(/,/,$newserverstatus{$type}{$setting});
19238:             }
19239:             if (@current > 0) {
19240:                 if (@new > 0) {
19241:                     foreach my $item (@current) {
19242:                         if (!grep(/^\Q$item\E$/,@new)) {
19243:                             $changes{$type}{$setting} = 1;
19244:                             last;
19245:                         }
19246:                     }
19247:                     foreach my $item (@new) {
19248:                         if (!grep(/^\Q$item\E$/,@current)) {
19249:                             $changes{$type}{$setting} = 1;
19250:                             last;
19251:                         }
19252:                     }
19253:                 } else {
19254:                     $changes{$type}{$setting} = 1;
19255:                 }
19256:             } elsif (@new > 0) {
19257:                 $changes{$type}{$setting} = 1;
19258:             }
19259:         }
19260:     }
19261:     if (keys(%changes) > 0) {
19262:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
19263:         my $putresult = &Apache::lonnet::put_dom('configuration',
19264:                                                  \%serverstatushash,$dom);
19265:         if ($putresult eq 'ok') {
19266:             $resulttext .= &mt('Changes made:').'<ul>';
19267:             foreach my $type (@pages) {
19268:                 if (ref($changes{$type}) eq 'HASH') {
19269:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
19270:                     if ($changes{$type}{'namedusers'}) {
19271:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
19272:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
19273:                         } else {
19274:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
19275:                         }
19276:                     }
19277:                     if ($changes{$type}{'machines'}) {
19278:                         if ($newserverstatus{$type}{'machines'} eq '') {
19279:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
19280:                         } else {
19281:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
19282:                         }
19283: 
19284:                     }
19285:                     $resulttext .= '</ul></li>';
19286:                 }
19287:             }
19288:             $resulttext .= '</ul>';
19289:         } else {
19290:             $resulttext = '<span class="LC_error">'.
19291:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
19292: 
19293:         }
19294:     } else {
19295:         $resulttext = &mt('No changes made to access to server status pages');
19296:     }
19297:     return $resulttext;
19298: }
19299: 
19300: sub modify_helpsettings {
19301:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
19302:     my ($resulttext,$errors,%changes,%helphash);
19303:     my %defaultchecked = ('submitbugs' => 'on');
19304:     my @offon = ('off','on');
19305:     my @toggles = ('submitbugs');
19306:     my %current = ('submitbugs' => '',
19307:                    'adhoc'      => {},
19308:                   );
19309:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
19310:         %current = %{$domconfig{'helpsettings'}};
19311:     }
19312:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19313:     foreach my $item (@toggles) {
19314:         if ($defaultchecked{$item} eq 'on') { 
19315:             if ($current{$item} eq '') {
19316:                 if ($env{'form.'.$item} eq '0') {
19317:                     $changes{$item} = 1;
19318:                 }
19319:             } elsif ($current{$item} ne $env{'form.'.$item}) {
19320:                 $changes{$item} = 1;
19321:             }
19322:         } elsif ($defaultchecked{$item} eq 'off') {
19323:             if ($current{$item} eq '') {
19324:                 if ($env{'form.'.$item} eq '1') {
19325:                     $changes{$item} = 1;
19326:                 }
19327:             } elsif ($current{$item} ne $env{'form.'.$item}) {
19328:                 $changes{$item} = 1;
19329:             }
19330:         }
19331:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
19332:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
19333:         }
19334:     }
19335:     my $maxnum = $env{'form.helproles_maxnum'};
19336:     my $confname = $dom.'-domainconfig';
19337:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
19338:     my (@allpos,%newsettings,%changedprivs,$newrole);
19339:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
19340:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
19341:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
19342:     my %lt = &Apache::lonlocal::texthash(
19343:                     s      => 'system',
19344:                     d      => 'domain',
19345:                     order  => 'Display order',
19346:                     access => 'Role usage',
19347:                     all    => 'All with domain helpdesk or helpdesk assistant role',
19348:                     dh     => 'All with domain helpdesk role',
19349:                     da     => 'All with domain helpdesk assistant role',
19350:                     none   => 'None',
19351:                     status => 'Determined based on institutional status',
19352:                     inc    => 'Include all, but exclude specific personnel',
19353:                     exc    => 'Exclude all, but include specific personnel',
19354:     );
19355:     for (my $num=0; $num<=$maxnum; $num++) {
19356:         my ($prefix,$identifier,$rolename,%curr);
19357:         if ($num == $maxnum) {
19358:             next unless ($env{'form.newcusthelp'} == $maxnum);
19359:             $identifier = 'custhelp'.$num;
19360:             $prefix = 'helproles_'.$num;
19361:             $rolename = $env{'form.custhelpname'.$num};
19362:             $rolename=~s/[^A-Za-z0-9]//gs;
19363:             next if ($rolename eq '');
19364:             next if (exists($existing{'rolesdef_'.$rolename}));
19365:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
19366:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
19367:                                                      $newprivs{'c'},$confname,$dom);
19368:             if ($result ne 'ok') {
19369:                 $errors .= '<li><span class="LC_error">'.
19370:                            &mt('An error occurred storing the new custom role: [_1]',
19371:                            $result).'</span></li>';
19372:                 next;
19373:             } else {
19374:                 $changedprivs{$rolename} = \%newprivs;
19375:                 $newrole = $rolename;
19376:             }
19377:         } else {
19378:             $prefix = 'helproles_'.$num;
19379:             $rolename = $env{'form.'.$prefix};
19380:             next if ($rolename eq '');
19381:             next unless (exists($existing{'rolesdef_'.$rolename}));
19382:             $identifier = 'custhelp'.$num;
19383:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
19384:             my %currprivs;
19385:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
19386:                 split(/\_/,$existing{'rolesdef_'.$rolename});
19387:             foreach my $level ('c','d','s') {
19388:                 if ($newprivs{$level} ne $currprivs{$level}) {
19389:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
19390:                                                              $newprivs{'c'},$confname,$dom);
19391:                     if ($result ne 'ok') {
19392:                         $errors .= '<li><span class="LC_error">'.
19393:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
19394:                                        $rolename,$result).'</span></li>';
19395:                     } else {
19396:                         $changedprivs{$rolename} = \%newprivs;
19397:                     }
19398:                     last;
19399:                 }
19400:             }
19401:             if (ref($current{'adhoc'}) eq 'HASH') {
19402:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
19403:                     %curr = %{$current{'adhoc'}{$rolename}};
19404:                 }
19405:             }
19406:         }
19407:         my $newpos = $env{'form.'.$prefix.'_pos'};
19408:         $newpos =~ s/\D+//g;
19409:         $allpos[$newpos] = $rolename;
19410:         my $newdesc = $env{'form.'.$prefix.'_desc'};
19411:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
19412:         if ($curr{'desc'}) {
19413:             if ($curr{'desc'} ne $newdesc) {
19414:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
19415:                 $newsettings{$rolename}{'desc'} = $newdesc;
19416:             }
19417:         } elsif ($newdesc ne '') {
19418:             $changes{'customrole'}{$rolename}{'desc'} = 1;
19419:             $newsettings{$rolename}{'desc'} = $newdesc;
19420:         }
19421:         my $access = $env{'form.'.$prefix.'_access'};
19422:         if (grep(/^\Q$access\E$/,@accesstypes)) {
19423:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
19424:             if ($access eq 'status') {
19425:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
19426:                 if (scalar(@statuses) == 0) {
19427:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
19428:                 } else {
19429:                     my (@shownstatus,$numtypes);
19430:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
19431:                     if (ref($types) eq 'ARRAY') {
19432:                         $numtypes = scalar(@{$types});
19433:                         foreach my $type (sort(@statuses)) {
19434:                             if ($type eq 'default') {
19435:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
19436:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
19437:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
19438:                                 push(@shownstatus,$usertypes->{$type});
19439:                             }
19440:                         }
19441:                     }
19442:                     if (grep(/^default$/,@statuses)) {
19443:                         push(@shownstatus,$othertitle);
19444:                     }
19445:                     if (scalar(@shownstatus) == 1+$numtypes) {
19446:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
19447:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
19448:                     } else {
19449:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
19450:                         if (ref($curr{'status'}) eq 'ARRAY') {
19451:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
19452:                             if (@diffs) {
19453:                                 $changes{'customrole'}{$rolename}{$access} = 1;
19454:                             }
19455:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19456:                             $changes{'customrole'}{$rolename}{$access} = 1;
19457:                         }
19458:                     }
19459:                 }
19460:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
19461:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
19462:                 my @newspecstaff;
19463:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
19464:                 foreach my $person (sort(@personnel)) {
19465:                     if ($domhelpdesk{$person}) {
19466:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
19467:                     }
19468:                 }
19469:                 if (ref($curr{$access}) eq 'ARRAY') {
19470:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
19471:                     if (@diffs) {
19472:                         $changes{'customrole'}{$rolename}{$access} = 1;
19473:                     }
19474:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19475:                     $changes{'customrole'}{$rolename}{$access} = 1;
19476:                 }
19477:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19478:                     my ($uname,$udom) = split(/:/,$person);
19479:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
19480:                 }
19481:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
19482:             }
19483:         } else {
19484:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
19485:         }
19486:         unless ($curr{'access'} eq $access) {
19487:             $changes{'customrole'}{$rolename}{'access'} = 1;
19488:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
19489:         }
19490:     }
19491:     if (@allpos > 0) {
19492:         my $idx = 0;
19493:         foreach my $rolename (@allpos) {
19494:             if ($rolename ne '') {
19495:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
19496:                 if (ref($current{'adhoc'}) eq 'HASH') {
19497:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
19498:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
19499:                             $changes{'customrole'}{$rolename}{'order'} = 1;
19500:                             $newsettings{$rolename}{'order'} = $idx+1;
19501:                         }
19502:                     }
19503:                 }
19504:                 $idx ++;
19505:             }
19506:         }
19507:     }
19508:     my $putresult;
19509:     if (keys(%changes) > 0) {
19510:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
19511:         if ($putresult eq 'ok') {
19512:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
19513:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
19514:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
19515:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
19516:                 }
19517:             }
19518:             my $cachetime = 24*60*60;
19519:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19520:             if (ref($lastactref) eq 'HASH') {
19521:                 $lastactref->{'domdefaults'} = 1;
19522:             }
19523:         } else {
19524:             $errors .= '<li><span class="LC_error">'.
19525:                        &mt('An error occurred storing the settings: [_1]',
19526:                            $putresult).'</span></li>';
19527:         }
19528:     }
19529:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
19530:         $resulttext = &mt('Changes made:').'<ul>';
19531:         my (%shownprivs,@levelorder);
19532:         @levelorder = ('c','d','s');
19533:         if ((keys(%changes)) && ($putresult eq 'ok')) {
19534:             foreach my $item (sort(keys(%changes))) {
19535:                 if ($item eq 'submitbugs') {
19536:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
19537:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
19538:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
19539:                 } elsif ($item eq 'customrole') {
19540:                     if (ref($changes{'customrole'}) eq 'HASH') {
19541:                         my @keyorder = ('order','desc','access','status','exc','inc');
19542:                         my %keytext = &Apache::lonlocal::texthash(
19543:                                                                    order  => 'Order',
19544:                                                                    desc   => 'Role description',
19545:                                                                    access => 'Role usage',
19546:                                                                    status => 'Allowed institutional types',
19547:                                                                    exc    => 'Allowed personnel',
19548:                                                                    inc    => 'Disallowed personnel',
19549:                         );
19550:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
19551:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
19552:                                 if ($role eq $newrole) {
19553:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
19554:                                                               $role).'<ul>';
19555:                                 } else {
19556:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19557:                                                               $role).'<ul>';
19558:                                 }
19559:                                 foreach my $key (@keyorder) {
19560:                                     if ($changes{'customrole'}{$role}{$key}) {
19561:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
19562:                                                                   $keytext{$key},$newsettings{$role}{$key}).
19563:                                                        '</li>';
19564:                                     }
19565:                                 }
19566:                                 if (ref($changedprivs{$role}) eq 'HASH') {
19567:                                     $shownprivs{$role} = 1;
19568:                                     $resulttext .= '<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>';
19583:                                 }
19584:                                 $resulttext .= '</ul></li>';
19585:                             }
19586:                         }
19587:                     }
19588:                 }
19589:             }
19590:         }
19591:         if (keys(%changedprivs)) {
19592:             foreach my $role (sort(keys(%changedprivs))) {
19593:                 unless ($shownprivs{$role}) {
19594:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19595:                                               $role).'<ul>'.
19596:                                    '<li>'.&mt('Privileges set to :').'<ul>';
19597:                     foreach my $level (@levelorder) {
19598:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
19599:                             next if ($item eq '');
19600:                             my ($priv) = split(/\&/,$item,2);
19601:                             if (&Apache::lonnet::plaintext($priv)) {
19602:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
19603:                                 unless ($level eq 'c') {
19604:                                     $resulttext .= ' ('.$lt{$level}.')';
19605:                                 }
19606:                                 $resulttext .= '</li>';
19607:                             }
19608:                         }
19609:                     }
19610:                     $resulttext .= '</ul></li></ul></li>';
19611:                 }
19612:             }
19613:         }
19614:         $resulttext .= '</ul>';
19615:     } else {
19616:         $resulttext = &mt('No changes made to help settings');
19617:     }
19618:     if ($errors) {
19619:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
19620:                                     $errors.'</ul>';
19621:     }
19622:     return $resulttext;
19623: }
19624: 
19625: sub modify_coursedefaults {
19626:     my ($dom,$lastactref,%domconfig) = @_;
19627:     my ($resulttext,$errors,%changes,%defaultshash);
19628:     my %defaultchecked = (
19629:                            'canuse_pdfforms' => 'off',
19630:                            'uselcmath'       => 'on',
19631:                            'usejsme'         => 'on'
19632:                          );
19633:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme');
19634:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
19635:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
19636:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
19637:                    'mysqltables_textbook','mysqltables_placement');
19638:     my @types = ('official','unofficial','community','textbook','placement');
19639:     my %staticdefaults = (
19640:                            anonsurvey_threshold => 10,
19641:                            uploadquota          => 500,
19642:                            postsubmit           => 60,
19643:                            mysqltables          => 172800,
19644:                          );
19645:     my %texoptions = (
19646:                         MathJax  => 'MathJax',
19647:                         mimetex  => &mt('Convert to Images'),
19648:                         tth      => &mt('TeX to HTML'),
19649:                      );
19650:     $defaultshash{'coursedefaults'} = {};
19651: 
19652:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
19653:         if ($domconfig{'coursedefaults'} eq '') {
19654:             $domconfig{'coursedefaults'} = {};
19655:         }
19656:     }
19657: 
19658:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
19659:         foreach my $item (@toggles) {
19660:             if ($defaultchecked{$item} eq 'on') {
19661:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19662:                     ($env{'form.'.$item} eq '0')) {
19663:                     $changes{$item} = 1;
19664:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19665:                     $changes{$item} = 1;
19666:                 }
19667:             } elsif ($defaultchecked{$item} eq 'off') {
19668:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19669:                     ($env{'form.'.$item} eq '1')) {
19670:                     $changes{$item} = 1;
19671:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19672:                     $changes{$item} = 1;
19673:                 }
19674:             }
19675:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
19676:         }
19677:         foreach my $item (@numbers) {
19678:             my ($currdef,$newdef);
19679:             $newdef = $env{'form.'.$item};
19680:             if ($item eq 'anonsurvey_threshold') {
19681:                 $currdef = $domconfig{'coursedefaults'}{$item};
19682:                 $newdef =~ s/\D//g;
19683:                 if ($newdef eq '' || $newdef < 1) {
19684:                     $newdef = 1;
19685:                 }
19686:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
19687:             } else {
19688:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
19689:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
19690:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
19691:                 }
19692:                 $newdef =~ s/[^\w.\-]//g;
19693:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
19694:             }
19695:             if ($currdef ne $newdef) {
19696:                 if ($item eq 'anonsurvey_threshold') {
19697:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
19698:                         $changes{$item} = 1;
19699:                     }
19700:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
19701:                     my $setting = $1;
19702:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
19703:                         $changes{$setting} = 1;
19704:                     }
19705:                 }
19706:             }
19707:         }
19708:         my $texengine;
19709:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
19710:             $texengine = $env{'form.texengine'};
19711:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
19712:             if ($currdef eq '') {
19713:                 unless ($texengine eq $Apache::lonnet::deftex) {
19714:                     $changes{'texengine'} = 1;
19715:                 }
19716:             } elsif ($currdef ne $texengine) {
19717:                 $changes{'texengine'} = 1;
19718:             }
19719:         }
19720:         if ($texengine ne '') {
19721:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
19722:         }
19723:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
19724:         my @currclonecode;
19725:         if (ref($currclone) eq 'HASH') {
19726:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
19727:                 @currclonecode = @{$currclone->{'instcode'}};
19728:             }
19729:         }
19730:         my $newclone;
19731:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
19732:             $newclone = $env{'form.canclone'};
19733:         }
19734:         if ($newclone eq 'instcode') {
19735:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
19736:             my (%codedefaults,@code_order,@clonecode);
19737:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
19738:                                                     \@code_order);
19739:             foreach my $item (@code_order) {
19740:                 if (grep(/^\Q$item\E$/,@newcodes)) {
19741:                     push(@clonecode,$item);
19742:                 }
19743:             }
19744:             if (@clonecode) {
19745:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
19746:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
19747:                 if (@diffs) {
19748:                     $changes{'canclone'} = 1;
19749:                 }
19750:             } else {
19751:                 $newclone eq '';
19752:             }
19753:         } elsif ($newclone ne '') {
19754:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
19755:         }
19756:         if ($newclone ne $currclone) {
19757:             $changes{'canclone'} = 1;
19758:         }
19759:         my %credits;
19760:         foreach my $type (@types) {
19761:             unless ($type eq 'community') {
19762:                 $credits{$type} = $env{'form.'.$type.'_credits'};
19763:                 $credits{$type} =~ s/[^\d.]+//g;
19764:             }
19765:         }
19766:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
19767:             ($env{'form.coursecredits'} eq '1')) {
19768:             $changes{'coursecredits'} = 1;
19769:             foreach my $type (keys(%credits)) {
19770:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19771:             }
19772:         } else {
19773:             if ($env{'form.coursecredits'} eq '1') {
19774:                 foreach my $type (@types) {
19775:                     unless ($type eq 'community') {
19776:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
19777:                             $changes{'coursecredits'} = 1;
19778:                         }
19779:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19780:                     }
19781:                 }
19782:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19783:                 foreach my $type (@types) {
19784:                     unless ($type eq 'community') {
19785:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
19786:                             $changes{'coursecredits'} = 1;
19787:                             last;
19788:                         }
19789:                     }
19790:                 }
19791:             }
19792:         }
19793:         if ($env{'form.postsubmit'} eq '1') {
19794:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
19795:             my %currtimeout;
19796:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19797:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
19798:                     $changes{'postsubmit'} = 1;
19799:                 }
19800:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19801:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
19802:                 }
19803:             } else {
19804:                 $changes{'postsubmit'} = 1;
19805:             }
19806:             foreach my $type (@types) {
19807:                 my $timeout = $env{'form.'.$type.'_timeout'};
19808:                 $timeout =~ s/\D//g;
19809:                 if ($timeout == $staticdefaults{'postsubmit'}) {
19810:                     $timeout = '';
19811:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
19812:                     $timeout = '0';
19813:                 }
19814:                 unless ($timeout eq '') {
19815:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
19816:                 }
19817:                 if (exists($currtimeout{$type})) {
19818:                     if ($timeout ne $currtimeout{$type}) {
19819:                         $changes{'postsubmit'} = 1;
19820:                     }
19821:                 } elsif ($timeout ne '') {
19822:                     $changes{'postsubmit'} = 1;
19823:                 }
19824:             }
19825:         } else {
19826:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
19827:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19828:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
19829:                     $changes{'postsubmit'} = 1;
19830:                 }
19831:             } else {
19832:                 $changes{'postsubmit'} = 1;
19833:             }
19834:         }
19835:     }
19836:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19837:                                              $dom);
19838:     if ($putresult eq 'ok') {
19839:         if (keys(%changes) > 0) {
19840:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19841:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
19842:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
19843:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
19844:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','texengine') {
19845:                     if ($changes{$item}) {
19846:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
19847:                     }
19848:                 }
19849:                 if ($changes{'coursecredits'}) {
19850:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19851:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
19852:                             $domdefaults{$type.'credits'} =
19853:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
19854:                         }
19855:                     }
19856:                 }
19857:                 if ($changes{'postsubmit'}) {
19858:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19859:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
19860:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19861:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
19862:                                 $domdefaults{$type.'postsubtimeout'} =
19863:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19864:                             }
19865:                         }
19866:                     }
19867:                 }
19868:                 if ($changes{'uploadquota'}) {
19869:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19870:                         foreach my $type (@types) {
19871:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
19872:                         }
19873:                     }
19874:                 }
19875:                 if ($changes{'canclone'}) {
19876:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
19877:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
19878:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
19879:                             if (@clonecodes) {
19880:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
19881:                             }
19882:                         }
19883:                     } else {
19884:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
19885:                     }
19886:                 }
19887:                 my $cachetime = 24*60*60;
19888:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19889:                 if (ref($lastactref) eq 'HASH') {
19890:                     $lastactref->{'domdefaults'} = 1;
19891:                 }
19892:             }
19893:             $resulttext = &mt('Changes made:').'<ul>';
19894:             foreach my $item (sort(keys(%changes))) {
19895:                 if ($item eq 'canuse_pdfforms') {
19896:                     if ($env{'form.'.$item} eq '1') {
19897:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
19898:                     } else {
19899:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
19900:                     }
19901:                 } elsif ($item eq 'uselcmath') {
19902:                     if ($env{'form.'.$item} eq '1') {
19903:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
19904:                     } else {
19905:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
19906:                     }
19907:                 } elsif ($item eq 'usejsme') {
19908:                     if ($env{'form.'.$item} eq '1') {
19909:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
19910:                     } else {
19911:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
19912:                     }
19913:                 } elsif ($item eq 'texengine') {
19914:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
19915:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
19916:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
19917:                     }
19918:                 } elsif ($item eq 'anonsurvey_threshold') {
19919:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
19920:                 } elsif ($item eq 'uploadquota') {
19921:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19922:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
19923:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
19924:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
19925:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
19926:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
19927:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
19928:                                        '</ul>'.
19929:                                        '</li>';
19930:                     } else {
19931:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
19932:                     }
19933:                 } elsif ($item eq 'mysqltables') {
19934:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
19935:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
19936:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
19937:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
19938:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
19939:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
19940:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
19941:                                        '</ul>'.
19942:                                        '</li>';
19943:                     } else {
19944:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
19945:                     }
19946:                 } elsif ($item eq 'postsubmit') {
19947:                     if ($domdefaults{'postsubmit'} eq 'off') {
19948:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
19949:                     } else {
19950:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
19951:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19952:                             $resulttext .= &mt('durations:').'<ul>';
19953:                             foreach my $type (@types) {
19954:                                 $resulttext .= '<li>';
19955:                                 my $timeout;
19956:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19957:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19958:                                 }
19959:                                 my $display;
19960:                                 if ($timeout eq '0') {
19961:                                     $display = &mt('unlimited');
19962:                                 } elsif ($timeout eq '') {
19963:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
19964:                                 } else {
19965:                                     $display = &mt('[quant,_1,second]',$timeout);
19966:                                 }
19967:                                 if ($type eq 'community') {
19968:                                     $resulttext .= &mt('Communities');
19969:                                 } elsif ($type eq 'official') {
19970:                                     $resulttext .= &mt('Official courses');
19971:                                 } elsif ($type eq 'unofficial') {
19972:                                     $resulttext .= &mt('Unofficial courses');
19973:                                 } elsif ($type eq 'textbook') {
19974:                                     $resulttext .= &mt('Textbook courses');
19975:                                 } elsif ($type eq 'placement') {
19976:                                     $resulttext .= &mt('Placement tests');
19977:                                 }
19978:                                 $resulttext .= ' -- '.$display.'</li>';
19979:                             }
19980:                             $resulttext .= '</ul>';
19981:                         }
19982:                         $resulttext .= '</li>';
19983:                     }
19984:                 } elsif ($item eq 'coursecredits') {
19985:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19986:                         if (($domdefaults{'officialcredits'} eq '') &&
19987:                             ($domdefaults{'unofficialcredits'} eq '') &&
19988:                             ($domdefaults{'textbookcredits'} eq '')) {
19989:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
19990:                         } else {
19991:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
19992:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
19993:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
19994:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
19995:                                            '</ul>'.
19996:                                            '</li>';
19997:                         }
19998:                     } else {
19999:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
20000:                     }
20001:                 } elsif ($item eq 'canclone') {
20002:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
20003:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
20004:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
20005:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
20006:                         }
20007:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
20008:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
20009:                     } else {
20010:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
20011:                     }
20012:                 }
20013:             }
20014:             $resulttext .= '</ul>';
20015:         } else {
20016:             $resulttext = &mt('No changes made to course defaults');
20017:         }
20018:     } else {
20019:         $resulttext = '<span class="LC_error">'.
20020:             &mt('An error occurred: [_1]',$putresult).'</span>';
20021:     }
20022:     return $resulttext;
20023: }
20024: 
20025: sub modify_selfenrollment {
20026:     my ($dom,$lastactref,%domconfig) = @_;
20027:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
20028:     my @types = ('official','unofficial','community','textbook','placement');
20029:     my %titles = &tool_titles();
20030:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
20031:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
20032:     $ordered{'default'} = ['types','registered','approval','limit'];
20033: 
20034:     my (%roles,%shown,%toplevel);
20035:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
20036: 
20037:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
20038:         if ($domconfig{'selfenrollment'} eq '') {
20039:             $domconfig{'selfenrollment'} = {};
20040:         }
20041:     }
20042:     %toplevel = (
20043:                   admin      => 'Configuration Rights',
20044:                   default    => 'Default settings',
20045:                   validation => 'Validation of self-enrollment requests',
20046:                 );
20047:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
20048: 
20049:     if (ref($ordered{'admin'}) eq 'ARRAY') {
20050:         foreach my $item (@{$ordered{'admin'}}) {
20051:             foreach my $type (@types) {
20052:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
20053:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
20054:                 } else {
20055:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
20056:                 }
20057:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
20058:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
20059:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
20060:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
20061:                             push(@{$changes{'admin'}{$type}},$item);
20062:                         }
20063:                     } else {
20064:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
20065:                             push(@{$changes{'admin'}{$type}},$item);
20066:                         }
20067:                     }
20068:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
20069:                     push(@{$changes{'admin'}{$type}},$item);
20070:                 }
20071:             }
20072:         }
20073:     }
20074: 
20075:     foreach my $item (@{$ordered{'default'}}) {
20076:         foreach my $type (@types) {
20077:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
20078:             if ($item eq 'types') {
20079:                 unless (($value eq 'all') || ($value eq 'dom')) {
20080:                     $value = '';
20081:                 }
20082:             } elsif ($item eq 'registered') {
20083:                 unless ($value eq '1') {
20084:                     $value = 0;
20085:                 }
20086:             } elsif ($item eq 'approval') {
20087:                 unless ($value =~ /^[012]$/) {
20088:                     $value = 0;
20089:                 }
20090:             } else {
20091:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
20092:                     $value = 'none';
20093:                 }
20094:             }
20095:             $selfenrollhash{'default'}{$type}{$item} = $value;
20096:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
20097:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
20098:                     if ($selfenrollhash{'default'}{$type}{$item} ne
20099:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
20100:                          push(@{$changes{'default'}{$type}},$item);
20101:                     }
20102:                 } else {
20103:                     push(@{$changes{'default'}{$type}},$item);
20104:                 }
20105:             } else {
20106:                 push(@{$changes{'default'}{$type}},$item);
20107:             }
20108:             if ($item eq 'limit') {
20109:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
20110:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
20111:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
20112:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
20113:                     }
20114:                 } else {
20115:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
20116:                 }
20117:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
20118:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
20119:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
20120:                          push(@{$changes{'default'}{$type}},'cap');
20121:                     }
20122:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
20123:                     push(@{$changes{'default'}{$type}},'cap');
20124:                 }
20125:             }
20126:         }
20127:     }
20128: 
20129:     foreach my $item (@{$itemsref}) {
20130:         if ($item eq 'fields') {
20131:             my @changed;
20132:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
20133:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
20134:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
20135:             }
20136:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
20137:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
20138:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
20139:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
20140:                 } else {
20141:                     @changed = @{$selfenrollhash{'validation'}{$item}};
20142:                 }
20143:             } else {
20144:                 @changed = @{$selfenrollhash{'validation'}{$item}};
20145:             }
20146:             if (@changed) {
20147:                 if ($selfenrollhash{'validation'}{$item}) { 
20148:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
20149:                 } else {
20150:                     $changes{'validation'}{$item} = &mt('None');
20151:                 }
20152:             }
20153:         } else {
20154:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
20155:             if ($item eq 'markup') {
20156:                if ($env{'form.selfenroll_validation_'.$item}) {
20157:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
20158:                }
20159:             }
20160:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
20161:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
20162:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
20163:                 }
20164:             }
20165:         }
20166:     }
20167: 
20168:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
20169:                                              $dom);
20170:     if ($putresult eq 'ok') {
20171:         if (keys(%changes) > 0) {
20172:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20173:             $resulttext = &mt('Changes made:').'<ul>';
20174:             foreach my $key ('admin','default','validation') {
20175:                 if (ref($changes{$key}) eq 'HASH') {
20176:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
20177:                     if ($key eq 'validation') {
20178:                         foreach my $item (@{$itemsref}) {
20179:                             if (exists($changes{$key}{$item})) {
20180:                                 if ($item eq 'markup') {
20181:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
20182:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
20183:                                 } else {  
20184:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
20185:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
20186:                                 }
20187:                             }
20188:                         }
20189:                     } else {
20190:                         foreach my $type (@types) {
20191:                             if ($type eq 'community') {
20192:                                 $roles{'1'} = &mt('Community personnel');
20193:                             } else {
20194:                                 $roles{'1'} = &mt('Course personnel');
20195:                             }
20196:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
20197:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
20198:                                     if ($key eq 'admin') {
20199:                                         my @mgrdc = ();
20200:                                         if (ref($ordered{$key}) eq 'ARRAY') {
20201:                                             foreach my $item (@{$ordered{'admin'}}) {
20202:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
20203:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
20204:                                                         push(@mgrdc,$item);
20205:                                                     }
20206:                                                 }
20207:                                             }
20208:                                             if (@mgrdc) {
20209:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
20210:                                             } else {
20211:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
20212:                                             }
20213:                                         }
20214:                                     } else {
20215:                                         if (ref($ordered{$key}) eq 'ARRAY') {
20216:                                             foreach my $item (@{$ordered{$key}}) {
20217:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
20218:                                                     $domdefaults{$type.'selfenroll'.$item} =
20219:                                                         $selfenrollhash{$key}{$type}{$item};
20220:                                                 }
20221:                                             }
20222:                                         }
20223:                                     }
20224:                                 }
20225:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
20226:                                 foreach my $item (@{$ordered{$key}}) {
20227:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
20228:                                         $resulttext .= '<li>';
20229:                                         if ($key eq 'admin') {
20230:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
20231:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
20232:                                         } else {
20233:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
20234:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
20235:                                         }
20236:                                         $resulttext .= '</li>';
20237:                                     }
20238:                                 }
20239:                                 $resulttext .= '</ul></li>';
20240:                             }
20241:                         }
20242:                         $resulttext .= '</ul></li>'; 
20243:                     }
20244:                 }
20245:             }
20246:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
20247:                 my $cachetime = 24*60*60;
20248:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20249:                 if (ref($lastactref) eq 'HASH') {
20250:                     $lastactref->{'domdefaults'} = 1;
20251:                 }
20252:             }
20253:             $resulttext .= '</ul>';
20254:         } else {
20255:             $resulttext = &mt('No changes made to self-enrollment settings');
20256:         }
20257:     } else {
20258:         $resulttext = '<span class="LC_error">'.
20259:             &mt('An error occurred: [_1]',$putresult).'</span>';
20260:     }
20261:     return $resulttext;
20262: }
20263: 
20264: sub modify_wafproxy {
20265:     my ($dom,$action,$lastactref,%domconfig) = @_;
20266:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20267:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
20268:         %wafproxy,%changes,%expirecache,%expiresaml);
20269:     foreach my $server (sort(keys(%servers))) {
20270:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
20271:         if ($serverhome eq $server) {
20272:             my $serverdom = &Apache::lonnet::host_domain($server);
20273:             if ($serverdom eq $dom) {
20274:                 $canset{$server} = 1;
20275:             }
20276:         }
20277:     }
20278:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
20279:         %{$values{$dom}} = ();
20280:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
20281:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
20282:         }
20283:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
20284:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
20285:         }
20286:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
20287:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
20288:         }
20289:     }
20290:     my $output;
20291:     if (keys(%canset)) {
20292:         %{$wafproxy{'alias'}} = ();
20293:         %{$wafproxy{'saml'}} = ();
20294:         foreach my $key (sort(keys(%canset))) {
20295:             if ($env{'form.wafproxy_'.$dom}) {
20296:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
20297:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
20298:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
20299:                     $changes{'alias'} = 1;
20300:                 }
20301:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
20302:                     $wafproxy{'saml'}{$key} = 1;
20303:                 }
20304:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
20305:                     $changes{'saml'} = 1;
20306:                 }
20307:             } else {
20308:                 $wafproxy{'alias'}{$key} = '';
20309:                 $wafproxy{'saml'}{$key} = '';
20310:                 if ($curralias{$key}) {
20311:                     $changes{'alias'} = 1;
20312:                 }
20313:                 if ($currsaml{$key}) {
20314:                     $changes{'saml'} = 1;
20315:                 }
20316:             }
20317:             if ($wafproxy{'alias'}{$key} eq '') {
20318:                 if ($curralias{$key}) {
20319:                     $expirecache{$key} = 1;
20320:                 }
20321:                 delete($wafproxy{'alias'}{$key});
20322:             }
20323:             if ($wafproxy{'saml'}{$key} eq '') {
20324:                 if ($currsaml{$key}) {
20325:                     $expiresaml{$key} = 1;
20326:                 }
20327:                 delete($wafproxy{'saml'}{$key});
20328:             }
20329:         }
20330:         unless (keys(%{$wafproxy{'alias'}})) {
20331:             delete($wafproxy{'alias'});
20332:         }
20333:         unless (keys(%{$wafproxy{'saml'}})) {
20334:             delete($wafproxy{'saml'});
20335:         }
20336:         # Localization for values in %warn occurs in &mt() calls separately.
20337:         my %warn = (
20338:                      trusted => 'trusted IP range(s)',
20339:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
20340:                      vpnext => 'IP range(s) for backend WAF connections',
20341:                    );
20342:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
20343:             my $possible = $env{'form.wafproxy_'.$item};
20344:             $possible =~ s/^\s+|\s+$//g;
20345:             if ($possible ne '') {
20346:                 if ($item eq 'remoteip') {
20347:                     if ($possible =~ /^[mhn]$/) {
20348:                         $wafproxy{$item} = $possible;
20349:                     }
20350:                 } elsif ($item eq 'ipheader') {
20351:                     if ($wafproxy{'remoteip'} eq 'h') {
20352:                         $wafproxy{$item} = $possible;
20353:                     }
20354:                 } elsif ($item eq 'sslopt') {
20355:                     if ($possible =~ /^0|1$/) {
20356:                         $wafproxy{$item} = $possible;
20357:                     }
20358:                 } else {
20359:                     my (@ok,$count);
20360:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
20361:                         unless ($env{'form.wafproxy_vpnaccess'}) {
20362:                             $possible = '';
20363:                         }
20364:                     } elsif ($item eq 'trusted') {
20365:                         unless ($wafproxy{'remoteip'} eq 'h') {
20366:                             $possible = '';
20367:                         }
20368:                     }
20369:                     unless ($possible eq '') {
20370:                         $possible =~ s/[\r\n]+/\s/g;
20371:                         $possible =~ s/\s*-\s*/-/g;
20372:                         $possible =~ s/\s+/,/g;
20373:                     }
20374:                     $count = 0;
20375:                     if ($possible ne '') {
20376:                         foreach my $poss (split(/\,/,$possible)) {
20377:                             $count ++;
20378:                             if (&validate_ip_pattern($poss)) {
20379:                                 push(@ok,$poss);
20380:                             }
20381:                         }
20382:                         if (@ok) {
20383:                             $wafproxy{$item} = join(',',@ok);
20384:                         }
20385:                         my $diff = $count - scalar(@ok);
20386:                         if ($diff) {
20387:                             push(@warnings,'<li>'.
20388:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
20389:                                      $diff,$warn{$item}).
20390:                                  '</li>');
20391:                         }
20392:                     }
20393:                 }
20394:                 if ($wafproxy{$item} ne $currvalue{$item}) {
20395:                     $changes{$item} = 1;
20396:                 }
20397:             } elsif ($currvalue{$item}) {
20398:                 $changes{$item} = 1;
20399:             } 
20400:         }
20401:     } else {
20402:         if (keys(%curralias)) {
20403:             $changes{'alias'} = 1;
20404:         }
20405:         if (keys(%currsaml)) {
20406:             $changes{'saml'} = 1;
20407:         } 
20408:         if (keys(%currvalue)) {
20409:             foreach my $key (keys(%currvalue)) {
20410:                 $changes{$key} = 1;
20411:             }
20412:         }
20413:     }
20414:     if (keys(%changes)) {
20415:         my %defaultshash = (
20416:                               wafproxy => \%wafproxy,
20417:                            ); 
20418:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20419:                                                  $dom);
20420:         if ($putresult eq 'ok') {
20421:             my $cachetime = 24*60*60;
20422:             my (%domdefaults,$updatedomdefs);
20423:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
20424:                 if ($changes{$item}) {
20425:                     unless ($updatedomdefs) {
20426:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20427:                         $updatedomdefs = 1;
20428:                     }
20429:                     if ($wafproxy{$item}) {
20430:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
20431:                     } elsif (exists($domdefaults{'waf_'.$item})) {
20432:                         delete($domdefaults{'waf_'.$item});
20433:                     } 
20434:                 }
20435:             }
20436:             if ($updatedomdefs) {
20437:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20438:                 if (ref($lastactref) eq 'HASH') {
20439:                     $lastactref->{'domdefaults'} = 1;
20440:                 }
20441:             }
20442:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
20443:                 my %updates = %expirecache;
20444:                 foreach my $key (keys(%expirecache)) {
20445:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
20446:                 }
20447:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
20448:                     my $cachetime = 24*60*60;
20449:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
20450:                         $updates{$key} = 1;
20451:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
20452:                                                       $cachetime);
20453:                     }
20454:                 }
20455:                 if (ref($lastactref) eq 'HASH') {
20456:                     $lastactref->{'proxyalias'} = \%updates;
20457:                 }
20458:             }
20459:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
20460:                 my %samlupdates = %expiresaml;
20461:                 foreach my $key (keys(%expiresaml)) {
20462:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
20463:                 }
20464:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
20465:                     my $cachetime = 24*60*60;
20466:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
20467:                         $samlupdates{$key} = 1;
20468:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
20469:                                                       $cachetime);
20470:                     }
20471:                 }
20472:                 if (ref($lastactref) eq 'HASH') {
20473:                     $lastactref->{'proxysaml'} = \%samlupdates;
20474:                 }
20475:             }
20476:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
20477:             foreach my $item ('alias','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
20478:                 if ($changes{$item}) {
20479:                     if ($item eq 'alias') {
20480:                         my $numaliased = 0;
20481:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
20482:                             my $shown;
20483:                             if (keys(%{$wafproxy{'alias'}})) {
20484:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
20485:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
20486:                                                          &Apache::lonnet::hostname($server),
20487:                                                          $wafproxy{'alias'}{$server}).'</li>';
20488:                                     $numaliased ++;
20489:                                 }
20490:                                 if ($numaliased) {
20491:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
20492:                                                           '<ul>'.$shown.'</ul>').'</li>';
20493:                                 }
20494:                             }
20495:                         }
20496:                         unless ($numaliased) {
20497:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
20498:                         }
20499:                     } elsif ($item eq 'saml') {
20500:                         my $shown; 
20501:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
20502:                             if (keys(%{$wafproxy{'saml'}})) {
20503:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
20504:                             }
20505:                         }
20506:                         if ($shown) {
20507:                             $output .= '<li>'.&mt('Alias used by Shibboleth for: [_1]',
20508:                                                   $shown).'</li>';
20509:                         } else {
20510:                             $output .= '<li>'.&mt('No alias used for Shibboleth').'</li>';
20511:                         }
20512:                     } else {
20513:                         if ($item eq 'remoteip') {
20514:                             my %ip_methods = &remoteip_methods();
20515:                             if ($wafproxy{$item} =~ /^[mh]$/) {
20516:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
20517:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
20518:                             } else {
20519:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
20520:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
20521:                                                '</li>';
20522:                                 } else {
20523:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
20524:                                 }
20525:                             }
20526:                         } elsif ($item eq 'ipheader') {
20527:                             if ($wafproxy{$item}) {
20528:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
20529:                                                       $wafproxy{$item}).'</li>';
20530:                             } else {
20531:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
20532:                             }
20533:                         } elsif ($item eq 'trusted') {
20534:                             if ($wafproxy{$item}) {
20535:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
20536:                                                       $wafproxy{$item}).'</li>';
20537:                             } else {
20538:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
20539:                             }
20540:                         } elsif ($item eq 'vpnint') {
20541:                             if ($wafproxy{$item}) {
20542:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
20543:                                                        $wafproxy{$item}).'</li>';
20544:                             } else {
20545:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
20546:                             }
20547:                         } elsif ($item eq 'vpnext') {
20548:                             if ($wafproxy{$item}) {
20549:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
20550:                                                        $wafproxy{$item}).'</li>';
20551:                             } else {
20552:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
20553:                             }
20554:                         } elsif ($item eq 'sslopt') {
20555:                             if ($wafproxy{$item}) {
20556:                                 $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>';
20557:                             } else {
20558:                                 $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>';
20559:                             }
20560:                         }
20561:                     }
20562:                 }
20563:             }
20564:         } else {
20565:             $output = '<span class="LC_error">'.
20566:                       &mt('An error occurred: [_1]',$putresult).'</span>';
20567:         }
20568:     } elsif (keys(%canset)) {
20569:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
20570:     }
20571:     if (@warnings) {
20572:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
20573:                        join("\n",@warnings).'</ul>';
20574:     }
20575:     return $output;
20576: }
20577: 
20578: sub validate_ip_pattern {
20579:     my ($pattern) = @_;
20580:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
20581:         my ($start,$end) = ($1,$2);
20582:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
20583:             return 1;
20584:         }
20585:     } elsif (&Net::CIDR::cidrvalidate($pattern)) {
20586:         return 1;
20587:     }
20588:     return
20589: }
20590: 
20591: sub modify_usersessions {
20592:     my ($dom,$lastactref,%domconfig) = @_;
20593:     my @hostingtypes = ('version','excludedomain','includedomain');
20594:     my @offloadtypes = ('primary','default');
20595:     my %types = (
20596:                   remote => \@hostingtypes,
20597:                   hosted => \@hostingtypes,
20598:                   spares => \@offloadtypes,
20599:                 );
20600:     my @prefixes = ('remote','hosted','spares');
20601:     my @lcversions = &Apache::lonnet::all_loncaparevs();
20602:     my (%by_ip,%by_location,@intdoms,@instdoms);
20603:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20604:     my @locations = sort(keys(%by_location));
20605:     my (%defaultshash,%changes);
20606:     foreach my $prefix (@prefixes) {
20607:         $defaultshash{'usersessions'}{$prefix} = {};
20608:     }
20609:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20610:     my $resulttext;
20611:     my %iphost = &Apache::lonnet::get_iphost();
20612:     foreach my $prefix (@prefixes) {
20613:         next if ($prefix eq 'spares');
20614:         foreach my $type (@{$types{$prefix}}) {
20615:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20616:             if ($type eq 'version') {
20617:                 my $value = $env{'form.'.$prefix.'_'.$type};
20618:                 my $okvalue;
20619:                 if ($value ne '') {
20620:                     if (grep(/^\Q$value\E$/,@lcversions)) {
20621:                         $okvalue = $value;
20622:                     }
20623:                 }
20624:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20625:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20626:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
20627:                             if ($inuse == 0) {
20628:                                 $changes{$prefix}{$type} = 1;
20629:                             } else {
20630:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
20631:                                     $changes{$prefix}{$type} = 1;
20632:                                 }
20633:                                 if ($okvalue ne '') {
20634:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20635:                                 } 
20636:                             }
20637:                         } else {
20638:                             if (($inuse == 1) && ($okvalue ne '')) {
20639:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20640:                                 $changes{$prefix}{$type} = 1;
20641:                             }
20642:                         }
20643:                     } else {
20644:                         if (($inuse == 1) && ($okvalue ne '')) {
20645:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20646:                             $changes{$prefix}{$type} = 1;
20647:                         }
20648:                     }
20649:                 } else {
20650:                     if (($inuse == 1) && ($okvalue ne '')) {
20651:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20652:                         $changes{$prefix}{$type} = 1;
20653:                     }
20654:                 }
20655:             } else {
20656:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20657:                 my @okvals;
20658:                 foreach my $val (@vals) {
20659:                     if ($val =~ /:/) {
20660:                         my @items = split(/:/,$val);
20661:                         foreach my $item (@items) {
20662:                             if (ref($by_location{$item}) eq 'ARRAY') {
20663:                                 push(@okvals,$item);
20664:                             }
20665:                         }
20666:                     } else {
20667:                         if (ref($by_location{$val}) eq 'ARRAY') {
20668:                             push(@okvals,$val);
20669:                         }
20670:                     }
20671:                 }
20672:                 @okvals = sort(@okvals);
20673:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20674:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20675:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20676:                             if ($inuse == 0) {
20677:                                 $changes{$prefix}{$type} = 1; 
20678:                             } else {
20679:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20680:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
20681:                                 if (@changed > 0) {
20682:                                     $changes{$prefix}{$type} = 1;
20683:                                 }
20684:                             }
20685:                         } else {
20686:                             if ($inuse == 1) {
20687:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20688:                                 $changes{$prefix}{$type} = 1;
20689:                             }
20690:                         } 
20691:                     } else {
20692:                         if ($inuse == 1) {
20693:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20694:                             $changes{$prefix}{$type} = 1;
20695:                         }
20696:                     }
20697:                 } else {
20698:                     if ($inuse == 1) {
20699:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20700:                         $changes{$prefix}{$type} = 1;
20701:                     }
20702:                 }
20703:             }
20704:         }
20705:     }
20706: 
20707:     my @alldoms = &Apache::lonnet::all_domains();
20708:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20709:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
20710:     my $savespares;
20711: 
20712:     foreach my $lonhost (sort(keys(%servers))) {
20713:         my $serverhomeID =
20714:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
20715:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
20716:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
20717:         my %spareschg;
20718:         foreach my $type (@{$types{'spares'}}) {
20719:             my @okspares;
20720:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
20721:             foreach my $server (@checked) {
20722:                 if (&Apache::lonnet::hostname($server) ne '') {
20723:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
20724:                         unless (grep(/^\Q$server\E$/,@okspares)) {
20725:                             push(@okspares,$server);
20726:                         }
20727:                     }
20728:                 }
20729:             }
20730:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
20731:             my $newspare;
20732:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
20733:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
20734:                     $newspare = $new;
20735:                 }
20736:             }
20737:             my @spares;
20738:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
20739:                 @spares = sort(@okspares,$newspare);
20740:             } else {
20741:                 @spares = sort(@okspares);
20742:             }
20743:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
20744:             if (ref($spareid{$lonhost}) eq 'HASH') {
20745:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
20746:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
20747:                     if (@diffs > 0) {
20748:                         $spareschg{$type} = 1;
20749:                     }
20750:                 }
20751:             }
20752:         }
20753:         if (keys(%spareschg) > 0) {
20754:             $changes{'spares'}{$lonhost} = \%spareschg;
20755:         }
20756:     }
20757:     $defaultshash{'usersessions'}{'offloadnow'} = {};
20758:     $defaultshash{'usersessions'}{'offloadoth'} = {};
20759:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
20760:     my @okoffload;
20761:     if (@offloadnow) {
20762:         foreach my $server (@offloadnow) {
20763:             if (&Apache::lonnet::hostname($server) ne '') {
20764:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
20765:                     push(@okoffload,$server);
20766:                 }
20767:             }
20768:         }
20769:         if (@okoffload) {
20770:             foreach my $lonhost (@okoffload) {
20771:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
20772:             }
20773:         }
20774:     }
20775:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
20776:     my @okoffloadoth;
20777:     if (@offloadoth) {
20778:         foreach my $server (@offloadoth) {
20779:             if (&Apache::lonnet::hostname($server) ne '') {
20780:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
20781:                     push(@okoffloadoth,$server);
20782:                 }
20783:             }
20784:         }
20785:         if (@okoffloadoth) {
20786:             foreach my $lonhost (@okoffloadoth) {
20787:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
20788:             }
20789:         }
20790:     }
20791:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
20792:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
20793:             if (ref($changes{'spares'}) eq 'HASH') {
20794:                 if (keys(%{$changes{'spares'}}) > 0) {
20795:                     $savespares = 1;
20796:                 }
20797:             }
20798:         } else {
20799:             $savespares = 1;
20800:         }
20801:         foreach my $offload ('offloadnow','offloadoth') {
20802:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
20803:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
20804:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
20805:                         $changes{$offload} = 1;
20806:                         last;
20807:                     }
20808:                 }
20809:                 unless ($changes{$offload}) {
20810:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
20811:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
20812:                             $changes{$offload} = 1;
20813:                             last;
20814:                         }
20815:                     }
20816:                 }
20817:             } else {
20818:                 if (($offload eq 'offloadnow') && (@okoffload)) {
20819:                      $changes{'offloadnow'} = 1;
20820:                 }
20821:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
20822:                     $changes{'offloadoth'} = 1;
20823:                 }
20824:             } 
20825:         }
20826:     } else {
20827:         if (@okoffload) {
20828:             $changes{'offloadnow'} = 1;
20829:         }
20830:         if (@okoffloadoth) {
20831:             $changes{'offloadoth'} = 1;
20832:         }
20833:     }
20834:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
20835:     if ((keys(%changes) > 0) || ($savespares)) {
20836:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20837:                                                  $dom);
20838:         if ($putresult eq 'ok') {
20839:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20840:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
20841:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
20842:                 }
20843:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
20844:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
20845:                 }
20846:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20847:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
20848:                 }
20849:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20850:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
20851:                 }
20852:             }
20853:             my $cachetime = 24*60*60;
20854:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20855:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
20856:             if (ref($lastactref) eq 'HASH') {
20857:                 $lastactref->{'domdefaults'} = 1;
20858:                 $lastactref->{'usersessions'} = 1;
20859:             }
20860:             if (keys(%changes) > 0) {
20861:                 my %lt = &usersession_titles();
20862:                 $resulttext = &mt('Changes made:').'<ul>';
20863:                 foreach my $prefix (@prefixes) {
20864:                     if (ref($changes{$prefix}) eq 'HASH') {
20865:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
20866:                         if ($prefix eq 'spares') {
20867:                             if (ref($changes{$prefix}) eq 'HASH') {
20868:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
20869:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
20870:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
20871:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
20872:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
20873:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
20874:                                         foreach my $type (@{$types{$prefix}}) {
20875:                                             if ($changes{$prefix}{$lonhost}{$type}) {
20876:                                                 my $offloadto = &mt('None');
20877:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
20878:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
20879:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
20880:                                                     }
20881:                                                 }
20882:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
20883:                                             }
20884:                                         }
20885:                                     }
20886:                                     $resulttext .= '</li>';
20887:                                 }
20888:                             }
20889:                         } else {
20890:                             foreach my $type (@{$types{$prefix}}) {
20891:                                 if (defined($changes{$prefix}{$type})) {
20892:                                     my ($newvalue,$notinuse);
20893:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20894:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
20895:                                             if ($type eq 'version') {
20896:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
20897:                                             } else {
20898:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20899:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
20900:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
20901:                                                     }
20902:                                                 } else {
20903:                                                     $notinuse = 1;
20904:                                                 }
20905:                                             }
20906:                                         }
20907:                                     }
20908:                                     if ($newvalue eq '') {
20909:                                         if ($type eq 'version') {
20910:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
20911:                                         } elsif ($notinuse) {
20912:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
20913:                                         } else {
20914:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
20915:                                         }
20916:                                     } else {
20917:                                         if ($type eq 'version') {
20918:                                             $newvalue .= ' '.&mt('(or later)');
20919:                                         }
20920:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
20921:                                     }
20922:                                 }
20923:                             }
20924:                         }
20925:                         $resulttext .= '</ul>';
20926:                     }
20927:                 }
20928:                 if ($changes{'offloadnow'}) {
20929:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20930:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
20931:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
20932:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
20933:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20934:                             }
20935:                             $resulttext .= '</ul>';
20936:                         } else {
20937:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
20938:                         }
20939:                     } else {
20940:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
20941:                     }
20942:                 }
20943:                 if ($changes{'offloadoth'}) {
20944:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20945:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
20946:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
20947:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
20948:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20949:                             }
20950:                             $resulttext .= '</ul>';
20951:                         } else {
20952:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
20953:                         }
20954:                     } else {
20955:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
20956:                     }
20957:                 }
20958:                 $resulttext .= '</ul>';
20959:             } else {
20960:                 $resulttext = $nochgmsg;
20961:             }
20962:         } else {
20963:             $resulttext = '<span class="LC_error">'.
20964:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20965:         }
20966:     } else {
20967:         $resulttext = $nochgmsg;
20968:     }
20969:     return $resulttext;
20970: }
20971: 
20972: sub modify_ssl {
20973:     my ($dom,$lastactref,%domconfig) = @_;
20974:     my (%by_ip,%by_location,@intdoms,@instdoms);
20975:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20976:     my @locations = sort(keys(%by_location));
20977:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20978:     my (%defaultshash,%changes);
20979:     my $action = 'ssl';
20980:     my @prefixes = ('connto','connfrom','replication');
20981:     foreach my $prefix (@prefixes) {
20982:         $defaultshash{$action}{$prefix} = {};
20983:     }
20984:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20985:     my $resulttext;
20986:     my %iphost = &Apache::lonnet::get_iphost();
20987:     my @reptypes = ('certreq','nocertreq');
20988:     my @connecttypes = ('dom','intdom','other');
20989:     my %types = (
20990:                   connto      => \@connecttypes,
20991:                   connfrom    => \@connecttypes,
20992:                   replication => \@reptypes,
20993:                 );
20994:     foreach my $prefix (sort(keys(%types))) {
20995:         foreach my $type (@{$types{$prefix}}) {
20996:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
20997:                 my $value = 'yes';
20998:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
20999:                     $value = $env{'form.'.$prefix.'_'.$type};
21000:                 }
21001:                 if (ref($domconfig{$action}) eq 'HASH') {
21002:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
21003:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
21004:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
21005:                                 $changes{$prefix}{$type} = 1;
21006:                             }
21007:                             $defaultshash{$action}{$prefix}{$type} = $value;
21008:                         } else {
21009:                             $defaultshash{$action}{$prefix}{$type} = $value;
21010:                             $changes{$prefix}{$type} = 1;
21011:                         }
21012:                     } else {
21013:                         $defaultshash{$action}{$prefix}{$type} = $value;
21014:                         $changes{$prefix}{$type} = 1;
21015:                     }
21016:                 } else {
21017:                     $defaultshash{$action}{$prefix}{$type} = $value;
21018:                     $changes{$prefix}{$type} = 1;
21019:                 }
21020:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
21021:                     delete($changes{$prefix}{$type});
21022:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
21023:                     delete($changes{$prefix}{$type});
21024:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
21025:                     delete($changes{$prefix}{$type});
21026:                 }
21027:             } elsif ($prefix eq 'replication') {
21028:                 if (@locations > 0) {
21029:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
21030:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
21031:                     my @okvals;
21032:                     foreach my $val (@vals) {
21033:                         if ($val =~ /:/) {
21034:                             my @items = split(/:/,$val);
21035:                             foreach my $item (@items) {
21036:                                 if (ref($by_location{$item}) eq 'ARRAY') {
21037:                                     push(@okvals,$item);
21038:                                 }
21039:                             }
21040:                         } else {
21041:                             if (ref($by_location{$val}) eq 'ARRAY') {
21042:                                 push(@okvals,$val);
21043:                             }
21044:                         }
21045:                     }
21046:                     @okvals = sort(@okvals);
21047:                     if (ref($domconfig{$action}) eq 'HASH') {
21048:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
21049:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
21050:                                 if ($inuse == 0) {
21051:                                     $changes{$prefix}{$type} = 1;
21052:                                 } else {
21053:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
21054:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
21055:                                     if (@changed > 0) {
21056:                                         $changes{$prefix}{$type} = 1;
21057:                                     }
21058:                                 }
21059:                             } else {
21060:                                 if ($inuse == 1) {
21061:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
21062:                                     $changes{$prefix}{$type} = 1;
21063:                                 }
21064:                             }
21065:                         } else {
21066:                             if ($inuse == 1) {
21067:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
21068:                                 $changes{$prefix}{$type} = 1;
21069:                             }
21070:                         }
21071:                     } else {
21072:                         if ($inuse == 1) {
21073:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
21074:                             $changes{$prefix}{$type} = 1;
21075:                         }
21076:                     }
21077:                 }
21078:             }
21079:         }
21080:     }
21081:     if (keys(%changes)) {
21082:         foreach my $prefix (keys(%changes)) {
21083:             if (ref($changes{$prefix}) eq 'HASH') {
21084:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
21085:                     delete($changes{$prefix});
21086:                 }
21087:             } else {
21088:                 delete($changes{$prefix});
21089:             }
21090:         }
21091:     }
21092:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
21093:     if (keys(%changes) > 0) {
21094:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21095:                                                  $dom);
21096:         if ($putresult eq 'ok') {
21097:             if (ref($defaultshash{$action}) eq 'HASH') {
21098:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
21099:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
21100:                 }
21101:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
21102:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
21103:                 }
21104:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
21105:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
21106:                 }
21107:             }
21108:             my $cachetime = 24*60*60;
21109:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21110:             if (ref($lastactref) eq 'HASH') {
21111:                 $lastactref->{'domdefaults'} = 1;
21112:             }
21113:             if (keys(%changes) > 0) {
21114:                 my %titles = &ssl_titles();
21115:                 $resulttext = &mt('Changes made:').'<ul>';
21116:                 foreach my $prefix (@prefixes) {
21117:                     if (ref($changes{$prefix}) eq 'HASH') {
21118:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
21119:                         foreach my $type (@{$types{$prefix}}) {
21120:                             if (defined($changes{$prefix}{$type})) {
21121:                                 my ($newvalue,$notinuse);
21122:                                 if (ref($defaultshash{$action}) eq 'HASH') {
21123:                                     if (ref($defaultshash{$action}{$prefix})) {
21124:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
21125:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
21126:                                         } else {
21127:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
21128:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
21129:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
21130:                                                 }
21131:                                             } else {
21132:                                                 $notinuse = 1;
21133:                                             }
21134:                                         }
21135:                                     }
21136:                                     if ($notinuse) {
21137:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
21138:                                     } elsif ($newvalue eq '') {
21139:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
21140:                                     } else {
21141:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
21142:                                     }
21143:                                 }
21144:                             }
21145:                         }
21146:                         $resulttext .= '</ul>';
21147:                     }
21148:                 }
21149:             } else {
21150:                 $resulttext = $nochgmsg;
21151:             }
21152:         } else {
21153:             $resulttext = '<span class="LC_error">'.
21154:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21155:         }
21156:     } else {
21157:         $resulttext = $nochgmsg;
21158:     }
21159:     return $resulttext;
21160: }
21161: 
21162: sub modify_trust {
21163:     my ($dom,$lastactref,%domconfig) = @_;
21164:     my (%by_ip,%by_location,@intdoms,@instdoms);
21165:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
21166:     my @locations = sort(keys(%by_location));
21167:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
21168:     my @types = ('exc','inc');
21169:     my (%defaultshash,%changes);
21170:     foreach my $prefix (@prefixes) {
21171:         $defaultshash{'trust'}{$prefix} = {};
21172:     }
21173:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21174:     my $resulttext;
21175:     foreach my $prefix (@prefixes) {
21176:         foreach my $type (@types) {
21177:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
21178:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
21179:             my @okvals;
21180:             foreach my $val (@vals) {
21181:                 if ($val =~ /:/) {
21182:                     my @items = split(/:/,$val);
21183:                     foreach my $item (@items) {
21184:                         if (ref($by_location{$item}) eq 'ARRAY') {
21185:                             push(@okvals,$item);
21186:                         }
21187:                     }
21188:                 } else {
21189:                     if (ref($by_location{$val}) eq 'ARRAY') {
21190:                         push(@okvals,$val);
21191:                     }
21192:                 }
21193:             }
21194:             @okvals = sort(@okvals);
21195:             if (ref($domconfig{'trust'}) eq 'HASH') {
21196:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
21197:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
21198:                         if ($inuse == 0) {
21199:                             $changes{$prefix}{$type} = 1;
21200:                         } else {
21201:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21202:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
21203:                             if (@changed > 0) {
21204:                                 $changes{$prefix}{$type} = 1;
21205:                             }
21206:                         }
21207:                     } else {
21208:                         if ($inuse == 1) {
21209:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21210:                             $changes{$prefix}{$type} = 1;
21211:                         }
21212:                     }
21213:                 } else {
21214:                     if ($inuse == 1) {
21215:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21216:                         $changes{$prefix}{$type} = 1;
21217:                     }
21218:                 }
21219:             } else {
21220:                 if ($inuse == 1) {
21221:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
21222:                     $changes{$prefix}{$type} = 1;
21223:                 }
21224:             }
21225:         }
21226:     }
21227:     my $nochgmsg = &mt('No changes made to trust settings.');
21228:     if (keys(%changes) > 0) {
21229:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21230:                                                  $dom);
21231:         if ($putresult eq 'ok') {
21232:             if (ref($defaultshash{'trust'}) eq 'HASH') {
21233:                 foreach my $prefix (@prefixes) {
21234:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
21235:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
21236:                     }
21237:                 }
21238:             }
21239:             my $cachetime = 24*60*60;
21240:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21241:             if (ref($lastactref) eq 'HASH') {
21242:                 $lastactref->{'domdefaults'} = 1;
21243:             }
21244:             if (keys(%changes) > 0) {
21245:                 my %lt = &trust_titles();
21246:                 $resulttext = &mt('Changes made:').'<ul>';
21247:                 foreach my $prefix (@prefixes) {
21248:                     if (ref($changes{$prefix}) eq 'HASH') {
21249:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
21250:                         foreach my $type (@types) {
21251:                             if (defined($changes{$prefix}{$type})) {
21252:                                 my ($newvalue,$notinuse);
21253:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
21254:                                     if (ref($defaultshash{'trust'}{$prefix})) {
21255:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
21256:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
21257:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
21258:                                             }
21259:                                         } else {
21260:                                             $notinuse = 1;
21261:                                         }
21262:                                     }
21263:                                 }
21264:                                 if ($notinuse) {
21265:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
21266:                                 } elsif ($newvalue eq '') {
21267:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
21268:                                 } else {
21269:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
21270:                                 }
21271:                             }
21272:                         }
21273:                         $resulttext .= '</ul>';
21274:                     }
21275:                 }
21276:                 $resulttext .= '</ul>';
21277:             } else {
21278:                 $resulttext = $nochgmsg;
21279:             }
21280:         } else {
21281:             $resulttext = '<span class="LC_error">'.
21282:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21283:         }
21284:     } else {
21285:         $resulttext = $nochgmsg;
21286:     }
21287:     return $resulttext;
21288: }
21289: 
21290: sub modify_loadbalancing {
21291:     my ($dom,%domconfig) = @_;
21292:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
21293:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
21294:     my ($othertitle,$usertypes,$types) =
21295:         &Apache::loncommon::sorted_inst_types($dom);
21296:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21297:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
21298:     my @sparestypes = ('primary','default');
21299:     my %typetitles = &sparestype_titles();
21300:     my $resulttext;
21301:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
21302:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
21303:         %existing = %{$domconfig{'loadbalancing'}};
21304:     }
21305:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
21306:                               \%currtargets,\%currrules,\%currcookies);
21307:     my ($saveloadbalancing,%defaultshash,%changes);
21308:     my ($alltypes,$othertypes,$titles) =
21309:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
21310:     my %ruletitles = &offloadtype_text();
21311:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
21312:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
21313:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
21314:         if ($balancer eq '') {
21315:             next;
21316:         }
21317:         if (!exists($servers{$balancer})) {
21318:             if (exists($currbalancer{$balancer})) {
21319:                 push(@{$changes{'delete'}},$balancer);
21320:             }
21321:             next;
21322:         }
21323:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
21324:             push(@{$changes{'delete'}},$balancer);
21325:             next;
21326:         }
21327:         if (!exists($currbalancer{$balancer})) {
21328:             push(@{$changes{'add'}},$balancer);
21329:         }
21330:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
21331:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
21332:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
21333:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
21334:             $saveloadbalancing = 1;
21335:         }
21336:         foreach my $sparetype (@sparestypes) {
21337:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
21338:             my @offloadto;
21339:             foreach my $target (@targets) {
21340:                 if (($servers{$target}) && ($target ne $balancer)) {
21341:                     if ($sparetype eq 'default') {
21342:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
21343:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
21344:                         }
21345:                     }
21346:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
21347:                         push(@offloadto,$target);
21348:                     }
21349:                 }
21350:             }
21351:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
21352:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
21353:                     push(@offloadto,$balancer);
21354:                 }
21355:             }
21356:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
21357:         }
21358:         if ($env{'form.loadbalancing_cookie_'.$i}) {
21359:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
21360:             if (exists($currbalancer{$balancer})) { 
21361:                 unless ($currcookies{$balancer}) {
21362:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
21363:                 }
21364:             }
21365:         } elsif (exists($currbalancer{$balancer})) {
21366:             if ($currcookies{$balancer}) {
21367:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
21368:             }
21369:         }
21370:         if (ref($currtargets{$balancer}) eq 'HASH') {
21371:             foreach my $sparetype (@sparestypes) {
21372:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
21373:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
21374:                     if (@targetdiffs > 0) {
21375:                         $changes{'curr'}{$balancer}{'targets'} = 1;
21376:                     }
21377:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21378:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
21379:                         $changes{'curr'}{$balancer}{'targets'} = 1;
21380:                     }
21381:                 }
21382:             }
21383:         } else {
21384:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
21385:                 foreach my $sparetype (@sparestypes) {
21386:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21387:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
21388:                             $changes{'curr'}{$balancer}{'targets'} = 1;
21389:                         }
21390:                     }
21391:                 }
21392:             }
21393:         }
21394:         my $ishomedom;
21395:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
21396:             $ishomedom = 1;
21397:         }
21398:         if (ref($alltypes) eq 'ARRAY') {
21399:             foreach my $type (@{$alltypes}) {
21400:                 my $rule;
21401:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
21402:                          (!$ishomedom)) {
21403:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
21404:                 }
21405:                 if ($rule eq 'specific') {
21406:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
21407:                     if (exists($servers{$specifiedhost})) {
21408:                         $rule = $specifiedhost;
21409:                     }
21410:                 }
21411:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
21412:                 if (ref($currrules{$balancer}) eq 'HASH') {
21413:                     if ($rule ne $currrules{$balancer}{$type}) {
21414:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
21415:                     }
21416:                 } elsif ($rule ne '') {
21417:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
21418:                 }
21419:             }
21420:         }
21421:     }
21422:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
21423:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
21424:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
21425:             $defaultshash{'loadbalancing'} = {};
21426:         }
21427:         my $putresult = &Apache::lonnet::put_dom('configuration',
21428:                                                  \%defaultshash,$dom);
21429:         if ($putresult eq 'ok') {
21430:             if (keys(%changes) > 0) {
21431:                 my %toupdate;
21432:                 if (ref($changes{'delete'}) eq 'ARRAY') {
21433:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
21434:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
21435:                         $toupdate{$balancer} = 1;
21436:                     }
21437:                 }
21438:                 if (ref($changes{'add'}) eq 'ARRAY') {
21439:                     foreach my $balancer (sort(@{$changes{'add'}})) {
21440:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
21441:                         $toupdate{$balancer} = 1;
21442:                     }
21443:                 }
21444:                 if (ref($changes{'curr'}) eq 'HASH') {
21445:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
21446:                         $toupdate{$balancer} = 1;
21447:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
21448:                             if ($changes{'curr'}{$balancer}{'targets'}) {
21449:                                 my %offloadstr;
21450:                                 foreach my $sparetype (@sparestypes) {
21451:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21452:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
21453:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
21454:                                         }
21455:                                     }
21456:                                 }
21457:                                 if (keys(%offloadstr) == 0) {
21458:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
21459:                                 } else {
21460:                                     my $showoffload;
21461:                                     foreach my $sparetype (@sparestypes) {
21462:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
21463:                                         if (defined($offloadstr{$sparetype})) {
21464:                                             $showoffload .= $offloadstr{$sparetype};
21465:                                         } else {
21466:                                             $showoffload .= &mt('None');
21467:                                         }
21468:                                         $showoffload .= ('&nbsp;'x3);
21469:                                     }
21470:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
21471:                                 }
21472:                             }
21473:                         }
21474:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
21475:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
21476:                                 foreach my $type (@{$alltypes}) {
21477:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
21478:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
21479:                                         my $balancetext;
21480:                                         if ($rule eq '') {
21481:                                             $balancetext =  $ruletitles{'default'};
21482:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
21483:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
21484:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
21485:                                                 foreach my $sparetype (@sparestypes) {
21486:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
21487:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
21488:                                                     }
21489:                                                 }
21490:                                                 foreach my $item (@{$alltypes}) {
21491:                                                     next if ($item =~  /^_LC_ipchange/);
21492:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
21493:                                                     if ($hasrule eq 'homeserver') {
21494:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
21495:                                                     } else {
21496:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
21497:                                                             if ($servers{$hasrule}) {
21498:                                                                 $toupdate{$hasrule} = 1;
21499:                                                             }
21500:                                                         }
21501:                                                     }
21502:                                                 }
21503:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
21504:                                                     $balancetext =  $ruletitles{$rule};
21505:                                                 } else {
21506:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
21507:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
21508:                                                     if ($receiver) {
21509:                                                         $toupdate{$receiver};
21510:                                                     }
21511:                                                 }
21512:                                             } else {
21513:                                                 $balancetext =  $ruletitles{$rule};
21514:                                             }
21515:                                         } else {
21516:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
21517:                                         }
21518:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
21519:                                     }
21520:                                 }
21521:                             }
21522:                         }
21523:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
21524:                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
21525:                                                       $balancer).'</li>'; 
21526:                         }
21527:                     }
21528:                 }
21529:                 if (keys(%toupdate)) {
21530:                     my %thismachine;
21531:                     my $updatedhere;
21532:                     my $cachetime = 60*60*24;
21533:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
21534:                     foreach my $lonhost (keys(%toupdate)) {
21535:                         if ($thismachine{$lonhost}) {
21536:                             unless ($updatedhere) {
21537:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
21538:                                                               $defaultshash{'loadbalancing'},
21539:                                                               $cachetime);
21540:                                 $updatedhere = 1;
21541:                             }
21542:                         } else {
21543:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
21544:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
21545:                         }
21546:                     }
21547:                 }
21548:                 if ($resulttext ne '') {
21549:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
21550:                 } else {
21551:                     $resulttext = $nochgmsg;
21552:                 }
21553:             } else {
21554:                 $resulttext = $nochgmsg;
21555:             }
21556:         } else {
21557:             $resulttext = '<span class="LC_error">'.
21558:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21559:         }
21560:     } else {
21561:         $resulttext = $nochgmsg;
21562:     }
21563:     return $resulttext;
21564: }
21565: 
21566: sub recurse_check {
21567:     my ($chkcats,$categories,$depth,$name) = @_;
21568:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
21569:         my $chg = 0;
21570:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
21571:             my $category = $chkcats->[$depth]{$name}[$j];
21572:             my $item;
21573:             if ($category eq '') {
21574:                 $chg ++;
21575:             } else {
21576:                 my $deeper = $depth + 1;
21577:                 $item = &escape($category).':'.&escape($name).':'.$depth;
21578:                 if ($chg) {
21579:                     $categories->{$item} -= $chg;
21580:                 }
21581:                 &recurse_check($chkcats,$categories,$deeper,$category);
21582:                 $deeper --;
21583:             }
21584:         }
21585:     }
21586:     return;
21587: }
21588: 
21589: sub recurse_cat_deletes {
21590:     my ($item,$coursecategories,$deletions) = @_;
21591:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
21592:     my $subdepth = $depth + 1;
21593:     if (ref($coursecategories) eq 'HASH') {
21594:         foreach my $subitem (keys(%{$coursecategories})) {
21595:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
21596:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
21597:                 delete($coursecategories->{$subitem});
21598:                 $deletions->{$subitem} = 1;
21599:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
21600:             }
21601:         }
21602:     }
21603:     return;
21604: }
21605: 
21606: sub active_dc_picker {
21607:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
21608:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
21609:     my @domcoord = keys(%domcoords);
21610:     if (keys(%currhash)) {
21611:         foreach my $dc (keys(%currhash)) {
21612:             unless (exists($domcoords{$dc})) {
21613:                 push(@domcoord,$dc);
21614:             }
21615:         }
21616:     }
21617:     @domcoord = sort(@domcoord);
21618:     my $numdcs = scalar(@domcoord);
21619:     my $rows = 0;
21620:     my $table;
21621:     if ($numdcs > 1) {
21622:         $table = '<table>';
21623:         for (my $i=0; $i<@domcoord; $i++) {
21624:             my $rem = $i%($numinrow);
21625:             if ($rem == 0) {
21626:                 if ($i > 0) {
21627:                     $table .= '</tr>';
21628:                 }
21629:                 $table .= '<tr>';
21630:                 $rows ++;
21631:             }
21632:             my $check = '';
21633:             if ($inputtype eq 'radio') {
21634:                 if (keys(%currhash) == 0) {
21635:                     if (!$i) {
21636:                         $check = ' checked="checked"';
21637:                     }
21638:                 } elsif (exists($currhash{$domcoord[$i]})) {
21639:                     $check = ' checked="checked"';
21640:                 }
21641:             } else {
21642:                 if (exists($currhash{$domcoord[$i]})) {
21643:                     $check = ' checked="checked"';
21644:                 }
21645:             }
21646:             if ($i == @domcoord - 1) {
21647:                 my $colsleft = $numinrow - $rem;
21648:                 if ($colsleft > 1) {
21649:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
21650:                 } else {
21651:                     $table .= '<td class="LC_left_item">';
21652:                 }
21653:             } else {
21654:                 $table .= '<td class="LC_left_item">';
21655:             }
21656:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
21657:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21658:             $table .= '<span class="LC_nobreak"><label>'.
21659:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
21660:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
21661:             if ($user ne $dcname.':'.$dcdom) {
21662:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21663:             }
21664:             $table .= '</label></span></td>';
21665:         }
21666:         $table .= '</tr></table>';
21667:     } elsif ($numdcs == 1) {
21668:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
21669:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21670:         if ($inputtype eq 'radio') {
21671:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
21672:             if ($user ne $dcname.':'.$dcdom) {
21673:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21674:             }
21675:         } else {
21676:             my $check;
21677:             if (exists($currhash{$domcoord[0]})) {
21678:                 $check = ' checked="checked"';
21679:             }
21680:             $table = '<span class="LC_nobreak"><label>'.
21681:                      '<input type="checkbox" name="'.$name.'" '.
21682:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
21683:             if ($user ne $dcname.':'.$dcdom) {
21684:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21685:             }
21686:             $table .= '</label></span>';
21687:             $rows ++;
21688:         }
21689:     }
21690:     return ($numdcs,$table,$rows);
21691: }
21692: 
21693: sub usersession_titles {
21694:     return &Apache::lonlocal::texthash(
21695:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
21696:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
21697:                spares => 'Servers offloaded to, when busy',
21698:                version => 'LON-CAPA version requirement',
21699:                excludedomain => 'Allow all, but exclude specific domains',
21700:                includedomain => 'Deny all, but include specific domains',
21701:                primary => 'Primary (checked first)',
21702:                default => 'Default',
21703:            );
21704: }
21705: 
21706: sub id_for_thisdom {
21707:     my (%servers) = @_;
21708:     my %altids;
21709:     foreach my $server (keys(%servers)) {
21710:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21711:         if ($serverhome ne $server) {
21712:             $altids{$serverhome} = $server;
21713:         }
21714:     }
21715:     return %altids;
21716: }
21717: 
21718: sub count_servers {
21719:     my ($currbalancer,%servers) = @_;
21720:     my (@spares,$numspares);
21721:     foreach my $lonhost (sort(keys(%servers))) {
21722:         next if ($currbalancer eq $lonhost);
21723:         push(@spares,$lonhost);
21724:     }
21725:     if ($currbalancer) {
21726:         $numspares = scalar(@spares);
21727:     } else {
21728:         $numspares = scalar(@spares) - 1;
21729:     }
21730:     return ($numspares,@spares);
21731: }
21732: 
21733: sub lonbalance_targets_js {
21734:     my ($dom,$types,$servers,$settings) = @_;
21735:     my $select = &mt('Select');
21736:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
21737:     if (ref($servers) eq 'HASH') {
21738:         $alltargets = join("','",sort(keys(%{$servers})));
21739:         my @homedoms;
21740:         foreach my $server (sort(keys(%{$servers}))) {
21741:             if (&Apache::lonnet::host_domain($server) eq $dom) {
21742:                 push(@homedoms,'1');
21743:             } else {
21744:                 push(@homedoms,'0');
21745:             }
21746:         }
21747:         $allishome = join("','",@homedoms);
21748:     }
21749:     if (ref($types) eq 'ARRAY') {
21750:         if (@{$types} > 0) {
21751:             @alltypes = @{$types};
21752:         }
21753:     }
21754:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
21755:     $allinsttypes = join("','",@alltypes);
21756:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
21757:     if (ref($settings) eq 'HASH') {
21758:         %existing = %{$settings};
21759:     }
21760:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
21761:                               \%currtargets,\%currrules,\%currcookies);
21762:     my $balancers = join("','",sort(keys(%currbalancer)));
21763:     return <<"END";
21764: 
21765: <script type="text/javascript">
21766: // <![CDATA[
21767: 
21768: currBalancers = new Array('$balancers');
21769: 
21770: function toggleTargets(balnum) {
21771:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21772:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
21773:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
21774:     var prevbalancer = prevhostitem.value;
21775:     var baltotal = document.getElementById('loadbalancing_total').value;
21776:     prevhostitem.value = balancer;
21777:     if (prevbalancer != '') {
21778:         var prevIdx = currBalancers.indexOf(prevbalancer);
21779:         if (prevIdx != -1) {
21780:             currBalancers.splice(prevIdx,1);
21781:         }
21782:     }
21783:     if (balancer == '') {
21784:         hideSpares(balnum);
21785:     } else {
21786:         var currIdx = currBalancers.indexOf(balancer);
21787:         if (currIdx == -1) {
21788:             currBalancers.push(balancer);
21789:         }
21790:         var homedoms = new Array('$allishome');
21791:         var ishomedom = homedoms[lonhostitem.selectedIndex];
21792:         showSpares(balancer,ishomedom,balnum);
21793:     }
21794:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
21795:     return;
21796: }
21797: 
21798: function showSpares(balancer,ishomedom,balnum) {
21799:     var alltargets = new Array('$alltargets');
21800:     var insttypes = new Array('$allinsttypes');
21801:     var offloadtypes = new Array('primary','default');
21802: 
21803:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
21804:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
21805:  
21806:     for (var i=0; i<offloadtypes.length; i++) {
21807:         var count = 0;
21808:         for (var j=0; j<alltargets.length; j++) {
21809:             if (alltargets[j] != balancer) {
21810:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
21811:                 item.value = alltargets[j];
21812:                 item.style.textAlign='left';
21813:                 item.style.textFace='normal';
21814:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
21815:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
21816:                     item.disabled = '';
21817:                 } else {
21818:                     item.disabled = 'disabled';
21819:                     item.checked = false;
21820:                 }
21821:                 count ++;
21822:             }
21823:         }
21824:     }
21825:     for (var k=0; k<insttypes.length; k++) {
21826:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
21827:             if (ishomedom == 1) {
21828:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21829:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21830:             } else {
21831:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21832:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21833:             }
21834:         } else {
21835:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21836:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21837:         }
21838:         if ((insttypes[k] != '_LC_external') && 
21839:             ((insttypes[k] != '_LC_internetdom') ||
21840:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
21841:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
21842:             item.options.length = 0;
21843:             item.options[0] = new Option("","",true,true);
21844:             var idx = 0;
21845:             for (var m=0; m<alltargets.length; m++) {
21846:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
21847:                     idx ++;
21848:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
21849:                 }
21850:             }
21851:         }
21852:     }
21853:     return;
21854: }
21855: 
21856: function hideSpares(balnum) {
21857:     var alltargets = new Array('$alltargets');
21858:     var insttypes = new Array('$allinsttypes');
21859:     var offloadtypes = new Array('primary','default');
21860: 
21861:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
21862:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
21863: 
21864:     var total = alltargets.length - 1;
21865:     for (var i=0; i<offloadtypes; i++) {
21866:         for (var j=0; j<total; j++) {
21867:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
21868:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
21869:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
21870:         }
21871:     }
21872:     for (var k=0; k<insttypes.length; k++) {
21873:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21874:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21875:         if (insttypes[k] != '_LC_external') {
21876:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
21877:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
21878:         }
21879:     }
21880:     return;
21881: }
21882: 
21883: function checkOffloads(item,balnum,type) {
21884:     var alltargets = new Array('$alltargets');
21885:     var offloadtypes = new Array('primary','default');
21886:     if (item.checked) {
21887:         var total = alltargets.length - 1;
21888:         var other;
21889:         if (type == offloadtypes[0]) {
21890:             other = offloadtypes[1];
21891:         } else {
21892:             other = offloadtypes[0];
21893:         }
21894:         for (var i=0; i<total; i++) {
21895:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
21896:             if (server == item.value) {
21897:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
21898:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
21899:                 }
21900:             }
21901:         }
21902:     }
21903:     return;
21904: }
21905: 
21906: function singleServerToggle(balnum,type) {
21907:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
21908:     if (offloadtoSelIdx == 0) {
21909:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
21910:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21911: 
21912:     } else {
21913:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
21914:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21915:     }
21916:     return;
21917: }
21918: 
21919: function balanceruleChange(formname,balnum,type) {
21920:     if (type == '_LC_external') {
21921:         return;
21922:     }
21923:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
21924:     for (var i=0; i<typesRules.length; i++) {
21925:         if (formname.elements[typesRules[i]].checked) {
21926:             if (formname.elements[typesRules[i]].value != 'specific') {
21927:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
21928:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21929:             } else {
21930:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21931:             }
21932:         }
21933:     }
21934:     return;
21935: }
21936: 
21937: function balancerDeleteChange(balnum) {
21938:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21939:     var baltotal = document.getElementById('loadbalancing_total').value;
21940:     var addtarget;
21941:     var removetarget;
21942:     var action = 'delete';
21943:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
21944:         var lonhost = hostitem.value;
21945:         var currIdx = currBalancers.indexOf(lonhost);
21946:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
21947:             if (currIdx != -1) {
21948:                 currBalancers.splice(currIdx,1);
21949:             }
21950:             addtarget = lonhost;
21951:         } else {
21952:             if (currIdx == -1) {
21953:                 currBalancers.push(lonhost);
21954:             }
21955:             removetarget = lonhost;
21956:             action = 'undelete';
21957:         }
21958:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
21959:     }
21960:     return;
21961: }
21962: 
21963: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
21964:     if (baltotal > 1) {
21965:         var offloadtypes = new Array('primary','default');
21966:         var alltargets = new Array('$alltargets');
21967:         var insttypes = new Array('$allinsttypes');
21968:         for (var i=0; i<baltotal; i++) {
21969:             if (i != balnum) {
21970:                 for (var j=0; j<offloadtypes.length; j++) {
21971:                     var total = alltargets.length - 1;
21972:                     for (var k=0; k<total; k++) {
21973:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
21974:                         var server = serveritem.value;
21975:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
21976:                             if (server == addtarget) {
21977:                                 serveritem.disabled = '';
21978:                             }
21979:                         }
21980:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
21981:                             if (server == removetarget) {
21982:                                 serveritem.disabled = 'disabled';
21983:                                 serveritem.checked = false;
21984:                             }
21985:                         }
21986:                     }
21987:                 }
21988:                 for (var j=0; j<insttypes.length; j++) {
21989:                     if (insttypes[j] != '_LC_external') {
21990:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
21991:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
21992:                             var currSel = singleserver.selectedIndex;
21993:                             var currVal = singleserver.options[currSel].value;
21994:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
21995:                                 var numoptions = singleserver.options.length;
21996:                                 var needsnew = 1;
21997:                                 for (var k=0; k<numoptions; k++) {
21998:                                     if (singleserver.options[k] == addtarget) {
21999:                                         needsnew = 0;
22000:                                         break;
22001:                                     }
22002:                                 }
22003:                                 if (needsnew == 1) {
22004:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
22005:                                 }
22006:                             }
22007:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
22008:                                 singleserver.options.length = 0;
22009:                                 if ((currVal) && (currVal != removetarget)) {
22010:                                     singleserver.options[0] = new Option("","",false,false);
22011:                                 } else {
22012:                                     singleserver.options[0] = new Option("","",true,true);
22013:                                 }
22014:                                 var idx = 0;
22015:                                 for (var m=0; m<alltargets.length; m++) {
22016:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
22017:                                         idx ++;
22018:                                         if (currVal == alltargets[m]) {
22019:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
22020:                                         } else {
22021:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
22022:                                         }
22023:                                     }
22024:                                 }
22025:                             }
22026:                         }
22027:                     }
22028:                 }
22029:             }
22030:         }
22031:     }
22032:     return;
22033: }
22034: 
22035: // ]]>
22036: </script>
22037: 
22038: END
22039: }
22040: 
22041: 
22042: sub new_spares_js {
22043:     my @sparestypes = ('primary','default');
22044:     my $types = join("','",@sparestypes);
22045:     my $select = &mt('Select');
22046:     return <<"END";
22047: 
22048: <script type="text/javascript">
22049: // <![CDATA[
22050: 
22051: function updateNewSpares(formname,lonhost) {
22052:     var types = new Array('$types');
22053:     var include = new Array();
22054:     var exclude = new Array();
22055:     for (var i=0; i<types.length; i++) {
22056:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
22057:         for (var j=0; j<spareboxes.length; j++) {
22058:             if (formname.elements[spareboxes[j]].checked) {
22059:                 exclude.push(formname.elements[spareboxes[j]].value);
22060:             } else {
22061:                 include.push(formname.elements[spareboxes[j]].value);
22062:             }
22063:         }
22064:     }
22065:     for (var i=0; i<types.length; i++) {
22066:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
22067:         var selIdx = newSpare.selectedIndex;
22068:         var currnew = newSpare.options[selIdx].value;
22069:         var okSpares = new Array();
22070:         for (var j=0; j<newSpare.options.length; j++) {
22071:             var possible = newSpare.options[j].value;
22072:             if (possible != '') {
22073:                 if (exclude.indexOf(possible) == -1) {
22074:                     okSpares.push(possible);
22075:                 } else {
22076:                     if (currnew == possible) {
22077:                         selIdx = 0;
22078:                     }
22079:                 }
22080:             }
22081:         }
22082:         for (var k=0; k<include.length; k++) {
22083:             if (okSpares.indexOf(include[k]) == -1) {
22084:                 okSpares.push(include[k]);
22085:             }
22086:         }
22087:         okSpares.sort();
22088:         newSpare.options.length = 0;
22089:         if (selIdx == 0) {
22090:             newSpare.options[0] = new Option("$select","",true,true);
22091:         } else {
22092:             newSpare.options[0] = new Option("$select","",false,false);
22093:         }
22094:         for (var m=0; m<okSpares.length; m++) {
22095:             var idx = m+1;
22096:             var selThis = 0;
22097:             if (selIdx != 0) {
22098:                 if (okSpares[m] == currnew) {
22099:                     selThis = 1;
22100:                 }
22101:             }
22102:             if (selThis == 1) {
22103:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
22104:             } else {
22105:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
22106:             }
22107:         }
22108:     }
22109:     return;
22110: }
22111: 
22112: function checkNewSpares(lonhost,type) {
22113:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
22114:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
22115:     if (chosen != '') {
22116:         var othertype;
22117:         var othernewSpare;
22118:         if (type == 'primary') {
22119:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
22120:         }
22121:         if (type == 'default') {
22122:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
22123:         }
22124:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
22125:             othernewSpare.selectedIndex = 0;
22126:         }
22127:     }
22128:     return;
22129: }
22130: 
22131: // ]]>
22132: </script>
22133: 
22134: END
22135: 
22136: }
22137: 
22138: sub common_domprefs_js {
22139:     return <<"END";
22140: 
22141: <script type="text/javascript">
22142: // <![CDATA[
22143: 
22144: function getIndicesByName(formname,item) {
22145:     var group = new Array();
22146:     for (var i=0;i<formname.elements.length;i++) {
22147:         if (formname.elements[i].name == item) {
22148:             group.push(formname.elements[i].id);
22149:         }
22150:     }
22151:     return group;
22152: }
22153: 
22154: // ]]>
22155: </script>
22156: 
22157: END
22158: 
22159: }
22160: 
22161: sub recaptcha_js {
22162:     my %lt = &captcha_phrases();
22163:     return <<"END";
22164: 
22165: <script type="text/javascript">
22166: // <![CDATA[
22167: 
22168: function updateCaptcha(caller,context) {
22169:     var privitem;
22170:     var pubitem;
22171:     var privtext;
22172:     var pubtext;
22173:     var versionitem;
22174:     var versiontext;
22175:     if (document.getElementById(context+'_recaptchapub')) {
22176:         pubitem = document.getElementById(context+'_recaptchapub');
22177:     } else {
22178:         return;
22179:     }
22180:     if (document.getElementById(context+'_recaptchapriv')) {
22181:         privitem = document.getElementById(context+'_recaptchapriv');
22182:     } else {
22183:         return;
22184:     }
22185:     if (document.getElementById(context+'_recaptchapubtxt')) {
22186:         pubtext = document.getElementById(context+'_recaptchapubtxt');
22187:     } else {
22188:         return;
22189:     }
22190:     if (document.getElementById(context+'_recaptchaprivtxt')) {
22191:         privtext = document.getElementById(context+'_recaptchaprivtxt');
22192:     } else {
22193:         return;
22194:     }
22195:     if (document.getElementById(context+'_recaptchaversion')) {
22196:         versionitem = document.getElementById(context+'_recaptchaversion');
22197:     } else {
22198:         return;
22199:     }
22200:     if (document.getElementById(context+'_recaptchavertxt')) {
22201:         versiontext = document.getElementById(context+'_recaptchavertxt');
22202:     } else {
22203:         return;
22204:     }
22205:     if (caller.checked) {
22206:         if (caller.value == 'recaptcha') {
22207:             pubitem.type = 'text';
22208:             privitem.type = 'text';
22209:             pubitem.size = '40';
22210:             privitem.size = '40';
22211:             pubtext.innerHTML = "$lt{'pub'}";
22212:             privtext.innerHTML = "$lt{'priv'}";
22213:             versionitem.type = 'text';
22214:             versionitem.size = '3';
22215:             versiontext.innerHTML = "$lt{'ver'}";
22216:         } else {
22217:             pubitem.type = 'hidden';
22218:             privitem.type = 'hidden';
22219:             versionitem.type = 'hidden';
22220:             pubtext.innerHTML = '';
22221:             privtext.innerHTML = '';
22222:             versiontext.innerHTML = '';
22223:         }
22224:     }
22225:     return;
22226: }
22227: 
22228: // ]]>
22229: </script>
22230: 
22231: END
22232: 
22233: }
22234: 
22235: sub toggle_display_js {
22236:     return <<"END";
22237: 
22238: <script type="text/javascript">
22239: // <![CDATA[
22240: 
22241: function toggleDisplay(domForm,caller) {
22242:     if (document.getElementById(caller)) {
22243:         var divitem = document.getElementById(caller);
22244:         var optionsElement = domForm.coursecredits;
22245:         var checkval = 1;
22246:         var dispval = 'block';
22247:         var selfcreateRegExp = /^cancreate_emailverified/;
22248:         if (caller == 'emailoptions') {
22249:             optionsElement = domForm.cancreate_email;
22250:         }
22251:         if (caller == 'studentsubmission') {
22252:             optionsElement = domForm.postsubmit;
22253:         }
22254:         if (caller == 'cloneinstcode') {
22255:             optionsElement = domForm.canclone;
22256:             checkval = 'instcode';
22257:         }
22258:         if (selfcreateRegExp.test(caller)) {
22259:             optionsElement = domForm.elements[caller];
22260:             checkval = 'other';
22261:             dispval = 'inline'
22262:         }
22263:         if (optionsElement.length) {
22264:             var currval;
22265:             for (var i=0; i<optionsElement.length; i++) {
22266:                 if (optionsElement[i].checked) {
22267:                    currval = optionsElement[i].value;
22268:                 }
22269:             }
22270:             if (currval == checkval) {
22271:                 divitem.style.display = dispval;
22272:             } else {
22273:                 divitem.style.display = 'none';
22274:             }
22275:         }
22276:     }
22277:     return;
22278: }
22279: 
22280: // ]]>
22281: </script>
22282: 
22283: END
22284: 
22285: }
22286: 
22287: sub captcha_phrases {
22288:     return &Apache::lonlocal::texthash (
22289:                  priv => 'Private key',
22290:                  pub  => 'Public key',
22291:                  original  => 'original (CAPTCHA)',
22292:                  recaptcha => 'successor (ReCAPTCHA)',
22293:                  notused   => 'unused',
22294:                  ver => 'ReCAPTCHA version (1 or 2)',
22295:     );
22296: }
22297: 
22298: sub devalidate_remote_domconfs {
22299:     my ($dom,$cachekeys) = @_;
22300:     return unless (ref($cachekeys) eq 'HASH');
22301:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22302:     my %thismachine;
22303:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
22304:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
22305:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml');
22306:     my %cache_by_lonhost;
22307:     if (exists($cachekeys->{'samllanding'})) {
22308:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
22309:             my %landing = %{$cachekeys->{'samllanding'}};
22310:             my %domservers = &Apache::lonnet::get_servers($dom);
22311:             if (keys(%domservers)) {
22312:                 foreach my $server (keys(%domservers)) {
22313:                     my @cached;
22314:                     next if ($thismachine{$server});
22315:                     if ($landing{$server}) {
22316:                         push(@cached,&escape('samllanding').':'.&escape($server));
22317:                     }
22318:                     if (@cached) {
22319:                         $cache_by_lonhost{$server} = \@cached;
22320:                     }
22321:                 }
22322:             }
22323:         }
22324:     }
22325:     if (keys(%servers)) {
22326:         foreach my $server (keys(%servers)) {
22327:             next if ($thismachine{$server});
22328:             my @cached;
22329:             foreach my $name (@posscached) {
22330:                 if ($cachekeys->{$name}) {
22331:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
22332:                         if (ref($cachekeys->{$name}) eq 'HASH') {
22333:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
22334:                                 push(@cached,&escape($name).':'.&escape($key));
22335:                             }
22336:                         }
22337:                     } else {
22338:                         push(@cached,&escape($name).':'.&escape($dom));
22339:                     }
22340:                 }
22341:             }
22342:             if ((exists($cache_by_lonhost{$server})) &&
22343:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
22344:                 push(@cached,@{$cache_by_lonhost{$server}});
22345:             }
22346:             if (@cached) {
22347:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
22348:             }
22349:         }
22350:     }
22351:     return;
22352: }
22353: 
22354: 1;

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