File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.383: download - view: text, annotated - select for diffs
Fri May 28 01:26:02 2021 UTC (3 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6914
  Update domain config UI for WAF/Proxy for an institution with more than one
  LON-CAPA domain, in the case where different nodes belong to different
  domains.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.383 2021/05/28 01:26:02 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);
  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:                       print => \&print_login,
  302:                       modify => \&modify_login,
  303:                     },
  304:         'defaults' => 
  305:                     { text => 'Default authentication/language/timezone/portal/types',
  306:                       help => 'Domain_Configuration_LangTZAuth',
  307:                       header => [{col1 => 'Setting',
  308:                                   col2 => 'Value'},
  309:                                  {col1 => 'Institutional user types',
  310:                                   col2 => 'Name displayed'}],
  311:                       print => \&print_defaults,
  312:                       modify => \&modify_defaults,
  313:                     },
  314:         'wafproxy' =>
  315:                     { text => 'Web Application Firewall/Reverse Proxy',
  316:                       help => 'Domain_Configuration_WAF_Proxy',
  317:                       header => [{col1 => 'Domain(s)',
  318:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  319:                                  },
  320:                                  {col1 => 'Domain(s)',
  321:                                   col2 => 'WAF Configuration',}],
  322:                       print => \&print_wafproxy,
  323:                       modify => \&modify_wafproxy,
  324:                     },
  325:         'passwords' =>
  326:                     { text => 'Passwords (Internal authentication)',
  327:                       help => 'Domain_Configuration_Passwords',
  328:                       header => [{col1 => 'Resetting Forgotten Password',
  329:                                   col2 => 'Settings'},
  330:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  331:                                   col2 => 'Settings'},
  332:                                  {col1 => 'Rules for LON-CAPA Passwords',
  333:                                   col2 => 'Settings'},
  334:                                  {col1 => 'Course Owner Changing Student Passwords',
  335:                                   col2 => 'Settings'}],
  336:                       print => \&print_passwords,
  337:                       modify => \&modify_passwords,
  338:                     },
  339:         'quotas' => 
  340:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  341:                       help => 'Domain_Configuration_Quotas',
  342:                       header => [{col1 => 'User affiliation',
  343:                                   col2 => 'Available tools',
  344:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  345:                       print => \&print_quotas,
  346:                       modify => \&modify_quotas,
  347:                     },
  348:         'autoenroll' =>
  349:                    { text => 'Auto-enrollment settings',
  350:                      help => 'Domain_Configuration_Auto_Enrollment',
  351:                      header => [{col1 => 'Configuration setting',
  352:                                  col2 => 'Value(s)'}],
  353:                      print => \&print_autoenroll,
  354:                      modify => \&modify_autoenroll,
  355:                    },
  356:         'autoupdate' => 
  357:                    { text => 'Auto-update settings',
  358:                      help => 'Domain_Configuration_Auto_Updates',
  359:                      header => [{col1 => 'Setting',
  360:                                  col2 => 'Value',},
  361:                                 {col1 => 'Setting',
  362:                                  col2 => 'Affiliation'},
  363:                                 {col1 => 'User population',
  364:                                  col2 => 'Updatable user data'}],
  365:                      print => \&print_autoupdate,
  366:                      modify => \&modify_autoupdate,
  367:                   },
  368:         'autocreate' => 
  369:                   { text => 'Auto-course creation settings',
  370:                      help => 'Domain_Configuration_Auto_Creation',
  371:                      header => [{col1 => 'Configuration Setting',
  372:                                  col2 => 'Value',}],
  373:                      print => \&print_autocreate,
  374:                      modify => \&modify_autocreate,
  375:                   },
  376:         'directorysrch' => 
  377:                   { text => 'Directory searches',
  378:                     help => 'Domain_Configuration_InstDirectory_Search',
  379:                     header => [{col1 => 'Institutional Directory Setting',
  380:                                 col2 => 'Value',},
  381:                                {col1 => 'LON-CAPA Directory Setting',
  382:                                 col2 => 'Value',}],
  383:                     print => \&print_directorysrch,
  384:                     modify => \&modify_directorysrch,
  385:                   },
  386:         'contacts' =>
  387:                   { text => 'E-mail addresses and helpform',
  388:                     help => 'Domain_Configuration_Contact_Info',
  389:                     header => [{col1 => 'Default e-mail addresses',
  390:                                 col2 => 'Value',},
  391:                                {col1 => 'Recipient(s) for notifications',
  392:                                 col2 => 'Value',},
  393:                                {col1 => 'Nightly status check e-mail',
  394:                                 col2 => 'Settings',},
  395:                                {col1 => 'Ask helpdesk form settings',
  396:                                 col2 => 'Value',},],
  397:                     print => \&print_contacts,
  398:                     modify => \&modify_contacts,
  399:                   },
  400:         'usercreation' => 
  401:                   { text => 'User creation',
  402:                     help => 'Domain_Configuration_User_Creation',
  403:                     header => [{col1 => 'Format rule type',
  404:                                 col2 => 'Format rules in force'},
  405:                                {col1 => 'User account creation',
  406:                                 col2 => 'Usernames which may be created',},
  407:                                {col1 => 'Context',
  408:                                 col2 => 'Assignable authentication types'}],
  409:                     print => \&print_usercreation,
  410:                     modify => \&modify_usercreation,
  411:                   },
  412:         'selfcreation' => 
  413:                   { text => 'Users self-creating accounts',
  414:                     help => 'Domain_Configuration_Self_Creation', 
  415:                     header => [{col1 => 'Self-creation with institutional username',
  416:                                 col2 => 'Enabled?'},
  417:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  418:                                 col2 => 'Information user can enter'},
  419:                                {col1 => 'Self-creation with e-mail verification',
  420:                                 col2 => 'Settings'}],
  421:                     print => \&print_selfcreation,
  422:                     modify => \&modify_selfcreation,
  423:                   },
  424:         'usermodification' =>
  425:                   { text => 'User modification',
  426:                     help => 'Domain_Configuration_User_Modification',
  427:                     header => [{col1 => 'Target user has role',
  428:                                 col2 => 'User information updatable in author context'},
  429:                                {col1 => 'Target user has role',
  430:                                 col2 => 'User information updatable in course context'}],
  431:                     print => \&print_usermodification,
  432:                     modify => \&modify_usermodification,
  433:                   },
  434:         'scantron' =>
  435:                   { text => 'Bubblesheet format',
  436:                     help => 'Domain_Configuration_Scantron_Format',
  437:                     header => [ {col1 => 'Bubblesheet format file',
  438:                                  col2 => ''},
  439:                                 {col1 => 'Bubblesheet data upload formats',
  440:                                  col2 => 'Settings'}],
  441:                     print => \&print_scantron,
  442:                     modify => \&modify_scantron,
  443:                   },
  444:         'requestcourses' => 
  445:                  {text => 'Request creation of courses',
  446:                   help => 'Domain_Configuration_Request_Courses',
  447:                   header => [{col1 => 'User affiliation',
  448:                               col2 => 'Availability/Processing of requests',},
  449:                              {col1 => 'Setting',
  450:                               col2 => 'Value'},
  451:                              {col1 => 'Available textbooks',
  452:                               col2 => ''},
  453:                              {col1 => 'Available templates',
  454:                               col2 => ''},
  455:                              {col1 => 'Validation (not official courses)',
  456:                               col2 => 'Value'},],
  457:                   print => \&print_quotas,
  458:                   modify => \&modify_quotas,
  459:                  },
  460:         'requestauthor' =>
  461:                  {text => 'Request Authoring Space',
  462:                   help => 'Domain_Configuration_Request_Author',
  463:                   header => [{col1 => 'User affiliation',
  464:                               col2 => 'Availability/Processing of requests',},
  465:                              {col1 => 'Setting',
  466:                               col2 => 'Value'}],
  467:                   print => \&print_quotas,
  468:                   modify => \&modify_quotas,
  469:                  },
  470:         'coursecategories' =>
  471:                   { text => 'Cataloging of courses/communities',
  472:                     help => 'Domain_Configuration_Cataloging_Courses',
  473:                     header => [{col1 => 'Catalog type/availability',
  474:                                 col2 => '',},
  475:                                {col1 => 'Category settings for standard catalog',
  476:                                 col2 => '',},
  477:                                {col1 => 'Categories',
  478:                                 col2 => '',
  479:                                }],
  480:                     print => \&print_coursecategories,
  481:                     modify => \&modify_coursecategories,
  482:                   },
  483:         'serverstatuses' =>
  484:                  {text   => 'Access to server status pages',
  485:                   help   => 'Domain_Configuration_Server_Status',
  486:                   header => [{col1 => 'Status Page',
  487:                               col2 => 'Other named users',
  488:                               col3 => 'Specific IPs',
  489:                             }],
  490:                   print => \&print_serverstatuses,
  491:                   modify => \&modify_serverstatuses,
  492:                  },
  493:         'helpsettings' =>
  494:                  {text   => 'Support settings',
  495:                   help   => 'Domain_Configuration_Help_Settings',
  496:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  497:                               col2 => 'Value'},
  498:                              {col1 => 'Helpdesk Roles',
  499:                               col2 => 'Settings'},],
  500:                   print  => \&print_helpsettings,
  501:                   modify => \&modify_helpsettings,
  502:                  },
  503:         'coursedefaults' => 
  504:                  {text => 'Course/Community defaults',
  505:                   help => 'Domain_Configuration_Course_Defaults',
  506:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  507:                               col2 => 'Value',},
  508:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  509:                               col2 => 'Value',},],
  510:                   print => \&print_coursedefaults,
  511:                   modify => \&modify_coursedefaults,
  512:                  },
  513:         'selfenrollment' => 
  514:                  {text   => 'Self-enrollment in Course/Community',
  515:                   help   => 'Domain_Configuration_Selfenrollment',
  516:                   header => [{col1 => 'Configuration Rights',
  517:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  518:                              {col1 => 'Defaults',
  519:                               col2 => 'Value'},
  520:                              {col1 => 'Self-enrollment validation (optional)',
  521:                               col2 => 'Value'},],
  522:                   print => \&print_selfenrollment,
  523:                   modify => \&modify_selfenrollment,
  524:                  },
  525:         'privacy' => 
  526:                  {text   => 'Availability of User Information',
  527:                   help   => 'Domain_Configuration_User_Privacy',
  528:                   header => [{col1 => 'Role assigned in different domain',
  529:                               col2 => 'Approval options'},
  530:                              {col1 => 'Role assigned in different domain to user of type',
  531:                               col2 => 'User information available in that domain'},
  532:                              {col1 => "Role assigned in user's domain",
  533:                               col2 => 'Information viewable by privileged user'},
  534:                              {col1 => "Role assigned in user's domain",
  535:                               col2 => 'Information viewable by unprivileged user'}],
  536:                   print => \&print_privacy,
  537:                   modify => \&modify_privacy,
  538:                  },
  539:         'usersessions' =>
  540:                  {text  => 'User session hosting/offloading',
  541:                   help  => 'Domain_Configuration_User_Sessions',
  542:                   header => [{col1 => 'Domain server',
  543:                               col2 => 'Servers to offload sessions to when busy'},
  544:                              {col1 => 'Hosting of users from other domains',
  545:                               col2 => 'Rules'},
  546:                              {col1 => "Hosting domain's own users elsewhere",
  547:                               col2 => 'Rules'}],
  548:                   print => \&print_usersessions,
  549:                   modify => \&modify_usersessions,
  550:                  },
  551:         'loadbalancing' =>
  552:                  {text  => 'Dedicated Load Balancer(s)',
  553:                   help  => 'Domain_Configuration_Load_Balancing',
  554:                   header => [{col1 => 'Balancers',
  555:                               col2 => 'Default destinations',
  556:                               col3 => 'User affiliation',
  557:                               col4 => 'Overrides'},
  558:                             ],
  559:                   print => \&print_loadbalancing,
  560:                   modify => \&modify_loadbalancing,
  561:                  },
  562:         'ltitools' => 
  563:                  {text => 'External Tools (LTI)',
  564:                   help => 'Domain_Configuration_LTI_Tools',
  565:                   header => [{col1 => 'Setting',
  566:                               col2 => 'Value',}],
  567:                   print => \&print_ltitools,
  568:                   modify => \&modify_ltitools,
  569:                  },
  570:         'proctoring' =>
  571:                  {text => 'Remote Proctoring Integration',
  572:                   help => 'Domain_Configuration_Proctoring',
  573:                   header => [{col1 => 'Name',
  574:                               col2 => 'Configuration'}],
  575:                   print => \&print_proctoring,
  576:                   modify => \&modify_proctoring,
  577:                  },
  578:         'ssl' =>
  579:                  {text  => 'LON-CAPA Network (SSL)',
  580:                   help  => 'Domain_Configuration_Network_SSL',
  581:                   header => [{col1 => 'Server',
  582:                               col2 => 'Certificate Status'},
  583:                              {col1 => 'Connections to other servers',
  584:                               col2 => 'Rules'},
  585:                              {col1 => 'Connections from other servers',
  586:                               col2 => 'Rules'},
  587:                              {col1 => "Replicating domain's published content",
  588:                               col2 => 'Rules'}],
  589:                   print => \&print_ssl,
  590:                   modify => \&modify_ssl,
  591:                  },
  592:         'trust' =>
  593:                  {text   => 'Trust Settings',
  594:                   help   => 'Domain_Configuration_Trust',
  595:                   header => [{col1 => "Access to this domain's content by others",
  596:                               col2 => 'Rules'},
  597:                              {col1 => "Access to other domain's content by this domain",
  598:                               col2 => 'Rules'},
  599:                              {col1 => "Enrollment in this domain's courses by others",
  600:                               col2 => 'Rules',},
  601:                              {col1 => "Co-author roles in this domain for others",
  602:                               col2 => 'Rules',},
  603:                              {col1 => "Co-author roles for this domain's users elsewhere",
  604:                               col2 => 'Rules',},
  605:                              {col1 => "Domain roles in this domain assignable to others",
  606:                               col2 => 'Rules'},
  607:                              {col1 => "Course catalog for this domain displayed elsewhere",
  608:                               col2 => 'Rules'},
  609:                              {col1 => "Requests for creation of courses in this domain by others",
  610:                               col2 => 'Rules'},
  611:                              {col1 => "Users in other domains can send messages to this domain",
  612:                               col2 => 'Rules'},],
  613:                   print => \&print_trust,
  614:                   modify => \&modify_trust,
  615:                  },
  616:           'lti' =>
  617:                  {text => 'LTI Provider',
  618:                   help => 'Domain_Configuration_LTI_Provider',
  619:                   header => [{col1 => 'Setting',
  620:                               col2 => 'Value',}],
  621:                   print => \&print_lti,
  622:                   modify => \&modify_lti,
  623:                  },
  624:     );
  625:     if (keys(%servers) > 1) {
  626:         $prefs{'login'}  = { text   => 'Log-in page options',
  627:                              help   => 'Domain_Configuration_Login_Page',
  628:                             header => [{col1 => 'Log-in Service',
  629:                                         col2 => 'Server Setting',},
  630:                                        {col1 => 'Log-in Page Items',
  631:                                         col2 => ''},
  632:                                        {col1 => 'Log-in Help',
  633:                                         col2 => 'Value'},
  634:                                        {col1 => 'Custom HTML in document head',
  635:                                         col2 => 'Value'}],
  636:                             print => \&print_login,
  637:                             modify => \&modify_login,
  638:                            };
  639:     }
  640: 
  641:     my @roles = ('student','coordinator','author','admin');
  642:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  643:     &Apache::lonhtmlcommon::add_breadcrumb
  644:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  645:       text=>"Settings to display/modify"});
  646:     my $confname = $dom.'-domainconfig';
  647: 
  648:     if ($phase eq 'process') {
  649:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  650:                                                               \%prefs,\%domconfig,$confname,\@roles);
  651:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  652:             $r->rflush();
  653:             &devalidate_remote_domconfs($dom,$result);
  654:         }
  655:     } elsif ($phase eq 'display') {
  656:         my $js = &recaptcha_js().
  657:                  &toggle_display_js();
  658:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  659:             my ($othertitle,$usertypes,$types) =
  660:                 &Apache::loncommon::sorted_inst_types($dom);
  661:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  662:                                           $domconfig{'loadbalancing'}).
  663:                    &new_spares_js().
  664:                    &common_domprefs_js().
  665:                    &Apache::loncommon::javascript_array_indexof();
  666:         }
  667:         if (grep(/^requestcourses$/,@actions)) {
  668:             my $javascript_validations;
  669:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  670:             $js .= <<END;
  671: <script type="text/javascript">
  672: $javascript_validations
  673: </script>
  674: $coursebrowserjs
  675: END
  676:         }
  677:         if (grep(/^selfcreation$/,@actions)) {
  678:             $js .= &selfcreate_javascript();
  679:         }
  680:         if (grep(/^contacts$/,@actions)) {
  681:             $js .= &contacts_javascript();
  682:         }
  683:         if (grep(/^scantron$/,@actions)) {
  684:             $js .= &scantron_javascript();
  685:         }
  686:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  687:     } else {
  688: # check if domconfig user exists for the domain.
  689:         my $servadm = $r->dir_config('lonAdmEMail');
  690:         my ($configuserok,$author_ok,$switchserver) =
  691:             &config_check($dom,$confname,$servadm);
  692:         unless ($configuserok eq 'ok') {
  693:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  694:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  695:                           $confname).
  696:                       '<br />'
  697:             );
  698:             if ($switchserver) {
  699:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  700:                           '<br />'.
  701:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  702:                           '<br />'.
  703:                           &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).
  704:                           '<br />'.
  705:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  706:                 );
  707:             } else {
  708:                 $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.').
  709:                           '<br />'.
  710:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  711:                 );
  712:             }
  713:             $r->print(&Apache::loncommon::end_page());
  714:             return OK;
  715:         }
  716:         if (keys(%domconfig) == 0) {
  717:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  718:             my @ids=&Apache::lonnet::current_machine_ids();
  719:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  720:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  721:                 my @loginimages = ('img','logo','domlogo','login');
  722:                 my $custom_img_count = 0;
  723:                 foreach my $img (@loginimages) {
  724:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  725:                         $custom_img_count ++;
  726:                     }
  727:                 }
  728:                 foreach my $role (@roles) {
  729:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  730:                         $custom_img_count ++;
  731:                     }
  732:                 }
  733:                 if ($custom_img_count > 0) {
  734:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  735:                     my $switch_server = &check_switchserver($dom,$confname);
  736:                     $r->print(
  737:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  738:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  739:     &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 />'.
  740:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  741:                     if ($switch_server) {
  742:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  743:                     }
  744:                     $r->print(&Apache::loncommon::end_page());
  745:                     return OK;
  746:                 }
  747:             }
  748:         }
  749:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  750:     }
  751:     return OK;
  752: }
  753: 
  754: sub process_changes {
  755:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  756:     my %domconfig;
  757:     if (ref($values) eq 'HASH') {
  758:         %domconfig = %{$values};
  759:     }
  760:     my $output;
  761:     if ($action eq 'login') {
  762:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  763:     } elsif ($action eq 'rolecolors') {
  764:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  765:                                      $lastactref,%domconfig);
  766:     } elsif ($action eq 'quotas') {
  767:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  768:     } elsif ($action eq 'autoenroll') {
  769:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  770:     } elsif ($action eq 'autoupdate') {
  771:         $output = &modify_autoupdate($dom,%domconfig);
  772:     } elsif ($action eq 'autocreate') {
  773:         $output = &modify_autocreate($dom,%domconfig);
  774:     } elsif ($action eq 'directorysrch') {
  775:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  776:     } elsif ($action eq 'usercreation') {
  777:         $output = &modify_usercreation($dom,%domconfig);
  778:     } elsif ($action eq 'selfcreation') {
  779:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  780:     } elsif ($action eq 'usermodification') {
  781:         $output = &modify_usermodification($dom,%domconfig);
  782:     } elsif ($action eq 'contacts') {
  783:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  784:     } elsif ($action eq 'defaults') {
  785:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  786:     } elsif ($action eq 'scantron') {
  787:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  788:     } elsif ($action eq 'coursecategories') {
  789:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  790:     } elsif ($action eq 'serverstatuses') {
  791:         $output = &modify_serverstatuses($dom,%domconfig);
  792:     } elsif ($action eq 'requestcourses') {
  793:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  794:     } elsif ($action eq 'requestauthor') {
  795:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  796:     } elsif ($action eq 'helpsettings') {
  797:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  798:     } elsif ($action eq 'coursedefaults') {
  799:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  800:     } elsif ($action eq 'selfenrollment') {
  801:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  802:     } elsif ($action eq 'usersessions') {
  803:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  804:     } elsif ($action eq 'loadbalancing') {
  805:         $output = &modify_loadbalancing($dom,%domconfig);
  806:     } elsif ($action eq 'ltitools') {
  807:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  808:     } elsif ($action eq 'proctoring') {
  809:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  810:     } elsif ($action eq 'ssl') {
  811:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  812:     } elsif ($action eq 'trust') {
  813:         $output = &modify_trust($dom,$lastactref,%domconfig);
  814:     } elsif ($action eq 'lti') {
  815:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  816:     } elsif ($action eq 'privacy') {
  817:         $output = &modify_privacy($dom,%domconfig);
  818:     } elsif ($action eq 'passwords') {
  819:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  820:     } elsif ($action eq 'wafproxy') {
  821:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  822:     }
  823:     return $output;
  824: }
  825: 
  826: sub print_config_box {
  827:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  828:     my $rowtotal = 0;
  829:     my $output;
  830:     if ($action eq 'coursecategories') {
  831:         $output = &coursecategories_javascript($settings);
  832:     } elsif ($action eq 'defaults') {
  833:         $output = &defaults_javascript($settings); 
  834:     } elsif ($action eq 'passwords') {
  835:         $output = &passwords_javascript();
  836:     } elsif ($action eq 'helpsettings') {
  837:         my (%privs,%levelscurrent);
  838:         my %full=();
  839:         my %levels=(
  840:                      course => {},
  841:                      domain => {},
  842:                      system => {},
  843:                    );
  844:         my $context = 'domain';
  845:         my $crstype = 'Course';
  846:         my $formname = 'display';
  847:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  848:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  849:         $output =
  850:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  851:                                                       \@templateroles);
  852:     } elsif ($action eq 'ltitools') {
  853:         $output .= &ltitools_javascript($settings);
  854:     } elsif ($action eq 'lti') {
  855:         $output .= &lti_javascript($settings);
  856:     } elsif ($action eq 'proctoring') {
  857:         $output .= &proctoring_javascript($settings);
  858:     } elsif ($action eq 'wafproxy') {
  859:         $output .= &wafproxy_javascript($dom);
  860:     }
  861:     $output .=
  862:          '<table class="LC_nested_outer">
  863:           <tr>
  864:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  865:            &mt($item->{text}).'&nbsp;'.
  866:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  867:           '</tr>';
  868:     $rowtotal ++;
  869:     my $numheaders = 1;
  870:     if (ref($item->{'header'}) eq 'ARRAY') {
  871:         $numheaders = scalar(@{$item->{'header'}});
  872:     }
  873:     if ($numheaders > 1) {
  874:         my $colspan = '';
  875:         my $rightcolspan = '';
  876:         my $leftnobr = '';
  877:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  878:             ($action eq 'directorysrch') ||
  879:             (($action eq 'login') && ($numheaders < 4))) {
  880:             $colspan = ' colspan="2"';
  881:         }
  882:         if ($action eq 'usersessions') {
  883:             $rightcolspan = ' colspan="3"'; 
  884:         }
  885:         if ($action eq 'passwords') {
  886:             $leftnobr = ' LC_nobreak';
  887:         }
  888:         $output .= '
  889:           <tr>
  890:            <td>
  891:             <table class="LC_nested">
  892:              <tr class="LC_info_row">
  893:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  894:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  895:              </tr>';
  896:         $rowtotal ++;
  897:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  898:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  899:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  900:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  901:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy')) {
  902:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  903:         } elsif ($action eq 'passwords') {
  904:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  905:         } elsif ($action eq 'coursecategories') {
  906:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  907:         } elsif ($action eq 'scantron') {
  908:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  909:         } elsif ($action eq 'login') {
  910:             if ($numheaders == 4) {
  911:                 $colspan = ' colspan="2"';
  912:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  913:             } else {
  914:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  915:             }
  916:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  917:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  918:         } elsif ($action eq 'rolecolors') {
  919:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  920:         }
  921:         $output .= '
  922:            </table>
  923:           </td>
  924:          </tr>
  925:          <tr>
  926:            <td>
  927:             <table class="LC_nested">
  928:              <tr class="LC_info_row">
  929:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  930:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  931:              </tr>';
  932:             $rowtotal ++;
  933:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  934:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  935:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  936:             ($action eq 'trust') || ($action eq 'contacts') ||
  937:             ($action eq 'privacy') || ($action eq 'passwords')) {
  938:             if ($action eq 'coursecategories') {
  939:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  940:                 $colspan = ' colspan="2"';
  941:             } elsif ($action eq 'trust') {
  942:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  943:             } elsif ($action eq 'passwords') {
  944:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  945:             } else {
  946:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  947:             }
  948:             if ($action eq 'trust') {
  949:                 $output .= '
  950:             </table>
  951:           </td>
  952:          </tr>';
  953:                 my @trusthdrs = qw(2 3 4 5 6 7);
  954:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
  955:                 for (my $i=0; $i<@trusthdrs; $i++) {
  956:                     $output .= '
  957:          <tr>
  958:            <td>
  959:             <table class="LC_nested">
  960:              <tr class="LC_info_row">
  961:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
  962:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
  963:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
  964:             </table>
  965:           </td>
  966:          </tr>';
  967:                 }
  968:                 $output .= '
  969:          <tr>
  970:            <td>
  971:             <table class="LC_nested">
  972:              <tr class="LC_info_row">
  973:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
  974:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
  975:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
  976:             } else {
  977:                 $output .= '
  978:            </table>
  979:           </td>
  980:          </tr>
  981:          <tr>
  982:            <td>
  983:             <table class="LC_nested">
  984:              <tr class="LC_info_row">
  985:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
  986:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
  987:              </tr>'."\n";
  988:                 if ($action eq 'coursecategories') {
  989:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
  990:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'passwords')) {
  991:                     if ($action eq 'passwords') {
  992:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
  993:                     } else {
  994:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
  995:                     }
  996:                     $output .= '
  997:              </tr>
  998:             </table>
  999:            </td>
 1000:           </tr>
 1001:           <tr>
 1002:            <td>
 1003:             <table class="LC_nested">
 1004:              <tr class="LC_info_row">
 1005:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1006:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1007:                     if ($action eq 'passwords') {
 1008:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1009:                     } else {
 1010:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1011:                     }
 1012:                     $output .= '
 1013:             </table>
 1014:           </td>
 1015:          </tr>
 1016:          <tr>';
 1017:                 } else {
 1018:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1019:                 }
 1020:             }
 1021:             $rowtotal ++;
 1022:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1023:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
 1024:                  ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
 1025:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1026:         } elsif ($action eq 'scantron') {
 1027:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1028:         } elsif ($action eq 'ssl') {
 1029:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1030:             </table>
 1031:           </td>
 1032:          </tr>
 1033:          <tr>
 1034:            <td>
 1035:             <table class="LC_nested">
 1036:              <tr class="LC_info_row">
 1037:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1038:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1039:                            $item->{'print'}->('connfrom',$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'}->[3]->{'col1'}).'</td>
 1048:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1049:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1050:         } elsif ($action eq 'login') {
 1051:             if ($numheaders == 4) {
 1052:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1053:            </table>
 1054:           </td>
 1055:          </tr>
 1056:          <tr>
 1057:            <td>
 1058:             <table class="LC_nested">
 1059:              <tr class="LC_info_row">
 1060:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1061:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1062:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1063:                 $rowtotal ++;
 1064:             } else {
 1065:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1066:             }
 1067:             $output .= '
 1068:            </table>
 1069:           </td>
 1070:          </tr>
 1071:          <tr>
 1072:            <td>
 1073:             <table class="LC_nested">
 1074:              <tr class="LC_info_row">';
 1075:             if ($numheaders == 4) {
 1076:                 $output .= '
 1077:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1078:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1079:              </tr>';
 1080:             } else {
 1081:                 $output .= '
 1082:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1083:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1084:              </tr>';
 1085:             }
 1086:             $rowtotal ++;
 1087:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal);
 1088:         } elsif ($action eq 'requestcourses') {
 1089:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1090:             $rowtotal ++;
 1091:             $output .= &print_studentcode($settings,\$rowtotal).'
 1092:            </table>
 1093:           </td>
 1094:          </tr>
 1095:          <tr>
 1096:            <td>
 1097:             <table class="LC_nested">
 1098:              <tr class="LC_info_row">
 1099:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1100:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1101:                        &textbookcourses_javascript($settings).
 1102:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1103:             </table>
 1104:            </td>
 1105:           </tr>
 1106:          <tr>
 1107:            <td>
 1108:             <table class="LC_nested">
 1109:              <tr class="LC_info_row">
 1110:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1111:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1112:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1113:             </table>
 1114:            </td>
 1115:           </tr>
 1116:           <tr>
 1117:            <td>
 1118:             <table class="LC_nested">
 1119:              <tr class="LC_info_row">
 1120:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1121:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1122:              </tr>'.
 1123:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1124:         } elsif ($action eq 'requestauthor') {
 1125:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1126:             $rowtotal ++;
 1127:         } elsif ($action eq 'rolecolors') {
 1128:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1129:            </table>
 1130:           </td>
 1131:          </tr>
 1132:          <tr>
 1133:            <td>
 1134:             <table class="LC_nested">
 1135:              <tr class="LC_info_row">
 1136:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1137:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1138:               <td class="LC_right_item" style="vertical-align: top">'.
 1139:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1140:              </tr>'.
 1141:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1142:            </table>
 1143:           </td>
 1144:          </tr>
 1145:          <tr>
 1146:            <td>
 1147:             <table class="LC_nested">
 1148:              <tr class="LC_info_row">
 1149:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1150:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1151:              </tr>'.
 1152:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1153:             $rowtotal += 2;
 1154:         }
 1155:     } else {
 1156:         $output .= '
 1157:           <tr>
 1158:            <td>
 1159:             <table class="LC_nested">
 1160:              <tr class="LC_info_row">';
 1161:         if ($action eq 'login') {
 1162:             $output .= '  
 1163:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1164:         } elsif ($action eq 'serverstatuses') {
 1165:             $output .= '
 1166:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1167:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1168: 
 1169:         } else {
 1170:             $output .= '
 1171:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1172:         }
 1173:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1174:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1175:                        &mt($item->{'header'}->[0]->{'col2'});
 1176:             if ($action eq 'serverstatuses') {
 1177:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1178:             } 
 1179:         } else {
 1180:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1181:                        &mt($item->{'header'}->[0]->{'col2'});
 1182:         }
 1183:         $output .= '</td>';
 1184:         if ($item->{'header'}->[0]->{'col3'}) {
 1185:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1186:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1187:                             &mt($item->{'header'}->[0]->{'col3'});
 1188:             } else {
 1189:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1190:                            &mt($item->{'header'}->[0]->{'col3'});
 1191:             }
 1192:             if ($action eq 'serverstatuses') {
 1193:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1194:             }
 1195:             $output .= '</td>';
 1196:         }
 1197:         if ($item->{'header'}->[0]->{'col4'}) {
 1198:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1199:                        &mt($item->{'header'}->[0]->{'col4'});
 1200:         }
 1201:         $output .= '</tr>';
 1202:         $rowtotal ++;
 1203:         if ($action eq 'quotas') {
 1204:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1205:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1206:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1207:                  ($action eq 'ltitools') || ($action eq 'lti') ||
 1208:                  ($action eq 'proctoring')) {
 1209:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1210:         }
 1211:     }
 1212:     $output .= '
 1213:    </table>
 1214:   </td>
 1215:  </tr>
 1216: </table><br />';
 1217:     return ($output,$rowtotal);
 1218: }
 1219: 
 1220: sub print_login {
 1221:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1222:     my ($css_class,$datatable);
 1223:     my %choices = &login_choices();
 1224: 
 1225:     if ($caller eq 'service') {
 1226:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1227:         my $choice = $choices{'disallowlogin'};
 1228:         $css_class = ' class="LC_odd_row"';
 1229:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1230:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1231:                       '<th>'.$choices{'server'}.'</th>'.
 1232:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1233:                       '<th>'.$choices{'custompath'}.'</th>'.
 1234:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1235:         my %disallowed;
 1236:         if (ref($settings) eq 'HASH') {
 1237:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1238:                %disallowed = %{$settings->{'loginvia'}};
 1239:             }
 1240:         }
 1241:         foreach my $lonhost (sort(keys(%servers))) {
 1242:             my $direct = 'selected="selected"';
 1243:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1244:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1245:                     $direct = '';
 1246:                 }
 1247:             }
 1248:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1249:                           '<td><select name="'.$lonhost.'_server">'.
 1250:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1251:                           '</option>';
 1252:             foreach my $hostid (sort(keys(%servers))) {
 1253:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1254:                 my $selected = '';
 1255:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1256:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1257:                         $selected = 'selected="selected"';
 1258:                     }
 1259:                 }
 1260:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1261:                               $servers{$hostid}.'</option>';
 1262:             }
 1263:             $datatable .= '</select></td>'.
 1264:                           '<td><select name="'.$lonhost.'_serverpath">';
 1265:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1266:                 my $pathname = $path;
 1267:                 if ($path eq 'custom') {
 1268:                     $pathname = &mt('Custom Path').' ->';
 1269:                 }
 1270:                 my $selected = '';
 1271:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1272:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1273:                         $selected = 'selected="selected"';
 1274:                     }
 1275:                 } elsif ($path eq '') {
 1276:                     $selected = 'selected="selected"';
 1277:                 }
 1278:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1279:             }
 1280:             $datatable .= '</select></td>';
 1281:             my ($custom,$exempt);
 1282:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1283:                 $custom = $disallowed{$lonhost}{'custompath'};
 1284:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1285:             }
 1286:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1287:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1288:                           '</tr>';
 1289:         }
 1290:         $datatable .= '</table></td></tr>';
 1291:         return $datatable;
 1292:     } elsif ($caller eq 'page') {
 1293:         my %defaultchecked = ( 
 1294:                                'coursecatalog' => 'on',
 1295:                                'helpdesk'      => 'on',
 1296:                                'adminmail'     => 'off',
 1297:                                'newuser'       => 'off',
 1298:                              );
 1299:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1300:         my (%checkedon,%checkedoff);
 1301:         foreach my $item (@toggles) {
 1302:             if ($defaultchecked{$item} eq 'on') { 
 1303:                 $checkedon{$item} = ' checked="checked" ';
 1304:                 $checkedoff{$item} = ' ';
 1305:             } elsif ($defaultchecked{$item} eq 'off') {
 1306:                 $checkedoff{$item} = ' checked="checked" ';
 1307:                 $checkedon{$item} = ' ';
 1308:             }
 1309:         }
 1310:         my @images = ('img','logo','domlogo','login');
 1311:         my @logintext = ('textcol','bgcol');
 1312:         my @bgs = ('pgbg','mainbg','sidebg');
 1313:         my @links = ('link','alink','vlink');
 1314:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1315:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1316:         my (%is_custom,%designs);
 1317:         my %defaults = (
 1318:                        font => $defaultdesign{'login.font'},
 1319:                        );
 1320:         foreach my $item (@images) {
 1321:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1322:             $defaults{'showlogo'}{$item} = 1;
 1323:         }
 1324:         foreach my $item (@bgs) {
 1325:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1326:         }
 1327:         foreach my $item (@logintext) {
 1328:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1329:         }
 1330:         foreach my $item (@links) {
 1331:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1332:         }
 1333:         if (ref($settings) eq 'HASH') {
 1334:             foreach my $item (@toggles) {
 1335:                 if ($settings->{$item} eq '1') {
 1336:                     $checkedon{$item} =  ' checked="checked" ';
 1337:                     $checkedoff{$item} = ' ';
 1338:                 } elsif ($settings->{$item} eq '0') {
 1339:                     $checkedoff{$item} =  ' checked="checked" ';
 1340:                     $checkedon{$item} = ' ';
 1341:                 }
 1342:             }
 1343:             foreach my $item (@images) {
 1344:                 if (defined($settings->{$item})) {
 1345:                     $designs{$item} = $settings->{$item};
 1346:                     $is_custom{$item} = 1;
 1347:                 }
 1348:                 if (defined($settings->{'showlogo'}{$item})) {
 1349:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1350:                 }
 1351:             }
 1352:             foreach my $item (@logintext) {
 1353:                 if ($settings->{$item} ne '') {
 1354:                     $designs{'logintext'}{$item} = $settings->{$item};
 1355:                     $is_custom{$item} = 1;
 1356:                 }
 1357:             }
 1358:             if ($settings->{'font'} ne '') {
 1359:                 $designs{'font'} = $settings->{'font'};
 1360:                 $is_custom{'font'} = 1;
 1361:             }
 1362:             foreach my $item (@bgs) {
 1363:                 if ($settings->{$item} ne '') {
 1364:                     $designs{'bgs'}{$item} = $settings->{$item};
 1365:                     $is_custom{$item} = 1;
 1366:                 }
 1367:             }
 1368:             foreach my $item (@links) {
 1369:                 if ($settings->{$item} ne '') {
 1370:                     $designs{'links'}{$item} = $settings->{$item};
 1371:                     $is_custom{$item} = 1;
 1372:                 }
 1373:             }
 1374:         } else {
 1375:             if ($designhash{$dom.'.login.font'} ne '') {
 1376:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1377:                 $is_custom{'font'} = 1;
 1378:             }
 1379:             foreach my $item (@images) {
 1380:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1381:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1382:                     $is_custom{$item} = 1;
 1383:                 }
 1384:             }
 1385:             foreach my $item (@bgs) {
 1386:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1387:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1388:                     $is_custom{$item} = 1;
 1389:                 }
 1390:             }
 1391:             foreach my $item (@links) {
 1392:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1393:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1394:                     $is_custom{$item} = 1;
 1395:                 }
 1396:             }
 1397:         }
 1398:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1399:                                                       logo => 'Institution Logo',
 1400:                                                       domlogo => 'Domain Logo',
 1401:                                                       login => 'Login box');
 1402:         my $itemcount = 1;
 1403:         foreach my $item (@toggles) {
 1404:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1405:             $datatable .=  
 1406:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1407:                 '</td><td>'.
 1408:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1409:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1410:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1411:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1412:                 '</tr>';
 1413:             $itemcount ++;
 1414:         }
 1415:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1416:         $datatable .= '</tr></table></td></tr>';
 1417:     } elsif ($caller eq 'help') {
 1418:         my ($defaulturl,$defaulttype,%url,%type,%lt,%langchoices);
 1419:         my $switchserver = &check_switchserver($dom,$confname);
 1420:         my $itemcount = 1;
 1421:         $defaulturl = '/adm/loginproblems.html';
 1422:         $defaulttype = 'default';
 1423:         %lt = &Apache::lonlocal::texthash (
 1424:                      del     => 'Delete?',
 1425:                      rep     => 'Replace:',
 1426:                      upl     => 'Upload:',
 1427:                      default => 'Default',
 1428:                      custom  => 'Custom',
 1429:                                              );
 1430:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1431:         my @currlangs;
 1432:         if (ref($settings) eq 'HASH') {
 1433:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1434:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1435:                     next if ($settings->{'helpurl'}{$key} eq '');
 1436:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1437:                     $type{$key} = 'custom';
 1438:                     unless ($key eq 'nolang') {
 1439:                         push(@currlangs,$key);
 1440:                     }
 1441:                 }
 1442:             } elsif ($settings->{'helpurl'} ne '') {
 1443:                 $type{'nolang'} = 'custom';
 1444:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1445:             }
 1446:         }
 1447:         foreach my $lang ('nolang',sort(@currlangs)) {
 1448:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1449:             $datatable .= '<tr'.$css_class.'>';
 1450:             if ($url{$lang} eq '') {
 1451:                 $url{$lang} = $defaulturl;
 1452:             }
 1453:             if ($type{$lang} eq '') {
 1454:                 $type{$lang} = $defaulttype;
 1455:             }
 1456:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1457:             if ($lang eq 'nolang') {
 1458:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1459:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1460:             } else {
 1461:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1462:                                   $langchoices{$lang},
 1463:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1464:             }
 1465:             $datatable .= '</span></td>'."\n".
 1466:                           '<td class="LC_left_item">';
 1467:             if ($type{$lang} eq 'custom') {
 1468:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1469:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1470:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1471:             } else {
 1472:                 $datatable .= $lt{'upl'};
 1473:             }
 1474:             $datatable .='<br />';
 1475:             if ($switchserver) {
 1476:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1477:             } else {
 1478:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1479:             }
 1480:             $datatable .= '</td></tr>';
 1481:             $itemcount ++;
 1482:         }
 1483:         my @addlangs;
 1484:         foreach my $lang (sort(keys(%langchoices))) {
 1485:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1486:             push(@addlangs,$lang);
 1487:         }
 1488:         if (@addlangs > 0) {
 1489:             my %toadd;
 1490:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1491:             $toadd{''} = &mt('Select');
 1492:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1493:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1494:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1495:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1496:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1497:             if ($switchserver) {
 1498:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1499:             } else {
 1500:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1501:             }
 1502:             $datatable .= '</td></tr>';
 1503:             $itemcount ++;
 1504:         }
 1505:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1506:     } elsif ($caller eq 'headtag') {
 1507:         my %domservers = &Apache::lonnet::get_servers($dom);
 1508:         my $choice = $choices{'headtag'};
 1509:         $css_class = ' class="LC_odd_row"';
 1510:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1511:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1512:                       '<th>'.$choices{'current'}.'</th>'.
 1513:                       '<th>'.$choices{'action'}.'</th>'.
 1514:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1515:         my (%currurls,%currexempt);
 1516:         if (ref($settings) eq 'HASH') {
 1517:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1518:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1519:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1520:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1521:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1522:                     }
 1523:                 }
 1524:             }
 1525:         }
 1526:         my %lt = &Apache::lonlocal::texthash(
 1527:                                                del  => 'Delete?',
 1528:                                                rep  => 'Replace:',
 1529:                                                upl  => 'Upload:',
 1530:                                                curr => 'View contents',
 1531:                                                none => 'None',
 1532:         );
 1533:         my $switchserver = &check_switchserver($dom,$confname);
 1534:         foreach my $lonhost (sort(keys(%domservers))) {
 1535:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1536:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1537:             if ($currurls{$lonhost}) {
 1538:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1539:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1540:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1541:                               '">'.$lt{'curr'}.'</a></td>'.
 1542:                               '<td><span class="LC_nobreak"><label>'.
 1543:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1544:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1545:             } else {
 1546:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1547:             }
 1548:             $datatable .='<br />';
 1549:             if ($switchserver) {
 1550:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1551:             } else {
 1552:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1553:             }
 1554:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1555:         }
 1556:         $datatable .= '</table></td></tr>';
 1557:     }
 1558:     return $datatable;
 1559: }
 1560: 
 1561: sub login_choices {
 1562:     my %choices =
 1563:         &Apache::lonlocal::texthash (
 1564:             coursecatalog => 'Display Course/Community Catalog link?',
 1565:             adminmail     => "Display Administrator's E-mail Address?",
 1566:             helpdesk      => 'Display "Contact Helpdesk" link',
 1567:             disallowlogin => "Login page requests redirected",
 1568:             hostid        => "Server",
 1569:             server        => "Redirect to:",
 1570:             serverpath    => "Path",
 1571:             custompath    => "Custom", 
 1572:             exempt        => "Exempt IP(s)",
 1573:             directlogin   => "No redirect",
 1574:             newuser       => "Link to create a user account",
 1575:             img           => "Header",
 1576:             logo          => "Main Logo",
 1577:             domlogo       => "Domain Logo",
 1578:             login         => "Log-in Header", 
 1579:             textcol       => "Text color",
 1580:             bgcol         => "Box color",
 1581:             bgs           => "Background colors",
 1582:             links         => "Link colors",
 1583:             font          => "Font color",
 1584:             pgbg          => "Header",
 1585:             mainbg        => "Page",
 1586:             sidebg        => "Login box",
 1587:             link          => "Link",
 1588:             alink         => "Active link",
 1589:             vlink         => "Visited link",
 1590:             headtag       => "Custom markup",
 1591:             action        => "Action",
 1592:             current       => "Current",
 1593:         );
 1594:     return %choices;
 1595: }
 1596: 
 1597: sub print_rolecolors {
 1598:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1599:     my %choices = &color_font_choices();
 1600:     my @bgs = ('pgbg','tabbg','sidebg');
 1601:     my @links = ('link','alink','vlink');
 1602:     my @images = ('img');
 1603:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1604:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1605:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1606:     my (%is_custom,%designs);
 1607:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1608:     if (ref($settings) eq 'HASH') {
 1609:         if (ref($settings->{$role}) eq 'HASH') {
 1610:             if ($settings->{$role}->{'img'} ne '') {
 1611:                 $designs{'img'} = $settings->{$role}->{'img'};
 1612:                 $is_custom{'img'} = 1;
 1613:             }
 1614:             if ($settings->{$role}->{'font'} ne '') {
 1615:                 $designs{'font'} = $settings->{$role}->{'font'};
 1616:                 $is_custom{'font'} = 1;
 1617:             }
 1618:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1619:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1620:                 $is_custom{'fontmenu'} = 1;
 1621:             }
 1622:             foreach my $item (@bgs) {
 1623:                 if ($settings->{$role}->{$item} ne '') {
 1624:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1625:                     $is_custom{$item} = 1;
 1626:                 }
 1627:             }
 1628:             foreach my $item (@links) {
 1629:                 if ($settings->{$role}->{$item} ne '') {
 1630:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1631:                     $is_custom{$item} = 1;
 1632:                 }
 1633:             }
 1634:         }
 1635:     } else {
 1636:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1637:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1638:             $is_custom{'img'} = 1;
 1639:         }
 1640:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1641:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1642:             $is_custom{'fontmenu'} = 1; 
 1643:         }
 1644:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1645:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1646:             $is_custom{'font'} = 1;
 1647:         }
 1648:         foreach my $item (@bgs) {
 1649:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1650:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1651:                 $is_custom{$item} = 1;
 1652:             
 1653:             }
 1654:         }
 1655:         foreach my $item (@links) {
 1656:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1657:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1658:                 $is_custom{$item} = 1;
 1659:             }
 1660:         }
 1661:     }
 1662:     my $itemcount = 1;
 1663:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 1664:     $datatable .= '</tr></table></td></tr>';
 1665:     return $datatable;
 1666: }
 1667: 
 1668: sub role_defaults {
 1669:     my ($role,$bgs,$links,$images,$logintext) = @_;
 1670:     my %defaults;
 1671:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 1672:         return %defaults;
 1673:     }
 1674:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1675:     if ($role eq 'login') {
 1676:         %defaults = (
 1677:                        font => $defaultdesign{$role.'.font'},
 1678:                     );
 1679:         if (ref($logintext) eq 'ARRAY') {
 1680:             foreach my $item (@{$logintext}) {
 1681:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 1682:             }
 1683:         }
 1684:         foreach my $item (@{$images}) {
 1685:             $defaults{'showlogo'}{$item} = 1;
 1686:         }
 1687:     } else {
 1688:         %defaults = (
 1689:                        img => $defaultdesign{$role.'.img'},
 1690:                        font => $defaultdesign{$role.'.font'},
 1691:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 1692:                     );
 1693:     }
 1694:     foreach my $item (@{$bgs}) {
 1695:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 1696:     }
 1697:     foreach my $item (@{$links}) {
 1698:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 1699:     }
 1700:     foreach my $item (@{$images}) {
 1701:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 1702:     }
 1703:     return %defaults;
 1704: }
 1705: 
 1706: sub display_color_options {
 1707:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 1708:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 1709:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 1710:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1711:     my $datatable = '<tr'.$css_class.'>'.
 1712:         '<td>'.$choices->{'font'}.'</td>';
 1713:     if (!$is_custom->{'font'}) {
 1714:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 1715:     } else {
 1716:         $datatable .= '<td>&nbsp;</td>';
 1717:     }
 1718:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 1719: 
 1720:     $datatable .= '<td><span class="LC_nobreak">'.
 1721:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 1722:                   ' value="'.$current_color.'" />&nbsp;'.
 1723:                   '&nbsp;</span></td></tr>';
 1724:     unless ($role eq 'login') { 
 1725:         $datatable .= '<tr'.$css_class.'>'.
 1726:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 1727:         if (!$is_custom->{'fontmenu'}) {
 1728:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 1729:         } else {
 1730:             $datatable .= '<td>&nbsp;</td>';
 1731:         }
 1732: 	$current_color = $designs->{'fontmenu'} ?
 1733: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 1734:         $datatable .= '<td><span class="LC_nobreak">'.
 1735:                       '<input class="colorchooser" type="text" size="10" name="'
 1736: 		      .$role.'_fontmenu"'.
 1737:                       ' value="'.$current_color.'" />&nbsp;'.
 1738:                       '&nbsp;</span></td></tr>';
 1739:     }
 1740:     my $switchserver = &check_switchserver($dom,$confname);
 1741:     foreach my $img (@{$images}) {
 1742: 	$itemcount ++;
 1743:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1744:         $datatable .= '<tr'.$css_class.'>'.
 1745:                       '<td>'.$choices->{$img};
 1746:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors);
 1747:         if ($role eq 'login') {
 1748:             if ($img eq 'login') {
 1749:                 $login_hdr_pick =
 1750:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 1751:                 $logincolors =
 1752:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 1753:                                        $designs,$defaults);
 1754:             } elsif ($img ne 'domlogo') {
 1755:                 $datatable.= &logo_display_options($img,$defaults,$designs);
 1756:             }
 1757:         }
 1758:         $datatable .= '</td>';
 1759:         if ($designs->{$img} ne '') {
 1760:             $imgfile = $designs->{$img};
 1761: 	    $img_import = ($imgfile =~ m{^/adm/});
 1762:         } else {
 1763:             $imgfile = $defaults->{$img};
 1764:         }
 1765:         if ($imgfile) {
 1766:             my ($showfile,$fullsize);
 1767:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 1768:                 my $urldir = $1;
 1769:                 my $filename = $2;
 1770:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 1771:                 if (@info) {
 1772:                     my $thumbfile = 'tn-'.$filename;
 1773:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 1774:                     if (@thumb) {
 1775:                         $showfile = $urldir.'/'.$thumbfile;
 1776:                     } else {
 1777:                         $showfile = $imgfile;
 1778:                     }
 1779:                 } else {
 1780:                     $showfile = '';
 1781:                 }
 1782:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 1783:                 $showfile = $imgfile;
 1784:                 my $imgdir = $1;
 1785:                 my $filename = $2;
 1786:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 1787:                     $showfile = "/$imgdir/tn-".$filename;
 1788:                 } else {
 1789:                     my $input = $londocroot.$imgfile;
 1790:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 1791:                     if (!-e $output) {
 1792:                         my ($width,$height) = &thumb_dimensions();
 1793:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 1794:                         if ($fullwidth ne '' && $fullheight ne '') {
 1795:                             if ($fullwidth > $width && $fullheight > $height) { 
 1796:                                 my $size = $width.'x'.$height;
 1797:                                 my @args = ('convert','-sample',$size,$input,$output);
 1798:                                 system({$args[0]} @args);
 1799:                                 $showfile = "/$imgdir/tn-".$filename;
 1800:                             }
 1801:                         }
 1802:                     }
 1803:                 }
 1804:             }
 1805:             if ($showfile) {
 1806:                 if ($showfile =~ m{^/(adm|res)/}) {
 1807:                     if ($showfile =~ m{^/res/}) {
 1808:                         my $local_showfile =
 1809:                             &Apache::lonnet::filelocation('',$showfile);
 1810:                         &Apache::lonnet::repcopy($local_showfile);
 1811:                     }
 1812:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 1813:                 }
 1814:                 if ($imgfile) {
 1815:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 1816:                         if ($imgfile =~ m{^/res/}) {
 1817:                             my $local_imgfile =
 1818:                                 &Apache::lonnet::filelocation('',$imgfile);
 1819:                             &Apache::lonnet::repcopy($local_imgfile);
 1820:                         }
 1821:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 1822:                     } else {
 1823:                         $fullsize = $imgfile;
 1824:                     }
 1825:                 }
 1826:                 $datatable .= '<td>';
 1827:                 if ($img eq 'login') {
 1828:                     $datatable .= $login_hdr_pick;
 1829:                 } 
 1830:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 1831:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 1832:             } else {
 1833:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1834:                               &mt('Upload:').'<br />';
 1835:             }
 1836:         } else {
 1837:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 1838:                           &mt('Upload:').'<br />';
 1839:         }
 1840:         if ($switchserver) {
 1841:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1842:         } else {
 1843:             if ($img ne 'login') { # suppress file selection for Log-in header
 1844:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 1845:             }
 1846:         }
 1847:         $datatable .= '</td></tr>';
 1848:     }
 1849:     $itemcount ++;
 1850:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1851:     $datatable .= '<tr'.$css_class.'>'.
 1852:                   '<td>'.$choices->{'bgs'}.'</td>';
 1853:     my $bgs_def;
 1854:     foreach my $item (@{$bgs}) {
 1855:         if (!$is_custom->{$item}) {
 1856:             $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>';
 1857:         }
 1858:     }
 1859:     if ($bgs_def) {
 1860:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 1861:     } else {
 1862:         $datatable .= '<td>&nbsp;</td>';
 1863:     }
 1864:     $datatable .= '<td class="LC_right_item">'.
 1865:                   '<table border="0"><tr>';
 1866: 
 1867:     foreach my $item (@{$bgs}) {
 1868:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 1869: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 1870:         if ($designs->{'bgs'}{$item}) {
 1871:             $datatable .= '&nbsp;';
 1872:         }
 1873:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1874:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1875:     }
 1876:     $datatable .= '</tr></table></td></tr>';
 1877:     $itemcount ++;
 1878:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1879:     $datatable .= '<tr'.$css_class.'>'.
 1880:                   '<td>'.$choices->{'links'}.'</td>';
 1881:     my $links_def;
 1882:     foreach my $item (@{$links}) {
 1883:         if (!$is_custom->{$item}) {
 1884:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 1885:         }
 1886:     }
 1887:     if ($links_def) {
 1888:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 1889:     } else {
 1890:         $datatable .= '<td>&nbsp;</td>';
 1891:     }
 1892:     $datatable .= '<td class="LC_right_item">'.
 1893:                   '<table border="0"><tr>';
 1894:     foreach my $item (@{$links}) {
 1895: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 1896:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 1897:         if ($designs->{'links'}{$item}) {
 1898:             $datatable.='&nbsp;';
 1899:         }
 1900:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 1901:                       '" /></td>';
 1902:     }
 1903:     $$rowtotal += $itemcount;
 1904:     return $datatable;
 1905: }
 1906: 
 1907: sub logo_display_options {
 1908:     my ($img,$defaults,$designs) = @_;
 1909:     my $checkedon;
 1910:     if (ref($defaults) eq 'HASH') {
 1911:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 1912:             if ($defaults->{'showlogo'}{$img}) {
 1913:                 $checkedon = 'checked="checked" ';     
 1914:             }
 1915:         } 
 1916:     }
 1917:     if (ref($designs) eq 'HASH') {
 1918:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 1919:             if (defined($designs->{'showlogo'}{$img})) {
 1920:                 if ($designs->{'showlogo'}{$img} == 0) {
 1921:                     $checkedon = '';
 1922:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 1923:                     $checkedon = 'checked="checked" ';
 1924:                 }
 1925:             }
 1926:         }
 1927:     }
 1928:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 1929:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 1930:            &mt('show').'</label>'."\n";
 1931: }
 1932: 
 1933: sub login_header_options  {
 1934:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 1935:     my $output = '';
 1936:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 1937:         $output .= &mt('Text default(s):').'<br />';
 1938:         if (!$is_custom->{'textcol'}) {
 1939:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 1940:                        '&nbsp;&nbsp;&nbsp;';
 1941:         }
 1942:         if (!$is_custom->{'bgcol'}) {
 1943:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 1944:                        '<span id="css_'.$role.'_font" style="background-color: '.
 1945:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 1946:         }
 1947:         $output .= '<br />';
 1948:     }
 1949:     $output .='<br />';
 1950:     return $output;
 1951: }
 1952: 
 1953: sub login_text_colors {
 1954:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 1955:     my $color_menu = '<table border="0"><tr>';
 1956:     foreach my $item (@{$logintext}) {
 1957:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 1958:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 1959:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 1960:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 1961:     }
 1962:     $color_menu .= '</tr></table><br />';
 1963:     return $color_menu;
 1964: }
 1965: 
 1966: sub image_changes {
 1967:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 1968:     my $output;
 1969:     if ($img eq 'login') {
 1970:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 1971:     } elsif (!$is_custom) {
 1972:         if ($img ne 'domlogo') {
 1973:             $output = &mt('Default image:').'<br />';
 1974:         } else {
 1975:             $output = &mt('Default in use:').'<br />';
 1976:         }
 1977:     }
 1978:     if ($img ne 'login') {
 1979:         if ($img_import) {
 1980:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 1981:         }
 1982:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 1983:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 1984:         if ($is_custom) {
 1985:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 1986:                        '<input type="checkbox" name="'.
 1987:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 1988:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 1989:         } else {
 1990:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 1991:         }
 1992:     }
 1993:     return $output;
 1994: }
 1995: 
 1996: sub print_quotas {
 1997:     my ($dom,$settings,$rowtotal,$action) = @_;
 1998:     my $context;
 1999:     if ($action eq 'quotas') {
 2000:         $context = 'tools';
 2001:     } else {
 2002:         $context = $action;
 2003:     }
 2004:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2005:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2006:     my $typecount = 0;
 2007:     my ($css_class,%titles);
 2008:     if ($context eq 'requestcourses') {
 2009:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2010:         @options =('norequest','approval','validate','autolimit');
 2011:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2012:         %titles = &courserequest_titles();
 2013:     } elsif ($context eq 'requestauthor') {
 2014:         @usertools = ('author');
 2015:         @options = ('norequest','approval','automatic');
 2016:         %titles = &authorrequest_titles();
 2017:     } else {
 2018:         @usertools = ('aboutme','blog','webdav','portfolio');
 2019:         %titles = &tool_titles();
 2020:     }
 2021:     if (ref($types) eq 'ARRAY') {
 2022:         foreach my $type (@{$types}) {
 2023:             my ($currdefquota,$currauthorquota);
 2024:             unless (($context eq 'requestcourses') ||
 2025:                     ($context eq 'requestauthor')) {
 2026:                 if (ref($settings) eq 'HASH') {
 2027:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2028:                         $currdefquota = $settings->{defaultquota}->{$type};
 2029:                     } else {
 2030:                         $currdefquota = $settings->{$type};
 2031:                     }
 2032:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2033:                         $currauthorquota = $settings->{authorquota}->{$type};
 2034:                     }
 2035:                 }
 2036:             }
 2037:             if (defined($usertypes->{$type})) {
 2038:                 $typecount ++;
 2039:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2040:                 $datatable .= '<tr'.$css_class.'>'.
 2041:                               '<td>'.$usertypes->{$type}.'</td>'.
 2042:                               '<td class="LC_left_item">';
 2043:                 if ($context eq 'requestcourses') {
 2044:                     $datatable .= '<table><tr>';
 2045:                 }
 2046:                 my %cell;  
 2047:                 foreach my $item (@usertools) {
 2048:                     if ($context eq 'requestcourses') {
 2049:                         my ($curroption,$currlimit);
 2050:                         if (ref($settings) eq 'HASH') {
 2051:                             if (ref($settings->{$item}) eq 'HASH') {
 2052:                                 $curroption = $settings->{$item}->{$type};
 2053:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2054:                                     $currlimit = $1; 
 2055:                                 }
 2056:                             }
 2057:                         }
 2058:                         if (!$curroption) {
 2059:                             $curroption = 'norequest';
 2060:                         }
 2061:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2062:                         foreach my $option (@options) {
 2063:                             my $val = $option;
 2064:                             if ($option eq 'norequest') {
 2065:                                 $val = 0;  
 2066:                             }
 2067:                             if ($option eq 'validate') {
 2068:                                 my $canvalidate = 0;
 2069:                                 if (ref($validations{$item}) eq 'HASH') { 
 2070:                                     if ($validations{$item}{$type}) {
 2071:                                         $canvalidate = 1;
 2072:                                     }
 2073:                                 }
 2074:                                 next if (!$canvalidate);
 2075:                             }
 2076:                             my $checked = '';
 2077:                             if ($option eq $curroption) {
 2078:                                 $checked = ' checked="checked"';
 2079:                             } elsif ($option eq 'autolimit') {
 2080:                                 if ($curroption =~ /^autolimit/) {
 2081:                                     $checked = ' checked="checked"';
 2082:                                 }                       
 2083:                             } 
 2084:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2085:                                   '<input type="radio" name="crsreq_'.$item.
 2086:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2087:                                   $titles{$option}.'</label>';
 2088:                             if ($option eq 'autolimit') {
 2089:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2090:                                                 $item.'_limit_'.$type.'" size="1" '.
 2091:                                                 'value="'.$currlimit.'" />';
 2092:                             }
 2093:                             $cell{$item} .= '</span> ';
 2094:                             if ($option eq 'autolimit') {
 2095:                                 $cell{$item} .= $titles{'unlimited'};
 2096:                             }
 2097:                         }
 2098:                     } elsif ($context eq 'requestauthor') {
 2099:                         my $curroption;
 2100:                         if (ref($settings) eq 'HASH') {
 2101:                             $curroption = $settings->{$type};
 2102:                         }
 2103:                         if (!$curroption) {
 2104:                             $curroption = 'norequest';
 2105:                         }
 2106:                         foreach my $option (@options) {
 2107:                             my $val = $option;
 2108:                             if ($option eq 'norequest') {
 2109:                                 $val = 0;
 2110:                             }
 2111:                             my $checked = '';
 2112:                             if ($option eq $curroption) {
 2113:                                 $checked = ' checked="checked"';
 2114:                             }
 2115:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2116:                                   '<input type="radio" name="authorreq_'.$type.
 2117:                                   '" value="'.$val.'"'.$checked.' />'.
 2118:                                   $titles{$option}.'</label></span>&nbsp; ';
 2119:                         }
 2120:                     } else {
 2121:                         my $checked = 'checked="checked" ';
 2122:                         if (ref($settings) eq 'HASH') {
 2123:                             if (ref($settings->{$item}) eq 'HASH') {
 2124:                                 if ($settings->{$item}->{$type} == 0) {
 2125:                                     $checked = '';
 2126:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2127:                                     $checked =  'checked="checked" ';
 2128:                                 }
 2129:                             }
 2130:                         }
 2131:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2132:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2133:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2134:                                       '</label></span>&nbsp; ';
 2135:                     }
 2136:                 }
 2137:                 if ($context eq 'requestcourses') {
 2138:                     $datatable .= '</tr><tr>';
 2139:                     foreach my $item (@usertools) {
 2140:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2141:                     }
 2142:                     $datatable .= '</tr></table>';
 2143:                 }
 2144:                 $datatable .= '</td>';
 2145:                 unless (($context eq 'requestcourses') ||
 2146:                         ($context eq 'requestauthor')) {
 2147:                     $datatable .= 
 2148:                               '<td class="LC_right_item">'.
 2149:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2150:                               '<input type="text" name="quota_'.$type.
 2151:                               '" value="'.$currdefquota.
 2152:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2153:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2154:                               '<input type="text" name="authorquota_'.$type.
 2155:                               '" value="'.$currauthorquota.
 2156:                               '" size="5" /></span></td>';
 2157:                 }
 2158:                 $datatable .= '</tr>';
 2159:             }
 2160:         }
 2161:     }
 2162:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2163:         $defaultquota = '20';
 2164:         $authorquota = '500';
 2165:         if (ref($settings) eq 'HASH') {
 2166:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2167:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2168:             } elsif (defined($settings->{'default'})) {
 2169:                 $defaultquota = $settings->{'default'};
 2170:             }
 2171:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2172:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2173:             }
 2174:         }
 2175:     }
 2176:     $typecount ++;
 2177:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2178:     $datatable .= '<tr'.$css_class.'>'.
 2179:                   '<td>'.$othertitle.'</td>'.
 2180:                   '<td class="LC_left_item">';
 2181:     if ($context eq 'requestcourses') {
 2182:         $datatable .= '<table><tr>';
 2183:     }
 2184:     my %defcell;
 2185:     foreach my $item (@usertools) {
 2186:         if ($context eq 'requestcourses') {
 2187:             my ($curroption,$currlimit);
 2188:             if (ref($settings) eq 'HASH') {
 2189:                 if (ref($settings->{$item}) eq 'HASH') {
 2190:                     $curroption = $settings->{$item}->{'default'};
 2191:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2192:                         $currlimit = $1;
 2193:                     }
 2194:                 }
 2195:             }
 2196:             if (!$curroption) {
 2197:                 $curroption = 'norequest';
 2198:             }
 2199:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2200:             foreach my $option (@options) {
 2201:                 my $val = $option;
 2202:                 if ($option eq 'norequest') {
 2203:                     $val = 0;
 2204:                 }
 2205:                 if ($option eq 'validate') {
 2206:                     my $canvalidate = 0;
 2207:                     if (ref($validations{$item}) eq 'HASH') {
 2208:                         if ($validations{$item}{'default'}) {
 2209:                             $canvalidate = 1;
 2210:                         }
 2211:                     }
 2212:                     next if (!$canvalidate);
 2213:                 }
 2214:                 my $checked = '';
 2215:                 if ($option eq $curroption) {
 2216:                     $checked = ' checked="checked"';
 2217:                 } elsif ($option eq 'autolimit') {
 2218:                     if ($curroption =~ /^autolimit/) {
 2219:                         $checked = ' checked="checked"';
 2220:                     }
 2221:                 }
 2222:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2223:                                   '<input type="radio" name="crsreq_'.$item.
 2224:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2225:                                   $titles{$option}.'</label>';
 2226:                 if ($option eq 'autolimit') {
 2227:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2228:                                        $item.'_limit_default" size="1" '.
 2229:                                        'value="'.$currlimit.'" />';
 2230:                 }
 2231:                 $defcell{$item} .= '</span> ';
 2232:                 if ($option eq 'autolimit') {
 2233:                     $defcell{$item} .= $titles{'unlimited'};
 2234:                 }
 2235:             }
 2236:         } elsif ($context eq 'requestauthor') {
 2237:             my $curroption;
 2238:             if (ref($settings) eq 'HASH') {
 2239:                 $curroption = $settings->{'default'};
 2240:             }
 2241:             if (!$curroption) {
 2242:                 $curroption = 'norequest';
 2243:             }
 2244:             foreach my $option (@options) {
 2245:                 my $val = $option;
 2246:                 if ($option eq 'norequest') {
 2247:                     $val = 0;
 2248:                 }
 2249:                 my $checked = '';
 2250:                 if ($option eq $curroption) {
 2251:                     $checked = ' checked="checked"';
 2252:                 }
 2253:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2254:                               '<input type="radio" name="authorreq_default"'.
 2255:                               ' value="'.$val.'"'.$checked.' />'.
 2256:                               $titles{$option}.'</label></span>&nbsp; ';
 2257:             }
 2258:         } else {
 2259:             my $checked = 'checked="checked" ';
 2260:             if (ref($settings) eq 'HASH') {
 2261:                 if (ref($settings->{$item}) eq 'HASH') {
 2262:                     if ($settings->{$item}->{'default'} == 0) {
 2263:                         $checked = '';
 2264:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2265:                         $checked = 'checked="checked" ';
 2266:                     }
 2267:                 }
 2268:             }
 2269:             $datatable .= '<span class="LC_nobreak"><label>'.
 2270:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2271:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2272:                           '</label></span>&nbsp; ';
 2273:         }
 2274:     }
 2275:     if ($context eq 'requestcourses') {
 2276:         $datatable .= '</tr><tr>';
 2277:         foreach my $item (@usertools) {
 2278:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2279:         }
 2280:         $datatable .= '</tr></table>';
 2281:     }
 2282:     $datatable .= '</td>';
 2283:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2284:         $datatable .= '<td class="LC_right_item">'.
 2285:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2286:                       '<input type="text" name="defaultquota" value="'.
 2287:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2288:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2289:                       '<input type="text" name="authorquota" value="'.
 2290:                       $authorquota.'" size="5" /></span></td>';
 2291:     }
 2292:     $datatable .= '</tr>';
 2293:     $typecount ++;
 2294:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2295:     $datatable .= '<tr'.$css_class.'>'.
 2296:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2297:     if ($context eq 'requestcourses') {
 2298:         $datatable .= &mt('(overrides affiliation, if set)').
 2299:                       '</td>'.
 2300:                       '<td class="LC_left_item">'.
 2301:                       '<table><tr>';
 2302:     } else {
 2303:         $datatable .= &mt('(overrides affiliation, if checked)').
 2304:                       '</td>'.
 2305:                       '<td class="LC_left_item" colspan="2">'.
 2306:                       '<br />';
 2307:     }
 2308:     my %advcell;
 2309:     foreach my $item (@usertools) {
 2310:         if ($context eq 'requestcourses') {
 2311:             my ($curroption,$currlimit);
 2312:             if (ref($settings) eq 'HASH') {
 2313:                 if (ref($settings->{$item}) eq 'HASH') {
 2314:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2315:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2316:                         $currlimit = $1;
 2317:                     }
 2318:                 }
 2319:             }
 2320:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2321:             my $checked = '';
 2322:             if ($curroption eq '') {
 2323:                 $checked = ' checked="checked"';
 2324:             }
 2325:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2326:                                '<input type="radio" name="crsreq_'.$item.
 2327:                                '__LC_adv" value=""'.$checked.' />'.
 2328:                                &mt('No override set').'</label></span>&nbsp; ';
 2329:             foreach my $option (@options) {
 2330:                 my $val = $option;
 2331:                 if ($option eq 'norequest') {
 2332:                     $val = 0;
 2333:                 }
 2334:                 if ($option eq 'validate') {
 2335:                     my $canvalidate = 0;
 2336:                     if (ref($validations{$item}) eq 'HASH') {
 2337:                         if ($validations{$item}{'_LC_adv'}) {
 2338:                             $canvalidate = 1;
 2339:                         }
 2340:                     }
 2341:                     next if (!$canvalidate);
 2342:                 }
 2343:                 my $checked = '';
 2344:                 if ($val eq $curroption) {
 2345:                     $checked = ' checked="checked"';
 2346:                 } elsif ($option eq 'autolimit') {
 2347:                     if ($curroption =~ /^autolimit/) {
 2348:                         $checked = ' checked="checked"';
 2349:                     }
 2350:                 }
 2351:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2352:                                   '<input type="radio" name="crsreq_'.$item.
 2353:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2354:                                   $titles{$option}.'</label>';
 2355:                 if ($option eq 'autolimit') {
 2356:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2357:                                        $item.'_limit__LC_adv" size="1" '.
 2358:                                        'value="'.$currlimit.'" />';
 2359:                 }
 2360:                 $advcell{$item} .= '</span> ';
 2361:                 if ($option eq 'autolimit') {
 2362:                     $advcell{$item} .= $titles{'unlimited'};
 2363:                 }
 2364:             }
 2365:         } elsif ($context eq 'requestauthor') {
 2366:             my $curroption;
 2367:             if (ref($settings) eq 'HASH') {
 2368:                 $curroption = $settings->{'_LC_adv'};
 2369:             }
 2370:             my $checked = '';
 2371:             if ($curroption eq '') {
 2372:                 $checked = ' checked="checked"';
 2373:             }
 2374:             $datatable .= '<span class="LC_nobreak"><label>'.
 2375:                           '<input type="radio" name="authorreq__LC_adv"'.
 2376:                           ' value=""'.$checked.' />'.
 2377:                           &mt('No override set').'</label></span>&nbsp; ';
 2378:             foreach my $option (@options) {
 2379:                 my $val = $option;
 2380:                 if ($option eq 'norequest') {
 2381:                     $val = 0;
 2382:                 }
 2383:                 my $checked = '';
 2384:                 if ($val eq $curroption) {
 2385:                     $checked = ' checked="checked"';
 2386:                 }
 2387:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2388:                               '<input type="radio" name="authorreq__LC_adv"'.
 2389:                               ' value="'.$val.'"'.$checked.' />'.
 2390:                               $titles{$option}.'</label></span>&nbsp; ';
 2391:             }
 2392:         } else {
 2393:             my $checked = 'checked="checked" ';
 2394:             if (ref($settings) eq 'HASH') {
 2395:                 if (ref($settings->{$item}) eq 'HASH') {
 2396:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2397:                         $checked = '';
 2398:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2399:                         $checked = 'checked="checked" ';
 2400:                     }
 2401:                 }
 2402:             }
 2403:             $datatable .= '<span class="LC_nobreak"><label>'.
 2404:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2405:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2406:                           '</label></span>&nbsp; ';
 2407:         }
 2408:     }
 2409:     if ($context eq 'requestcourses') {
 2410:         $datatable .= '</tr><tr>';
 2411:         foreach my $item (@usertools) {
 2412:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2413:         }
 2414:         $datatable .= '</tr></table>';
 2415:     }
 2416:     $datatable .= '</td></tr>';
 2417:     $$rowtotal += $typecount;
 2418:     return $datatable;
 2419: }
 2420: 
 2421: sub print_requestmail {
 2422:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2423:     my ($now,$datatable,%currapp);
 2424:     $now = time;
 2425:     if (ref($settings) eq 'HASH') {
 2426:         if (ref($settings->{'notify'}) eq 'HASH') {
 2427:             if ($settings->{'notify'}{'approval'} ne '') {
 2428:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2429:             }
 2430:         }
 2431:     }
 2432:     my $numinrow = 2;
 2433:     my $css_class;
 2434:     if ($$rowtotal%2) {
 2435:         $css_class = 'LC_odd_row';
 2436:     }
 2437:     if ($customcss) {
 2438:         $css_class .= " $customcss";
 2439:     }
 2440:     $css_class =~ s/^\s+//;
 2441:     if ($css_class) {
 2442:         $css_class = ' class="'.$css_class.'"';
 2443:     }
 2444:     if ($rowstyle) {
 2445:         $css_class .= ' style="'.$rowstyle.'"';
 2446:     }
 2447:     my $text;
 2448:     if ($action eq 'requestcourses') {
 2449:         $text = &mt('Receive notification of course requests requiring approval');
 2450:     } elsif ($action eq 'requestauthor') {
 2451:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2452:     } else {
 2453:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2454:     }
 2455:     $datatable = '<tr'.$css_class.'>'.
 2456:                  ' <td>'.$text.'</td>'.
 2457:                  ' <td class="LC_left_item">';
 2458:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2459:                                                  $action.'notifyapproval',%currapp);
 2460:     if ($numdc > 0) {
 2461:         $datatable .= $table;
 2462:     } else {
 2463:         $datatable .= &mt('There are no active Domain Coordinators');
 2464:     }
 2465:     $datatable .='</td></tr>';
 2466:     return $datatable;
 2467: }
 2468: 
 2469: sub print_studentcode {
 2470:     my ($settings,$rowtotal) = @_;
 2471:     my $rownum = 0; 
 2472:     my ($output,%current);
 2473:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2474:     if (ref($settings) eq 'HASH') {
 2475:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2476:             foreach my $type (@crstypes) {
 2477:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2478:             }
 2479:         }
 2480:     }
 2481:     $output .= '<tr>'.
 2482:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2483:                '<td class="LC_left_item">';
 2484:     foreach my $type (@crstypes) {
 2485:         my $check = ' ';
 2486:         if ($current{$type}) {
 2487:             $check = ' checked="checked" ';
 2488:         }
 2489:         $output .= '<span class="LC_nobreak"><label>'.
 2490:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2491:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2492:     }
 2493:     $output .= '</td></tr>';
 2494:     $$rowtotal ++;
 2495:     return $output;
 2496: }
 2497: 
 2498: sub print_textbookcourses {
 2499:     my ($dom,$type,$settings,$rowtotal) = @_;
 2500:     my $rownum = 0;
 2501:     my $css_class;
 2502:     my $itemcount = 1;
 2503:     my $maxnum = 0;
 2504:     my $bookshash;
 2505:     if (ref($settings) eq 'HASH') {
 2506:         $bookshash = $settings->{$type};
 2507:     }
 2508:     my %ordered;
 2509:     if (ref($bookshash) eq 'HASH') {
 2510:         foreach my $item (keys(%{$bookshash})) {
 2511:             if (ref($bookshash->{$item}) eq 'HASH') {
 2512:                 my $num = $bookshash->{$item}{'order'};
 2513:                 $ordered{$num} = $item;
 2514:             }
 2515:         }
 2516:     }
 2517:     my $confname = $dom.'-domainconfig';
 2518:     my $switchserver = &check_switchserver($dom,$confname);
 2519:     my $maxnum = scalar(keys(%ordered));
 2520:     my $datatable;
 2521:     if (keys(%ordered)) {
 2522:         my @items = sort { $a <=> $b } keys(%ordered);
 2523:         for (my $i=0; $i<@items; $i++) {
 2524:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2525:             my $key = $ordered{$items[$i]};
 2526:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2527:             my $coursetitle = $coursehash{'description'};
 2528:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2529:             if (ref($bookshash->{$key}) eq 'HASH') {
 2530:                 $subject = $bookshash->{$key}->{'subject'};
 2531:                 $title = $bookshash->{$key}->{'title'};
 2532:                 if ($type eq 'textbooks') {
 2533:                     $publisher = $bookshash->{$key}->{'publisher'};
 2534:                     $author = $bookshash->{$key}->{'author'};
 2535:                     $image = $bookshash->{$key}->{'image'};
 2536:                     if ($image ne '') {
 2537:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2538:                         my $imagethumb = "$path/tn-".$imagefile;
 2539:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2540:                     }
 2541:                 }
 2542:             }
 2543:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2544:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2545:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2546:             for (my $k=0; $k<=$maxnum; $k++) {
 2547:                 my $vpos = $k+1;
 2548:                 my $selstr;
 2549:                 if ($k == $i) {
 2550:                     $selstr = ' selected="selected" ';
 2551:                 }
 2552:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2553:             }
 2554:             $datatable .= '</select>'.('&nbsp;'x2).
 2555:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2556:                 &mt('Delete?').'</label></span></td>'.
 2557:                 '<td colspan="2">'.
 2558:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2559:                 ('&nbsp;'x2).
 2560:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2561:             if ($type eq 'textbooks') {
 2562:                 $datatable .= ('&nbsp;'x2).
 2563:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2564:                               ('&nbsp;'x2).
 2565:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2566:                               ('&nbsp;'x2).
 2567:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2568:                 if ($image) {
 2569:                     $datatable .= $imgsrc.
 2570:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2571:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2572:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2573:                 }
 2574:                 if ($switchserver) {
 2575:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2576:                 } else {
 2577:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2578:                 }
 2579:             }
 2580:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2581:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2582:                           $coursetitle.'</span></td></tr>'."\n";
 2583:             $itemcount ++;
 2584:         }
 2585:     }
 2586:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2587:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2588:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2589:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2590:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2591:     for (my $k=0; $k<$maxnum+1; $k++) {
 2592:         my $vpos = $k+1;
 2593:         my $selstr;
 2594:         if ($k == $maxnum) {
 2595:             $selstr = ' selected="selected" ';
 2596:         }
 2597:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2598:     }
 2599:     $datatable .= '</select>&nbsp;'."\n".
 2600:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2601:                   '<td colspan="2">'.
 2602:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2603:                   ('&nbsp;'x2).
 2604:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2605:                   ('&nbsp;'x2);
 2606:     if ($type eq 'textbooks') {
 2607:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2608:                       ('&nbsp;'x2).
 2609:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2610:                       ('&nbsp;'x2).
 2611:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2612:         if ($switchserver) {
 2613:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2614:         } else {
 2615:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2616:         }
 2617:         $datatable .= '</span>'."\n";
 2618:     }
 2619:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2620:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2621:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2622:                   &Apache::loncommon::selectcourse_link
 2623:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2624:                   '</span></td>'."\n".
 2625:                   '</tr>'."\n";
 2626:     $itemcount ++;
 2627:     return $datatable;
 2628: }
 2629: 
 2630: sub textbookcourses_javascript {
 2631:     my ($settings) = @_;
 2632:     return unless(ref($settings) eq 'HASH');
 2633:     my (%ordered,%total,%jstext);
 2634:     foreach my $type ('textbooks','templates') {
 2635:         $total{$type} = 0;
 2636:         if (ref($settings->{$type}) eq 'HASH') {
 2637:             foreach my $item (keys(%{$settings->{$type}})) {
 2638:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2639:                     my $num = $settings->{$type}->{$item}{'order'};
 2640:                     $ordered{$type}{$num} = $item;
 2641:                 }
 2642:             }
 2643:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2644:         }
 2645:         my @jsarray = ();
 2646:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2647:             push(@jsarray,$ordered{$type}{$item});
 2648:         }
 2649:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 2650:     }
 2651:     return <<"ENDSCRIPT";
 2652: <script type="text/javascript">
 2653: // <![CDATA[
 2654: function reorderBooks(form,item,caller) {
 2655:     var changedVal;
 2656: $jstext{'textbooks'};
 2657: $jstext{'templates'};
 2658:     var newpos;
 2659:     var maxh;
 2660:     if (caller == 'textbooks') {  
 2661:         newpos = 'textbooks_addbook_pos';
 2662:         maxh = 1 + $total{'textbooks'};
 2663:     } else {
 2664:         newpos = 'templates_addbook_pos';
 2665:         maxh = 1 + $total{'templates'};
 2666:     }
 2667:     var current = new Array;
 2668:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2669:     if (item == newpos) {
 2670:         changedVal = newitemVal;
 2671:     } else {
 2672:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2673:         current[newitemVal] = newpos;
 2674:     }
 2675:     if (caller == 'textbooks') {
 2676:         for (var i=0; i<textbooks.length; i++) {
 2677:             var elementName = 'textbooks_'+textbooks[i];
 2678:             if (elementName != item) {
 2679:                 if (form.elements[elementName]) {
 2680:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2681:                     current[currVal] = elementName;
 2682:                 }
 2683:             }
 2684:         }
 2685:     }
 2686:     if (caller == 'templates') {
 2687:         for (var i=0; i<templates.length; i++) {
 2688:             var elementName = 'templates_'+templates[i];
 2689:             if (elementName != item) {
 2690:                 if (form.elements[elementName]) {
 2691:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2692:                     current[currVal] = elementName;
 2693:                 }
 2694:             }
 2695:         }
 2696:     }
 2697:     var oldVal;
 2698:     for (var j=0; j<maxh; j++) {
 2699:         if (current[j] == undefined) {
 2700:             oldVal = j;
 2701:         }
 2702:     }
 2703:     if (oldVal < changedVal) {
 2704:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2705:            var elementName = current[k];
 2706:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2707:         }
 2708:     } else {
 2709:         for (var k=changedVal; k<oldVal; k++) {
 2710:             var elementName = current[k];
 2711:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2712:         }
 2713:     }
 2714:     return;
 2715: }
 2716: 
 2717: // ]]>
 2718: </script>
 2719: 
 2720: ENDSCRIPT
 2721: }
 2722: 
 2723: sub ltitools_javascript {
 2724:     my ($settings) = @_;
 2725:     my $togglejs = &ltitools_toggle_js();
 2726:     unless (ref($settings) eq 'HASH') {
 2727:         return $togglejs;
 2728:     }
 2729:     my (%ordered,$total,%jstext);
 2730:     $total = 0;
 2731:     foreach my $item (keys(%{$settings})) {
 2732:         if (ref($settings->{$item}) eq 'HASH') {
 2733:             my $num = $settings->{$item}{'order'};
 2734:             $ordered{$num} = $item;
 2735:         }
 2736:     }
 2737:     $total = scalar(keys(%{$settings}));
 2738:     my @jsarray = ();
 2739:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2740:         push(@jsarray,$ordered{$item});
 2741:     }
 2742:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 2743:     return <<"ENDSCRIPT";
 2744: <script type="text/javascript">
 2745: // <![CDATA[
 2746: function reorderLTITools(form,item) {
 2747:     var changedVal;
 2748: $jstext
 2749:     var newpos = 'ltitools_add_pos';
 2750:     var maxh = 1 + $total;
 2751:     var current = new Array;
 2752:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 2753:     if (item == newpos) {
 2754:         changedVal = newitemVal;
 2755:     } else {
 2756:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2757:         current[newitemVal] = newpos;
 2758:     }
 2759:     for (var i=0; i<ltitools.length; i++) {
 2760:         var elementName = 'ltitools_'+ltitools[i];
 2761:         if (elementName != item) {
 2762:             if (form.elements[elementName]) {
 2763:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 2764:                 current[currVal] = elementName;
 2765:             }
 2766:         }
 2767:     }
 2768:     var oldVal;
 2769:     for (var j=0; j<maxh; j++) {
 2770:         if (current[j] == undefined) {
 2771:             oldVal = j;
 2772:         }
 2773:     }
 2774:     if (oldVal < changedVal) {
 2775:         for (var k=oldVal+1; k<=changedVal ; k++) {
 2776:            var elementName = current[k];
 2777:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 2778:         }
 2779:     } else {
 2780:         for (var k=changedVal; k<oldVal; k++) {
 2781:             var elementName = current[k];
 2782:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 2783:         }
 2784:     }
 2785:     return;
 2786: }
 2787: 
 2788: // ]]>
 2789: </script>
 2790: 
 2791: $togglejs
 2792: 
 2793: ENDSCRIPT
 2794: }
 2795: 
 2796: sub ltitools_toggle_js {
 2797:     return <<"ENDSCRIPT";
 2798: <script type="text/javascript">
 2799: // <![CDATA[
 2800: 
 2801: function toggleLTITools(form,setting,item) {
 2802:     var radioname = '';
 2803:     var divid = '';
 2804:     if ((setting == 'passback') || (setting == 'roster')) {
 2805:         radioname = 'ltitools_'+setting+'_'+item;
 2806:         divid = 'ltitools_'+setting+'time_'+item;
 2807:         var num = form.elements[radioname].length;
 2808:         if (num) {
 2809:             var setvis = '';
 2810:             for (var i=0; i<num; i++) {
 2811:                 if (form.elements[radioname][i].checked) {
 2812:                     if (form.elements[radioname][i].value == '1') {
 2813:                         if (document.getElementById(divid)) {
 2814:                             document.getElementById(divid).style.display = 'inline-block';
 2815:                         }
 2816:                         setvis = 1;
 2817:                     }
 2818:                     break;
 2819:                 }
 2820:             }
 2821:         }
 2822:         if (!setvis) {
 2823:             if (document.getElementById(divid)) {
 2824:                 document.getElementById(divid).style.display = 'none';
 2825:             }
 2826:         }
 2827:     }
 2828:     if (setting == 'user') {
 2829:         divid = 'ltitools_'+setting+'_div_'+item;
 2830:         var checkid = 'ltitools_'+setting+'_field_'+item;
 2831:         if (document.getElementById(divid)) {
 2832:             if (document.getElementById(checkid)) {
 2833:                 if (document.getElementById(checkid).checked) {
 2834:                     document.getElementById(divid).style.display = 'inline-block';
 2835:                 } else {
 2836:                     document.getElementById(divid).style.display = 'none';
 2837:                 }
 2838:             }
 2839:         }
 2840:     }
 2841:     return;
 2842: }
 2843: // ]]>
 2844: </script>
 2845: 
 2846: ENDSCRIPT
 2847: }
 2848: 
 2849: sub wafproxy_javascript {
 2850:     my ($dom) = @_;
 2851:     return <<"ENDSCRIPT";
 2852: <script type="text/javascript">
 2853: // <![CDATA[
 2854: function updateWAF() {
 2855:     if (document.getElementById('wafproxy_remoteip')) {
 2856:         var wafremote = 0;
 2857:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 2858:             wafremote = 1;
 2859:         }
 2860:         var fields = new Array('header','trust');
 2861:         for (var i=0; i<fields.length; i++) {
 2862:             if (document.getElementById('wafproxy_'+fields[i])) {
 2863:                 if (wafremote == 1) {
 2864:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 2865:                 }
 2866:                 else {
 2867:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 2868:                 }
 2869:             }
 2870:         }
 2871:         if (document.getElementById('wafproxyranges_$dom')) {
 2872:             if (wafremote == 1) {
 2873:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2874:             } else {
 2875:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2876:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 2877:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 2878:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2879:                         }
 2880:                     }
 2881:                 }
 2882:             }
 2883:         }
 2884:     }
 2885:     return;
 2886: }
 2887: 
 2888: function checkWAF() {
 2889:     if (document.getElementById('wafproxy_remoteip')) {
 2890:         var wafvpn = 0;
 2891:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 2892:             if (document.display.wafproxy_vpnaccess[i].checked) {
 2893:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 2894:                     wafvpn = 1;
 2895:                 }
 2896:                 break;
 2897:             }
 2898:         }
 2899:         var vpn = new Array('vpnint','vpnext');
 2900:         for (var i=0; i<vpn.length; i++) {
 2901:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 2902:                 if (wafvpn == 1) {
 2903:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 2904:                 }
 2905:                 else {
 2906:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 2907:                 }
 2908:             }
 2909:         }
 2910:         if (document.getElementById('wafproxyranges_$dom')) {
 2911:             if (wafvpn == 1) {
 2912:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 2913:             }
 2914:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 2915:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 2916:             }
 2917:         }
 2918:     }
 2919:     return;
 2920: }
 2921: 
 2922: function toggleWAF() {
 2923:     if (document.getElementById('wafproxy_table')) {
 2924:         var wafproxy = 0;
 2925:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 2926:              if (document.display.wafproxy_${dom}[i].checked) {
 2927:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 2928:                      wafproxy = 1;
 2929:                      break;
 2930:                 }
 2931:             }
 2932:         }
 2933:         if (wafproxy == 1) {
 2934:             document.getElementById('wafproxy_table').style.display='inline';
 2935:         }
 2936:         else {
 2937:            document.getElementById('wafproxy_table').style.display='none';
 2938:         }
 2939:         if (document.getElementById('wafproxyrow_${dom}')) {
 2940:             if (wafproxy == 1) {
 2941:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 2942:             }
 2943:             else {
 2944:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 2945:             }
 2946:         }
 2947:         if (document.getElementById('nowafproxyrow_$dom')) {
 2948:             if (wafproxy == 1) {
 2949:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 2950:             }
 2951:             else {
 2952:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 2953:             }
 2954:         }
 2955:     }
 2956:     return;
 2957: }
 2958: // ]]>
 2959: </script>
 2960: 
 2961: ENDSCRIPT
 2962: }
 2963: 
 2964: sub proctoring_javascript {
 2965:     my ($settings) = @_;
 2966:     my (%ordered,$total,%jstext);
 2967:     $total = 0;
 2968:     if (ref($settings) eq 'HASH') {
 2969:         foreach my $item (keys(%{$settings})) {
 2970:             if (ref($settings->{$item}) eq 'HASH') {
 2971:                 my $num = $settings->{$item}{'order'};
 2972:                 $ordered{$num} = $item;
 2973:             }
 2974:         }
 2975:         $total = scalar(keys(%{$settings}));
 2976:     } else {
 2977:         %ordered = (
 2978:                        0 => 'proctorio',
 2979:                        1 => 'examity',
 2980:                    );
 2981:         $total = 2; 
 2982:     }
 2983:     my @jsarray = ();
 2984:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 2985:         push(@jsarray,$ordered{$item});
 2986:     }
 2987:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 2988:     return <<"ENDSCRIPT";
 2989: <script type="text/javascript">
 2990: // <![CDATA[
 2991: function reorderProctoring(form,item) {
 2992:     var changedVal;
 2993: $jstext
 2994:     var maxh = $total;
 2995:     var current = new Array;
 2996:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 2997:     for (var i=0; i<proctors.length; i++) {
 2998:         var elementName = 'proctoring_pos_'+proctors[i];
 2999:         if (elementName != item) {
 3000:             if (form.elements[elementName]) {
 3001:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3002:                 current[currVal] = elementName;
 3003:             }
 3004:         }
 3005:     }
 3006:     var oldVal;
 3007:     for (var j=0; j<maxh; j++) {
 3008:         if (current[j] == undefined) {
 3009:             oldVal = j;
 3010:         }
 3011:     }
 3012:     if (oldVal < changedVal) {
 3013:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3014:            var elementName = current[k];
 3015:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3016:         }
 3017:     } else {
 3018:         for (var k=changedVal; k<oldVal; k++) {
 3019:             var elementName = current[k];
 3020:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3021:         }
 3022:     }
 3023:     return;
 3024: }
 3025: 
 3026: function toggleProctoring(form,item) {
 3027:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3028:     if (fieldsets.length) {
 3029:         var radioname = 'proctoring_available_'+item;
 3030:         var num = form.elements[radioname].length;
 3031:         if (num) {
 3032:             var setvis = '';
 3033:             for (var i=0; i<num; i++) {
 3034:                 if (form.elements[radioname][i].checked) {
 3035:                     if (form.elements[radioname][i].value == '1') {
 3036:                        setvis = 1;
 3037:                        break;
 3038:                     }
 3039:                 }
 3040:             }
 3041:             for (var j=0; j<fieldsets.length; j++) {
 3042:                 if (setvis) {
 3043:                     fieldsets[j].style.display = 'block';
 3044:                 } else {
 3045:                     fieldsets[j].style.display = 'none';
 3046:                 }
 3047:             }
 3048:         }
 3049:     }
 3050:     return;
 3051: }
 3052: 
 3053: // ]]>
 3054: </script>
 3055: 
 3056: ENDSCRIPT
 3057: }
 3058: 
 3059: 
 3060: sub lti_javascript {
 3061:     my ($settings) = @_;
 3062:     my $togglejs = &lti_toggle_js();
 3063:     unless (ref($settings) eq 'HASH') {
 3064:         return $togglejs;
 3065:     }
 3066:     my (%ordered,$total,%jstext);
 3067:     $total = 0;
 3068:     foreach my $item (keys(%{$settings})) {
 3069:         if (ref($settings->{$item}) eq 'HASH') {
 3070:             my $num = $settings->{$item}{'order'};
 3071:             $ordered{$num} = $item;
 3072:         }
 3073:     }
 3074:     $total = scalar(keys(%{$settings}));
 3075:     my @jsarray = ();
 3076:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3077:         push(@jsarray,$ordered{$item});
 3078:     }
 3079:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3080:     return <<"ENDSCRIPT";
 3081: <script type="text/javascript">
 3082: // <![CDATA[
 3083: function reorderLTI(form,item) {
 3084:     var changedVal;
 3085: $jstext
 3086:     var newpos = 'lti_pos_add';
 3087:     var maxh = 1 + $total;
 3088:     var current = new Array;
 3089:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3090:     if (item == newpos) {
 3091:         changedVal = newitemVal;
 3092:     } else {
 3093:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3094:         current[newitemVal] = newpos;
 3095:     }
 3096:     for (var i=0; i<lti.length; i++) {
 3097:         var elementName = 'lti_pos_'+lti[i];
 3098:         if (elementName != item) {
 3099:             if (form.elements[elementName]) {
 3100:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3101:                 current[currVal] = elementName;
 3102:             }
 3103:         }
 3104:     }
 3105:     var oldVal;
 3106:     for (var j=0; j<maxh; j++) {
 3107:         if (current[j] == undefined) {
 3108:             oldVal = j;
 3109:         }
 3110:     }
 3111:     if (oldVal < changedVal) {
 3112:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3113:            var elementName = current[k];
 3114:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3115:         }
 3116:     } else {
 3117:         for (var k=changedVal; k<oldVal; k++) {
 3118:             var elementName = current[k];
 3119:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3120:         }
 3121:     }
 3122:     return;
 3123: }
 3124: // ]]>
 3125: </script>
 3126: 
 3127: $togglejs
 3128: 
 3129: ENDSCRIPT
 3130: }
 3131: 
 3132: sub lti_toggle_js {
 3133:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3134:                             localauth => 'Local auth argument',
 3135:                             krb       => 'Kerberos domain',
 3136:                          );
 3137:     return <<"ENDSCRIPT";
 3138: <script type="text/javascript">
 3139: // <![CDATA[
 3140: 
 3141: function toggleLTI(form,setting,item) {
 3142:     if (setting == 'requser') {
 3143:         var fieldsets = document.getElementsByClassName('ltioption_'+item);
 3144:         if (fieldsets.length) {
 3145:             var radioname = 'lti_'+setting+'_'+item;
 3146:             var num = form.elements[radioname].length;
 3147:             if (num) {
 3148:                 var setvis = '';
 3149:                 for (var i=0; i<num; i++) {
 3150:                     if (form.elements[radioname][i].checked) {
 3151:                         if (form.elements[radioname][i].value == '1') {
 3152:                            setvis = 1;
 3153:                            break;
 3154:                         }
 3155:                     }
 3156:                 }
 3157:                 for (var j=0; j<fieldsets.length; j++) {
 3158:                     if (setvis) {
 3159:                         fieldsets[j].style.display = 'block';
 3160:                     } else {
 3161:                         fieldsets[j].style.display = 'none';
 3162:                     }
 3163:                 }
 3164:             }
 3165:         }
 3166:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3167:         var radioname = '';
 3168:         var divid = '';
 3169:         if (setting == 'user') {
 3170:             radioname = 'lti_mapuser_'+item;
 3171:             divid = 'lti_userfield_'+item;
 3172:         } else if (setting == 'crs') {
 3173:             radioname = 'lti_mapcrs_'+item;
 3174:             divid = 'lti_crsfield_'+item;
 3175:         } else if (setting == 'callback') {
 3176:             radioname = 'lti_callback_'+item;
 3177:             divid = 'lti_callbackfield_'+item;
 3178:         } else {
 3179:             radioname = 'lti_passback_'+item;
 3180:             divid =  'lti_passback_'+item;
 3181:         }
 3182:         var num = form.elements[radioname].length;
 3183:         if (num) {
 3184:             var setvis = '';
 3185:             for (var i=0; i<num; i++) {
 3186:                if (form.elements[radioname][i].checked) {
 3187:                    if ((setting == 'passback') || (setting == 'callback')) {
 3188:                        if (form.elements[radioname][i].value == '1') {
 3189:                            if (document.getElementById(divid)) {
 3190:                                document.getElementById(divid).style.display = 'inline-block';
 3191:                            }
 3192:                            setvis = 1;
 3193:                            break;
 3194:                        }
 3195:                    } else {
 3196:                        if (form.elements[radioname][i].value == 'other') {
 3197:                            if (document.getElementById(divid)) {
 3198:                                document.getElementById(divid).style.display = 'inline-block';
 3199:                            }
 3200:                            setvis = 1;
 3201:                            break;
 3202:                        }
 3203:                    }
 3204:                } 
 3205:             }
 3206:             if (!setvis) {
 3207:                 if (document.getElementById(divid)) {
 3208:                     document.getElementById(divid).style.display = 'none';
 3209:                 }
 3210:             }
 3211:         }
 3212:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3213:         var numsec = form.elements['lti_crssec_'+item].length;
 3214:         if (numsec) {
 3215:             var setvis = '';
 3216:             for (var i=0; i<numsec; i++) {
 3217:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3218:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3219:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3220:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3221:                             setvis = 1;
 3222:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3223:                             if (numsrcsec) {
 3224:                                 var setsrcvis = '';
 3225:                                 for (var j=0; j<numsrcsec; j++) {
 3226:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3227:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3228:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3229:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3230:                                                 setsrcvis = 1;
 3231:                                             }
 3232:                                         }
 3233:                                     }
 3234:                                 }
 3235:                                 if (!setsrcvis) {
 3236:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3237:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3238:                                     }
 3239:                                 }
 3240:                             }
 3241:                         }
 3242:                     }
 3243:                 }
 3244:             }
 3245:             if (!setvis) {
 3246:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3247:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3248:                 }
 3249:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3250:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3251:                 }
 3252:             }
 3253:         }
 3254:     } else if (setting == 'lcauth') {
 3255:         var numauth = form.elements['lti_lcauth_'+item].length;
 3256:         if (numauth) {
 3257:             for (var i=0; i<numauth; i++) {
 3258:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3259:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3260:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3261:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3262:                         } else {
 3263:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3264:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3265:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3266:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3267:                                 } else {
 3268:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3269:                                 }
 3270:                             }
 3271:                         }
 3272:                     }
 3273:                 }
 3274:             }
 3275:         }
 3276:     } else if (setting == 'lcmenu') {
 3277:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3278:         var divid = 'lti_menufield_'+item;
 3279:         var setvis = '';
 3280:         for (var i=0; i<menus.length; i++) {
 3281:             var radioname = menus[i];  
 3282:             var num = form.elements[radioname].length;
 3283:             if (num) {
 3284:                 for (var j=0; j<num; j++) {
 3285:                     if (form.elements[radioname][j].checked) {
 3286:                         if (form.elements[radioname][j].value == '1') {
 3287:                             if (document.getElementById(divid)) {
 3288:                                 document.getElementById(divid).style.display = 'inline-block';
 3289:                             }
 3290:                             setvis = 1;
 3291:                             break;
 3292:                         }
 3293:                     }
 3294:                 }
 3295:             }
 3296:             if (setvis == 1) {
 3297:                 break;
 3298:             }
 3299:         }
 3300:         if (!setvis) {
 3301:             if (document.getElementById(divid)) {
 3302:                 document.getElementById(divid).style.display = 'none';
 3303:             }
 3304:         }
 3305:     }
 3306:     return;
 3307: }
 3308: // ]]>
 3309: </script>
 3310: 
 3311: ENDSCRIPT
 3312: }
 3313: 
 3314: sub print_autoenroll {
 3315:     my ($dom,$settings,$rowtotal) = @_;
 3316:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 3317:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,$failsafe);
 3318:     if (ref($settings) eq 'HASH') {
 3319:         if (exists($settings->{'run'})) {
 3320:             if ($settings->{'run'} eq '0') {
 3321:                 $runoff = ' checked="checked" ';
 3322:                 $runon = ' ';
 3323:             } else {
 3324:                 $runon = ' checked="checked" ';
 3325:                 $runoff = ' ';
 3326:             }
 3327:         } else {
 3328:             if ($autorun) {
 3329:                 $runon = ' checked="checked" ';
 3330:                 $runoff = ' ';
 3331:             } else {
 3332:                 $runoff = ' checked="checked" ';
 3333:                 $runon = ' ';
 3334:             }
 3335:         }
 3336:         if (exists($settings->{'co-owners'})) {
 3337:             if ($settings->{'co-owners'} eq '0') {
 3338:                 $coownersoff = ' checked="checked" ';
 3339:                 $coownerson = ' ';
 3340:             } else {
 3341:                 $coownerson = ' checked="checked" ';
 3342:                 $coownersoff = ' ';
 3343:             }
 3344:         } else {
 3345:             $coownersoff = ' checked="checked" ';
 3346:             $coownerson = ' ';
 3347:         }
 3348:         if (exists($settings->{'sender_domain'})) {
 3349:             $defdom = $settings->{'sender_domain'};
 3350:         }
 3351:         if (exists($settings->{'autofailsafe'})) {
 3352:             $failsafe = $settings->{'autofailsafe'};
 3353:         }
 3354:     } else {
 3355:         if ($autorun) {
 3356:             $runon = ' checked="checked" ';
 3357:             $runoff = ' ';
 3358:         } else {
 3359:             $runoff = ' checked="checked" ';
 3360:             $runon = ' ';
 3361:         }
 3362:     }
 3363:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 3364:     my $notif_sender;
 3365:     if (ref($settings) eq 'HASH') {
 3366:         $notif_sender = $settings->{'sender_uname'};
 3367:     }
 3368:     my $datatable='<tr class="LC_odd_row">'.
 3369:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 3370:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3371:                   '<input type="radio" name="autoenroll_run"'.
 3372:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3373:                   '<label><input type="radio" name="autoenroll_run"'.
 3374:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3375:                   '</tr><tr>'.
 3376:                   '<td>'.&mt('Notification messages - sender').
 3377:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 3378:                   &mt('username').':&nbsp;'.
 3379:                   '<input type="text" name="sender_uname" value="'.
 3380:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 3381:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 3382:                   '<tr class="LC_odd_row">'.
 3383:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 3384:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3385:                   '<input type="radio" name="autoassign_coowners"'.
 3386:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3387:                   '<label><input type="radio" name="autoassign_coowners"'.
 3388:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3389:                   '</tr><tr>'.
 3390:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 3391:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 3392:                   '<input type="text" name="autoenroll_failsafe"'.
 3393:                   ' value="'.$failsafe.'" size="4" /></span></td></tr>';
 3394:     $$rowtotal += 4;
 3395:     return $datatable;
 3396: }
 3397: 
 3398: sub print_autoupdate {
 3399:     my ($position,$dom,$settings,$rowtotal) = @_;
 3400:     my $datatable;
 3401:     if ($position eq 'top') {
 3402:         my $updateon = ' ';
 3403:         my $updateoff = ' checked="checked" ';
 3404:         my $classlistson = ' ';
 3405:         my $classlistsoff = ' checked="checked" ';
 3406:         if (ref($settings) eq 'HASH') {
 3407:             if ($settings->{'run'} eq '1') {
 3408:                 $updateon = $updateoff;
 3409:                 $updateoff = ' ';
 3410:             }
 3411:             if ($settings->{'classlists'} eq '1') {
 3412:                 $classlistson = $classlistsoff;
 3413:                 $classlistsoff = ' ';
 3414:             }
 3415:         }
 3416:         my %title = (
 3417:                    run => 'Auto-update active?',
 3418:                    classlists => 'Update information in classlists?',
 3419:                     );
 3420:         $datatable = '<tr class="LC_odd_row">'. 
 3421:                   '<td>'.&mt($title{'run'}).'</td>'.
 3422:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3423:                   '<input type="radio" name="autoupdate_run"'.
 3424:                   $updateon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3425:                   '<label><input type="radio" name="autoupdate_run"'.
 3426:                   $updateoff.'value="0" />'.&mt('No').'</label></span></td>'.
 3427:                   '</tr><tr>'.
 3428:                   '<td>'.&mt($title{'classlists'}).'</td>'.
 3429:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
 3430:                   '<label><input type="radio" name="classlists"'.
 3431:                   $classlistson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3432:                   '<label><input type="radio" name="classlists"'.
 3433:                   $classlistsoff.'value="0" />'.&mt('No').'</label></span></td>'.
 3434:                   '</tr>';
 3435:         $$rowtotal += 2;
 3436:     } elsif ($position eq 'middle') {
 3437:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3438:         my $numinrow = 3;
 3439:         my $locknamesettings;
 3440:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 3441:                                      $dom,$numinrow,$othertitle,
 3442:                                     'lockablenames',$rowtotal);
 3443:         $$rowtotal ++;
 3444:     } else {
 3445:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3446:         my @fields = ('lastname','firstname','middlename','generation',
 3447:                       'permanentemail','id');
 3448:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 3449:         my $numrows = 0;
 3450:         if (ref($types) eq 'ARRAY') {
 3451:             if (@{$types} > 0) {
 3452:                 $datatable = 
 3453:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 3454:                                          \@fields,$types,\$numrows);
 3455:                     $$rowtotal += @{$types}; 
 3456:             }
 3457:         }
 3458:         $datatable .= 
 3459:             &usertype_update_row($settings,{'default' => $othertitle},
 3460:                                  \%fieldtitles,\@fields,['default'],
 3461:                                  \$numrows);
 3462:         $$rowtotal ++;     
 3463:     }
 3464:     return $datatable;
 3465: }
 3466: 
 3467: sub print_autocreate {
 3468:     my ($dom,$settings,$rowtotal) = @_;
 3469:     my (%createon,%createoff,%currhash);
 3470:     my @types = ('xml','req');
 3471:     if (ref($settings) eq 'HASH') {
 3472:         foreach my $item (@types) {
 3473:             $createoff{$item} = ' checked="checked" ';
 3474:             $createon{$item} = ' ';
 3475:             if (exists($settings->{$item})) {
 3476:                 if ($settings->{$item}) {
 3477:                     $createon{$item} = ' checked="checked" ';
 3478:                     $createoff{$item} = ' ';
 3479:                 }
 3480:             }
 3481:         }
 3482:         if ($settings->{'xmldc'} ne '') {
 3483:             $currhash{$settings->{'xmldc'}} = 1;
 3484:         }
 3485:     } else {
 3486:         foreach my $item (@types) {
 3487:             $createoff{$item} = ' checked="checked" ';
 3488:             $createon{$item} = ' ';
 3489:         }
 3490:     }
 3491:     $$rowtotal += 2;
 3492:     my $numinrow = 2;
 3493:     my $datatable='<tr class="LC_odd_row">'.
 3494:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 3495:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3496:                   '<input type="radio" name="autocreate_xml"'.
 3497:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3498:                   '<label><input type="radio" name="autocreate_xml"'.
 3499:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 3500:                   '</td></tr><tr>'.
 3501:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 3502:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3503:                   '<input type="radio" name="autocreate_req"'.
 3504:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3505:                   '<label><input type="radio" name="autocreate_req"'.
 3506:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 3507:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 3508:                                                    'autocreate_xmldc',%currhash);
 3509:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 3510:     if ($numdc > 1) {
 3511:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 3512:                       '</td><td class="LC_left_item">';
 3513:     } else {
 3514:         $datatable .= &mt('Course creation processed as:').
 3515:                       '</td><td class="LC_right_item">';
 3516:     }
 3517:     $datatable .= $dctable.'</td></tr>';
 3518:     $$rowtotal += $rows;
 3519:     return $datatable;
 3520: }
 3521: 
 3522: sub print_directorysrch {
 3523:     my ($position,$dom,$settings,$rowtotal) = @_;
 3524:     my $datatable;
 3525:     if ($position eq 'top') {
 3526:         my $instsrchon = ' ';
 3527:         my $instsrchoff = ' checked="checked" ';
 3528:         my ($exacton,$containson,$beginson);
 3529:         my $instlocalon = ' ';
 3530:         my $instlocaloff = ' checked="checked" ';
 3531:         if (ref($settings) eq 'HASH') {
 3532:             if ($settings->{'available'} eq '1') {
 3533:                 $instsrchon = $instsrchoff;
 3534:                 $instsrchoff = ' ';
 3535:             }
 3536:             if ($settings->{'localonly'} eq '1') {
 3537:                 $instlocalon = $instlocaloff;
 3538:                 $instlocaloff = ' ';
 3539:             }
 3540:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 3541:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 3542:                     if ($type eq 'exact') {
 3543:                         $exacton = ' checked="checked" ';
 3544:                     } elsif ($type eq 'contains') {
 3545:                         $containson = ' checked="checked" ';
 3546:                     } elsif ($type eq 'begins') {
 3547:                         $beginson = ' checked="checked" ';
 3548:                     }
 3549:                 }
 3550:             } else {
 3551:                 if ($settings->{'searchtypes'} eq 'exact') {
 3552:                     $exacton = ' checked="checked" ';
 3553:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 3554:                     $containson = ' checked="checked" ';
 3555:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 3556:                     $exacton = ' checked="checked" ';
 3557:                     $containson = ' checked="checked" ';
 3558:                 }
 3559:             }
 3560:         }
 3561:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 3562:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3563: 
 3564:         my $numinrow = 4;
 3565:         my $cansrchrow = 0;
 3566:         $datatable='<tr class="LC_odd_row">'.
 3567:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 3568:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3569:                    '<input type="radio" name="dirsrch_available"'.
 3570:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3571:                    '<label><input type="radio" name="dirsrch_available"'.
 3572:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3573:                    '</tr><tr>'.
 3574:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 3575:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3576:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 3577:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3578:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 3579:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3580:                    '</tr>';
 3581:         $$rowtotal += 2;
 3582:         if (ref($usertypes) eq 'HASH') {
 3583:             if (keys(%{$usertypes}) > 0) {
 3584:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 3585:                                              $numinrow,$othertitle,'cansearch',
 3586:                                              $rowtotal);
 3587:                 $cansrchrow = 1;
 3588:             }
 3589:         }
 3590:         if ($cansrchrow) {
 3591:             $$rowtotal ++;
 3592:             $datatable .= '<tr>';
 3593:         } else {
 3594:             $datatable .= '<tr class="LC_odd_row">';
 3595:         }
 3596:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 3597:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 3598:         foreach my $title (@{$titleorder}) {
 3599:             if (defined($searchtitles->{$title})) {
 3600:                 my $check = ' ';
 3601:                 if (ref($settings) eq 'HASH') {
 3602:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 3603:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 3604:                             $check = ' checked="checked" ';
 3605:                         }
 3606:                     }
 3607:                 }
 3608:                 $datatable .= '<td class="LC_left_item">'.
 3609:                               '<span class="LC_nobreak"><label>'.
 3610:                               '<input type="checkbox" name="searchby" '.
 3611:                               'value="'.$title.'"'.$check.'/>'.
 3612:                               $searchtitles->{$title}.'</label></span></td>';
 3613:             }
 3614:         }
 3615:         $datatable .= '</tr></table></td></tr>';
 3616:         $$rowtotal ++;
 3617:         if ($cansrchrow) {
 3618:             $datatable .= '<tr class="LC_odd_row">';
 3619:         } else {
 3620:             $datatable .= '<tr>';
 3621:         }
 3622:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 3623:                       '<td class="LC_left_item" colspan="2">'.
 3624:                       '<span class="LC_nobreak"><label>'.
 3625:                       '<input type="checkbox" name="searchtypes" '.
 3626:                       $exacton.' value="exact" />'.&mt('Exact match').
 3627:                       '</label>&nbsp;'.
 3628:                       '<label><input type="checkbox" name="searchtypes" '.
 3629:                       $beginson.' value="begins" />'.&mt('Begins with').
 3630:                       '</label>&nbsp;'.
 3631:                       '<label><input type="checkbox" name="searchtypes" '.
 3632:                       $containson.' value="contains" />'.&mt('Contains').
 3633:                       '</label></span></td></tr>';
 3634:         $$rowtotal ++;
 3635:     } else {
 3636:         my $domsrchon = ' checked="checked" ';
 3637:         my $domsrchoff = ' ';
 3638:         my $domlocalon = ' ';
 3639:         my $domlocaloff = ' checked="checked" ';
 3640:         if (ref($settings) eq 'HASH') {
 3641:             if ($settings->{'lclocalonly'} eq '1') {
 3642:                 $domlocalon = $domlocaloff;
 3643:                 $domlocaloff = ' ';
 3644:             }
 3645:             if ($settings->{'lcavailable'} eq '0') {
 3646:                 $domsrchoff = $domsrchon;
 3647:                 $domsrchon = ' ';
 3648:             }
 3649:         }
 3650:         $datatable='<tr class="LC_odd_row">'.
 3651:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 3652:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3653:                       '<input type="radio" name="dirsrch_domavailable"'.
 3654:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 3655:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 3656:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 3657:                       '</tr><tr>'.
 3658:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 3659:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 3660:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 3661:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 3662:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 3663:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 3664:                       '</tr>';
 3665:         $$rowtotal += 2;
 3666:     }
 3667:     return $datatable;
 3668: }
 3669: 
 3670: sub print_contacts {
 3671:     my ($position,$dom,$settings,$rowtotal) = @_;
 3672:     my $datatable;
 3673:     my @contacts = ('adminemail','supportemail');
 3674:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 3675:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 3676:     if ($position eq 'top') {
 3677:         if (ref($settings) eq 'HASH') {
 3678:             foreach my $item (@contacts) {
 3679:                 if (exists($settings->{$item})) {
 3680:                     $to{$item} = $settings->{$item};
 3681:                 }
 3682:             }
 3683:         }
 3684:     } elsif ($position eq 'middle') {
 3685:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 3686:                      'updatesmail','idconflictsmail','hostipmail');
 3687:         foreach my $type (@mailings) {
 3688:             $otheremails{$type} = '';
 3689:         }
 3690:     } elsif ($position eq 'lower') {
 3691:         if (ref($settings) eq 'HASH') {
 3692:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 3693:                 %lonstatus = %{$settings->{'lonstatus'}};
 3694:             }
 3695:         }
 3696:     } else {
 3697:         @mailings = ('helpdeskmail','otherdomsmail');
 3698:         foreach my $type (@mailings) {
 3699:             $otheremails{$type} = '';
 3700:         }
 3701:         $bccemails{'helpdeskmail'} = '';
 3702:         $bccemails{'otherdomsmail'} = '';
 3703:         $includestr{'helpdeskmail'} = '';
 3704:         $includestr{'otherdomsmail'} = '';
 3705:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 3706:     }
 3707:     if (ref($settings) eq 'HASH') {
 3708:         unless (($position eq 'top') || ($position eq 'lower')) {
 3709:             foreach my $type (@mailings) {
 3710:                 if (exists($settings->{$type})) {
 3711:                     if (ref($settings->{$type}) eq 'HASH') {
 3712:                         foreach my $item (@contacts) {
 3713:                             if ($settings->{$type}{$item}) {
 3714:                                 $checked{$type}{$item} = ' checked="checked" ';
 3715:                             }
 3716:                         }
 3717:                         $otheremails{$type} = $settings->{$type}{'others'};
 3718:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3719:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 3720:                             if ($settings->{$type}{'include'} ne '') {
 3721:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3722:                                 $includestr{$type} = &unescape($includestr{$type});
 3723:                             }
 3724:                         }
 3725:                     }
 3726:                 } elsif ($type eq 'lonstatusmail') {
 3727:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3728:                 }
 3729:             }
 3730:         }
 3731:         if ($position eq 'bottom') {
 3732:             foreach my $type (@mailings) {
 3733:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 3734:                 if ($settings->{$type}{'include'} ne '') {
 3735:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 3736:                     $includestr{$type} = &unescape($includestr{$type});
 3737:                 }
 3738:             }
 3739:             if (ref($settings->{'helpform'}) eq 'HASH') {
 3740:                 if (ref($fields) eq 'ARRAY') {
 3741:                     foreach my $field (@{$fields}) {
 3742:                         $currfield{$field} = $settings->{'helpform'}{$field};
 3743:                     }
 3744:                 }
 3745:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 3746:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 3747:                 } else {
 3748:                     $maxsize = '1.0';
 3749:                 }
 3750:             } else {
 3751:                 if (ref($fields) eq 'ARRAY') {
 3752:                     foreach my $field (@{$fields}) {
 3753:                         $currfield{$field} = 'yes';
 3754:                     }
 3755:                 }
 3756:                 $maxsize = '1.0';
 3757:             }
 3758:         }
 3759:     } else {
 3760:         if ($position eq 'top') {
 3761:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 3762:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 3763:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 3764:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 3765:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 3766:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 3767:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 3768:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 3769:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 3770:         } elsif ($position eq 'bottom') {
 3771:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 3772:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 3773:             if (ref($fields) eq 'ARRAY') {
 3774:                 foreach my $field (@{$fields}) {
 3775:                     $currfield{$field} = 'yes';
 3776:                 }
 3777:             }
 3778:             $maxsize = '1.0';
 3779:         }
 3780:     }
 3781:     my ($titles,$short_titles) = &contact_titles();
 3782:     my $rownum = 0;
 3783:     my $css_class;
 3784:     if ($position eq 'top') {
 3785:         foreach my $item (@contacts) {
 3786:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3787:             $datatable .= '<tr'.$css_class.'>'. 
 3788:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 3789:                           '</span></td><td class="LC_right_item">'.
 3790:                           '<input type="text" name="'.$item.'" value="'.
 3791:                           $to{$item}.'" /></td></tr>';
 3792:             $rownum ++;
 3793:         }
 3794:     } elsif ($position eq 'bottom') {
 3795:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3796:         $datatable .= '<tr'.$css_class.'>'.
 3797:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 3798:                       &mt('(e-mail, subject, and description always shown)').
 3799:                       '</td><td class="LC_left_item">';
 3800:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 3801:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 3802:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 3803:             foreach my $field (@{$fields}) {
 3804:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 3805:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 3806:                     $datatable .= ' '.&mt('(logged-in users)');
 3807:                 }
 3808:                 $datatable .='</td><td>';
 3809:                 my $clickaction;
 3810:                 if ($field eq 'screenshot') {
 3811:                     $clickaction = ' onclick="screenshotSize(this);"';
 3812:                 }
 3813:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 3814:                     foreach my $option (@{$possoptions->{$field}}) {
 3815:                         my $checked;
 3816:                         if ($currfield{$field} eq $option) {
 3817:                             $checked = ' checked="checked"';
 3818:                         }
 3819:                         $datatable .= '<span class="LC_nobreak"><label>'.
 3820:                                       '<input type="radio" name="helpform_'.$field.'" '.
 3821:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 3822:                                       '</label></span>'.('&nbsp;'x2);
 3823:                     }
 3824:                 }
 3825:                 if ($field eq 'screenshot') {
 3826:                     my $display;
 3827:                     if ($currfield{$field} eq 'no') {
 3828:                         $display = ' style="display:none"';
 3829:                     }
 3830:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 3831:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 3832:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 3833:                 }
 3834:                 $datatable .= '</td></tr>';
 3835:             }
 3836:             $datatable .= '</table>';
 3837:         }
 3838:         $datatable .= '</td></tr>'."\n";
 3839:         $rownum ++;
 3840:     }
 3841:     unless (($position eq 'top') || ($position eq 'lower')) {
 3842:         foreach my $type (@mailings) {
 3843:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3844:             $datatable .= '<tr'.$css_class.'>'.
 3845:                           '<td><span class="LC_nobreak">'.
 3846:                           $titles->{$type}.': </span></td>'.
 3847:                           '<td class="LC_left_item">';
 3848:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3849:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 3850:             }
 3851:             $datatable .= '<span class="LC_nobreak">';
 3852:             foreach my $item (@contacts) {
 3853:                 $datatable .= '<label>'.
 3854:                               '<input type="checkbox" name="'.$type.'"'.
 3855:                               $checked{$type}{$item}.
 3856:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 3857:                               '</label>&nbsp;';
 3858:             }
 3859:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 3860:                           '<input type="text" name="'.$type.'_others" '.
 3861:                           'value="'.$otheremails{$type}.'"  />';
 3862:             my %locchecked;
 3863:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 3864:                 foreach my $loc ('s','b') {
 3865:                     if ($includeloc{$type} eq $loc) {
 3866:                         $locchecked{$loc} = ' checked="checked"';
 3867:                         last;
 3868:                     }
 3869:                 }
 3870:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 3871:                               '<input type="text" name="'.$type.'_bcc" '.
 3872:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 3873:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 3874:                               &mt('Text automatically added to e-mail:').' '.
 3875:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 3876:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 3877:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 3878:                               ('&nbsp;'x2).
 3879:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 3880:                               '</span></fieldset>';
 3881:             }
 3882:             $datatable .= '</td></tr>'."\n";
 3883:             $rownum ++;
 3884:         }
 3885:     }
 3886:     if ($position eq 'middle') {
 3887:         my %choices;
 3888:         my $corelink = &core_link_msu();
 3889:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 3890:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 3891:                                         $corelink);
 3892:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 3893:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 3894:         my %defaultchecked = ('reporterrors'  => 'on',
 3895:                               'reportupdates' => 'on',
 3896:                               'reportstatus'  => 'on');
 3897:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 3898:                                                    \%choices,$rownum);
 3899:         $datatable .= $reports;
 3900:     } elsif ($position eq 'lower') {
 3901:         my (%current,%excluded,%weights);
 3902:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 3903:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 3904:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 3905:         } else {
 3906:             $current{'errorthreshold'} = $defaults->{'threshold'};
 3907:         }
 3908:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 3909:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 3910:         } else {
 3911:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 3912:         }
 3913:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 3914:             foreach my $type ('E','W','N','U') {
 3915:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 3916:                     $weights{$type} = $lonstatus{'weights'}{$type};
 3917:                 } else {
 3918:                     $weights{$type} = $defaults->{$type};
 3919:                 }
 3920:             }
 3921:         } else {
 3922:             foreach my $type ('E','W','N','U') {
 3923:                 $weights{$type} = $defaults->{$type};
 3924:             }
 3925:         }
 3926:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 3927:             if (@{$lonstatus{'excluded'}} > 0) {
 3928:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 3929:             }
 3930:         }
 3931:         foreach my $item ('errorthreshold','errorsysmail') { 
 3932:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 3933:             $datatable .= '<tr'.$css_class.'>'.
 3934:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 3935:                           $titles->{$item}.
 3936:                           '</span></td><td class="LC_left_item">'.
 3937:                           '<input type="text" name="'.$item.'" value="'.
 3938:                           $current{$item}.'" size="5" /></td></tr>';
 3939:             $rownum ++;
 3940:         }
 3941:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3942:         $datatable .= '<tr'.$css_class.'>'.
 3943:                       '<td class="LC_left_item">'.
 3944:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 3945:                       '</span></td><td class="LC_left_item"><table><tr>';
 3946:         foreach my $type ('E','W','N','U') {
 3947:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 3948:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 3949:                           $weights{$type}.'" size="5" /></td>';
 3950:         }
 3951:         $datatable .= '</tr></table></tr>';
 3952:         $rownum ++;
 3953:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 3954:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 3955:                       $titles->{'errorexcluded'}.'</td>'.
 3956:                       '<td class="LC_left_item"><table>';
 3957:         my $numinrow = 4;
 3958:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 3959:         for (my $i=0; $i<@ids; $i++) {
 3960:             my $rem = $i%($numinrow);
 3961:             if ($rem == 0) {
 3962:                 if ($i > 0) {
 3963:                     $datatable .= '</tr>';
 3964:                 }
 3965:                 $datatable .= '<tr>';
 3966:             }
 3967:             my $check;
 3968:             if ($excluded{$ids[$i]}) {
 3969:                 $check = ' checked="checked" ';
 3970:             }
 3971:             $datatable .= '<td class="LC_left_item">'.
 3972:                           '<span class="LC_nobreak"><label>'.
 3973:                           '<input type="checkbox" name="errorexcluded" '.
 3974:                           'value="'.$ids[$i].'"'.$check.' />'.
 3975:                           $ids[$i].'</label></span></td>';
 3976:         }
 3977:         my $colsleft = $numinrow - @ids%($numinrow);
 3978:         if ($colsleft > 1 ) {
 3979:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 3980:                           '&nbsp;</td>';
 3981:         } elsif ($colsleft == 1) {
 3982:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 3983:         }
 3984:         $datatable .= '</tr></table></td></tr>';
 3985:         $rownum ++;
 3986:     } elsif ($position eq 'bottom') {
 3987:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 3988:         my (@posstypes,%usertypeshash);
 3989:         if (ref($types) eq 'ARRAY') {
 3990:             @posstypes = @{$types};
 3991:         }
 3992:         if (@posstypes) {
 3993:             if (ref($usertypes) eq 'HASH') {
 3994:                 %usertypeshash = %{$usertypes};
 3995:             }
 3996:             my @overridden;
 3997:             my $numinrow = 4;
 3998:             if (ref($settings) eq 'HASH') {
 3999:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4000:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4001:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4002:                             push(@overridden,$key);
 4003:                             foreach my $item (@contacts) {
 4004:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4005:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4006:                                 }
 4007:                             }
 4008:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4009:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4010:                             $includeloc{'override_'.$key} = '';
 4011:                             $includestr{'override_'.$key} = '';
 4012:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4013:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 4014:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4015:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4016:                             }
 4017:                         }
 4018:                     }
 4019:                 }
 4020:             }
 4021:             my $customclass = 'LC_helpdesk_override';
 4022:             my $optionsprefix = 'LC_options_helpdesk_';
 4023: 
 4024:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4025:  
 4026:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4027:                                          $numinrow,$othertitle,'overrides',
 4028:                                          \$rownum,$onclicktypes,$customclass);
 4029:             $rownum ++;
 4030:             $usertypeshash{'default'} = $othertitle;
 4031:             foreach my $status (@posstypes) {
 4032:                 my $css_class;
 4033:                 if ($rownum%2) {
 4034:                     $css_class = 'LC_odd_row ';
 4035:                 }
 4036:                 $css_class .= $customclass;
 4037:                 my $rowid = $optionsprefix.$status;
 4038:                 my $hidden = 1;
 4039:                 my $currstyle = 'display:none';
 4040:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4041:                     $currstyle = 'display:table-row';
 4042:                     $hidden = 0;
 4043:                 }
 4044:                 my $key = 'override_'.$status;
 4045:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4046:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4047:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4048:                                                   \@contacts,$short_titles);
 4049:                 unless ($hidden) {
 4050:                     $rownum ++;
 4051:                 }
 4052:             }
 4053:         }
 4054:     }
 4055:     $$rowtotal += $rownum;
 4056:     return $datatable;
 4057: }
 4058: 
 4059: sub core_link_msu {
 4060:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4061:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4062: }
 4063: 
 4064: sub overridden_helpdesk {
 4065:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4066:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4067:     my $class = 'LC_left_item';
 4068:     if ($css_class) {
 4069:         $css_class = ' class="'.$css_class.'"';
 4070:     }
 4071:     if ($rowid) {
 4072:         $rowid = ' id="'.$rowid.'"';
 4073:     }
 4074:     if ($rowstyle) {
 4075:         $rowstyle = ' style="'.$rowstyle.'"';
 4076:     }
 4077:     my ($output,$description);
 4078:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4079:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4080:               "<td>$description</td>\n".
 4081:               '<td class="'.$class.'" colspan="2">'.
 4082:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4083:               '<span class="LC_nobreak">';
 4084:     if (ref($contacts) eq 'ARRAY') {
 4085:         foreach my $item (@{$contacts}) {
 4086:             my $check;
 4087:             if (ref($checked) eq 'HASH') {
 4088:                $check = $checked->{$item};
 4089:             }
 4090:             my $title;
 4091:             if (ref($short_titles) eq 'HASH') {
 4092:                 $title = $short_titles->{$item}; 
 4093:             }
 4094:             $output .= '<label>'.
 4095:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4096:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4097:         }
 4098:     }
 4099:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4100:                '<input type="text" name="override_'.$type.'_others" '.
 4101:                'value="'.$otheremails.'"  />';
 4102:     my %locchecked;
 4103:     foreach my $loc ('s','b') {
 4104:         if ($includeloc eq $loc) {
 4105:             $locchecked{$loc} = ' checked="checked"';
 4106:             last;
 4107:         }
 4108:     }
 4109:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4110:                '<input type="text" name="override_'.$type.'_bcc" '.
 4111:                'value="'.$bccemails.'"  /></fieldset>'.
 4112:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4113:                &mt('Text automatically added to e-mail:').' '.
 4114:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4115:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4116:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4117:                ('&nbsp;'x2).
 4118:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4119:                '</span></fieldset>'.
 4120:                '</td></tr>'."\n";
 4121:     return $output;
 4122: }
 4123: 
 4124: sub contacts_javascript {
 4125:     return <<"ENDSCRIPT";
 4126: 
 4127: <script type="text/javascript">
 4128: // <![CDATA[
 4129: 
 4130: function screenshotSize(field) {
 4131:     if (document.getElementById('help_screenshotsize')) {
 4132:         if (field.value == 'no') {
 4133:             document.getElementById('help_screenshotsize').style.display="none";
 4134:         } else {
 4135:             document.getElementById('help_screenshotsize').style.display="";
 4136:         }
 4137:     }
 4138:     return;
 4139: }
 4140: 
 4141: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4142:     if (form.elements[checkbox].length != undefined) {
 4143:         var count = 0;
 4144:         if (docount) {
 4145:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4146:                 if (form.elements[checkbox][i].checked) {
 4147:                     count ++;
 4148:                 }
 4149:             }
 4150:         }
 4151:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4152:             var type = form.elements[checkbox][i].value;
 4153:             if (document.getElementById(prefix+type)) {
 4154:                 if (form.elements[checkbox][i].checked) {
 4155:                     document.getElementById(prefix+type).style.display = 'table-row';
 4156:                     if (count % 2 == 1) {
 4157:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4158:                     } else {
 4159:                         document.getElementById(prefix+type).className = target;
 4160:                     }
 4161:                     count ++;
 4162:                 } else {
 4163:                     document.getElementById(prefix+type).style.display = 'none';
 4164:                 }
 4165:             }
 4166:         }
 4167:     }
 4168:     return;
 4169: }
 4170: 
 4171: 
 4172: // ]]>
 4173: </script>
 4174: 
 4175: ENDSCRIPT
 4176: }
 4177: 
 4178: sub print_helpsettings {
 4179:     my ($position,$dom,$settings,$rowtotal) = @_;
 4180:     my $confname = $dom.'-domainconfig';
 4181:     my $formname = 'display';
 4182:     my ($datatable,$itemcount);
 4183:     if ($position eq 'top') {
 4184:         $itemcount = 1;
 4185:         my (%choices,%defaultchecked,@toggles);
 4186:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4187:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4188:                                      &mt('LON-CAPA bug tracker'),600,500));
 4189:         %defaultchecked = ('submitbugs' => 'on');
 4190:         @toggles = ('submitbugs');
 4191:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4192:                                                      \%choices,$itemcount);
 4193:         $$rowtotal ++;
 4194:     } else {
 4195:         my $css_class;
 4196:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4197:         my (%customroles,%ordered,%current);
 4198:         if (ref($settings) eq 'HASH') {
 4199:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4200:                 %current = %{$settings->{'adhoc'}};
 4201:             }
 4202:         }
 4203:         my $count = 0;
 4204:         foreach my $key (sort(keys(%existing))) {
 4205:             if ($key=~/^rolesdef\_(\w+)$/) {
 4206:                 my $rolename = $1;
 4207:                 my (%privs,$order);
 4208:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4209:                 $customroles{$rolename} = \%privs;
 4210:                 if (ref($current{$rolename}) eq 'HASH') {
 4211:                     $order = $current{$rolename}{'order'};
 4212:                 }
 4213:                 if ($order eq '') {
 4214:                     $order = $count;
 4215:                 }
 4216:                 $ordered{$order} = $rolename;
 4217:                 $count++;
 4218:             }
 4219:         }
 4220:         my $maxnum = scalar(keys(%ordered));
 4221:         my @roles_by_num = ();
 4222:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4223:             push(@roles_by_num,$item);
 4224:         }
 4225:         my $context = 'domprefs';
 4226:         my $crstype = 'Course';
 4227:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4228:         my @accesstypes = ('all','dh','da','none');
 4229:         my ($numstatustypes,@jsarray);
 4230:         if (ref($types) eq 'ARRAY') {
 4231:             if (@{$types} > 0) {
 4232:                 $numstatustypes = scalar(@{$types});
 4233:                 push(@accesstypes,'status');
 4234:                 @jsarray = ('bystatus');
 4235:             }
 4236:         }
 4237:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4238:         if (keys(%domhelpdesk)) {
 4239:             push(@accesstypes,('inc','exc'));
 4240:             push(@jsarray,('notinc','notexc'));
 4241:         }
 4242:         my $hiddenstr = join("','",@jsarray);
 4243:         my $context = 'domprefs';
 4244:         my $crstype = 'Course';
 4245:         my $prefix = 'helproles_';
 4246:         my $add_class = 'LC_hidden';
 4247:         foreach my $num (@roles_by_num) {
 4248:             my $role = $ordered{$num};
 4249:             my ($desc,$access,@statuses);
 4250:             if (ref($current{$role}) eq 'HASH') {
 4251:                 $desc = $current{$role}{'desc'};
 4252:                 $access = $current{$role}{'access'};
 4253:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4254:                     @statuses = @{$current{$role}{'insttypes'}};
 4255:                 }
 4256:             }
 4257:             if ($desc eq '') {
 4258:                 $desc = $role;
 4259:             }
 4260:             my $identifier = 'custhelp'.$num;
 4261:             my %full=();
 4262:             my %levels= (
 4263:                          course => {},
 4264:                          domain => {},
 4265:                          system => {},
 4266:                         );
 4267:             my %levelscurrent=(
 4268:                                course => {},
 4269:                                domain => {},
 4270:                                system => {},
 4271:                               );
 4272:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 4273:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4274:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4275:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 4276:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 4277:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 4278:             for (my $k=0; $k<=$maxnum; $k++) {
 4279:                 my $vpos = $k+1;
 4280:                 my $selstr;
 4281:                 if ($k == $num) {
 4282:                     $selstr = ' selected="selected" ';
 4283:                 }
 4284:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4285:             }
 4286:             $datatable .= '</select>'.('&nbsp;'x2).
 4287:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 4288:                           '</td>'.
 4289:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4290:                           &mt('Name shown to users:').
 4291:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 4292:                           '</fieldset>'.
 4293:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 4294:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 4295:                           '<fieldset>'.
 4296:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 4297:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 4298:                                                                    \%levelscurrent,$identifier,
 4299:                                                                    'LC_hidden',$prefix.$num.'_privs').
 4300:                           '</fieldset></td>';
 4301:             $itemcount ++;
 4302:         }
 4303:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4304:         my $newcust = 'custhelp'.$count;
 4305:         my (%privs,%levelscurrent);
 4306:         my %full=();
 4307:         my %levels= (
 4308:                      course => {},
 4309:                      domain => {},
 4310:                      system => {},
 4311:                     );
 4312:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 4313:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 4314:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 4315:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 4316:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 4317:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 4318:         for (my $k=0; $k<$maxnum+1; $k++) {
 4319:             my $vpos = $k+1;
 4320:             my $selstr;
 4321:             if ($k == $maxnum) {
 4322:                 $selstr = ' selected="selected" ';
 4323:             }
 4324:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4325:         }
 4326:         $datatable .= '</select>&nbsp;'."\n".
 4327:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 4328:                       '</label></span></td>'.
 4329:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 4330:                       '<span class="LC_nobreak">'.
 4331:                       &mt('Internal name:').
 4332:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 4333:                       '</span>'.('&nbsp;'x4).
 4334:                       '<span class="LC_nobreak">'.
 4335:                       &mt('Name shown to users:').
 4336:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 4337:                       '</span></fieldset>'.
 4338:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 4339:                                              $usertypes,$types,\%domhelpdesk).
 4340:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 4341:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 4342:                                                                 \@templateroles,$newcust).
 4343:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 4344:                                                                \%levelscurrent,$newcust).
 4345:                       '</fieldset>'.
 4346:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 4347:                       '</td></tr>';
 4348:         $count ++;
 4349:         $$rowtotal += $count;
 4350:     }
 4351:     return $datatable;
 4352: }
 4353: 
 4354: sub adhocbutton {
 4355:     my ($prefix,$num,$field,$visibility) = @_;
 4356:     my %lt = &Apache::lonlocal::texthash(
 4357:                                           show => 'Show details',
 4358:                                           hide => 'Hide details',
 4359:                                         );
 4360:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 4361:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 4362:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 4363:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 4364: }
 4365: 
 4366: sub helpsettings_javascript {
 4367:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 4368:     return unless(ref($roles_by_num) eq 'ARRAY');
 4369:     my %html_js_lt = &Apache::lonlocal::texthash(
 4370:                                           show => 'Show details',
 4371:                                           hide => 'Hide details',
 4372:                                         );
 4373:     &html_escape(\%html_js_lt);
 4374:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 4375:     return <<"ENDSCRIPT";
 4376: <script type="text/javascript">
 4377: // <![CDATA[
 4378: 
 4379: function reorderHelpRoles(form,item) {
 4380:     var changedVal;
 4381: $jstext
 4382:     var newpos = 'helproles_${total}_pos';
 4383:     var maxh = 1 + $total;
 4384:     var current = new Array();
 4385:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 4386:     if (item == newpos) {
 4387:         changedVal = newitemVal;
 4388:     } else {
 4389:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 4390:         current[newitemVal] = newpos;
 4391:     }
 4392:     for (var i=0; i<helproles.length; i++) {
 4393:         var elementName = 'helproles_'+helproles[i]+'_pos';
 4394:         if (elementName != item) {
 4395:             if (form.elements[elementName]) {
 4396:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 4397:                 current[currVal] = elementName;
 4398:             }
 4399:         }
 4400:     }
 4401:     var oldVal;
 4402:     for (var j=0; j<maxh; j++) {
 4403:         if (current[j] == undefined) {
 4404:             oldVal = j;
 4405:         }
 4406:     }
 4407:     if (oldVal < changedVal) {
 4408:         for (var k=oldVal+1; k<=changedVal ; k++) {
 4409:            var elementName = current[k];
 4410:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 4411:         }
 4412:     } else {
 4413:         for (var k=changedVal; k<oldVal; k++) {
 4414:             var elementName = current[k];
 4415:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4416:         }
 4417:     }
 4418:     return;
 4419: }
 4420: 
 4421: function helpdeskAccess(num) {
 4422:     var curraccess = null;
 4423:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 4424:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 4425:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 4426:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 4427:             }
 4428:         }
 4429:     }
 4430:     var shown = Array();
 4431:     var hidden = Array();
 4432:     if (curraccess == 'none') {
 4433:         hidden = Array('$hiddenstr');
 4434:     } else {
 4435:         if (curraccess == 'status') {
 4436:             shown = Array('bystatus');
 4437:             hidden = Array('notinc','notexc');
 4438:         } else {
 4439:             if (curraccess == 'exc') {
 4440:                 shown = Array('notexc');
 4441:                 hidden = Array('notinc','bystatus');
 4442:             }
 4443:             if (curraccess == 'inc') {
 4444:                 shown = Array('notinc');
 4445:                 hidden = Array('notexc','bystatus');
 4446:             }
 4447:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 4448:                 hidden = Array('notinc','notexc','bystatus');
 4449:             }
 4450:         }
 4451:     }
 4452:     if (hidden.length > 0) {
 4453:         for (var i=0; i<hidden.length; i++) {
 4454:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 4455:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 4456:             }
 4457:         }
 4458:     }
 4459:     if (shown.length > 0) {
 4460:         for (var i=0; i<shown.length; i++) {
 4461:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 4462:                 if (shown[i] == 'privs') {
 4463:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 4464:                 } else {
 4465:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 4466:                 }
 4467:             }
 4468:         }
 4469:     }
 4470:     return;
 4471: }
 4472: 
 4473: function toggleHelpdeskItem(num,field) {
 4474:     if (document.getElementById('helproles_'+num+'_'+field)) {
 4475:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 4476:             document.getElementById('helproles_'+num+'_'+field).className =
 4477:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 4478:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4479:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 4480:             }
 4481:         } else {
 4482:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 4483:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 4484:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 4485:             }
 4486:         }
 4487:     }
 4488:     return;
 4489: }
 4490: 
 4491: // ]]>
 4492: </script>
 4493: 
 4494: ENDSCRIPT
 4495: }
 4496: 
 4497: sub helpdeskroles_access {
 4498:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 4499:         $usertypes,$types,$domhelpdesk) = @_;
 4500:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 4501:     my %lt = &Apache::lonlocal::texthash(
 4502:                     'rou'    => 'Role usage',
 4503:                     'whi'    => 'Which helpdesk personnel may use this role?',
 4504:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 4505:                     'dh'     => 'All with domain helpdesk role',
 4506:                     'da'     => 'All with domain helpdesk assistant role',
 4507:                     'none'   => 'None',
 4508:                     'status' => 'Determined based on institutional status',
 4509:                     'inc'    => 'Include all, but exclude specific personnel',
 4510:                     'exc'    => 'Exclude all, but include specific personnel',
 4511:                   );
 4512:     my %usecheck = (
 4513:                      all => ' checked="checked"',
 4514:                    );
 4515:     my %displaydiv = (
 4516:                       status => 'none',
 4517:                       inc    => 'none',
 4518:                       exc    => 'none',
 4519:                       priv   => 'block',
 4520:                      );
 4521:     my $output;
 4522:     if (ref($current) eq 'HASH') {
 4523:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 4524:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 4525:                 $usecheck{$current->{access}} = $usecheck{'all'};
 4526:                 delete($usecheck{'all'});
 4527:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 4528:                     my $access = $1;
 4529:                     $displaydiv{$access} = 'inline';
 4530:                 } elsif ($current->{access} eq 'none') {
 4531:                     $displaydiv{'priv'} = 'none';
 4532:                 }
 4533:             }
 4534:         }
 4535:     }
 4536:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 4537:               '<p>'.$lt{'whi'}.'</p>';
 4538:     foreach my $access (@{$accesstypes}) {
 4539:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 4540:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 4541:                    $lt{$access}.'</label>';
 4542:         if ($access eq 'status') {
 4543:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 4544:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 4545:                                                                  $othertitle,$usertypes,$types).
 4546:                        '</div>';
 4547:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 4548:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 4549:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4550:                        '</div>';
 4551:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 4552:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 4553:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 4554:                        '</div>';
 4555:         }
 4556:         $output .= '</p>';
 4557:     }
 4558:     $output .= '</fieldset>';
 4559:     return $output;
 4560: }
 4561: 
 4562: sub radiobutton_prefs {
 4563:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 4564:         $additional,$align) = @_;
 4565:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 4566:                    (ref($choices) eq 'HASH'));
 4567: 
 4568:     my (%checkedon,%checkedoff,$datatable,$css_class);
 4569: 
 4570:     foreach my $item (@{$toggles}) {
 4571:         if ($defaultchecked->{$item} eq 'on') {
 4572:             $checkedon{$item} = ' checked="checked" ';
 4573:             $checkedoff{$item} = ' ';
 4574:         } elsif ($defaultchecked->{$item} eq 'off') {
 4575:             $checkedoff{$item} = ' checked="checked" ';
 4576:             $checkedon{$item} = ' ';
 4577:         }
 4578:     }
 4579:     if (ref($settings) eq 'HASH') {
 4580:         foreach my $item (@{$toggles}) {
 4581:             if ($settings->{$item} eq '1') {
 4582:                 $checkedon{$item} =  ' checked="checked" ';
 4583:                 $checkedoff{$item} = ' ';
 4584:             } elsif ($settings->{$item} eq '0') {
 4585:                 $checkedoff{$item} =  ' checked="checked" ';
 4586:                 $checkedon{$item} = ' ';
 4587:             }
 4588:         }
 4589:     }
 4590:     if ($onclick) {
 4591:         $onclick = ' onclick="'.$onclick.'"';
 4592:     }
 4593:     foreach my $item (@{$toggles}) {
 4594:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4595:         $datatable .=
 4596:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 4597:             '<span class="LC_nobreak">'.$choices->{$item}.
 4598:             '</span></td>';
 4599:         if ($align eq 'left') {
 4600:             $datatable .= '<td class="LC_left_item">';
 4601:         } else {
 4602:             $datatable .= '<td class="LC_right_item">';
 4603:         }
 4604:         $datatable .=
 4605:             '<span class="LC_nobreak">'.
 4606:             '<label><input type="radio" name="'.
 4607:             $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 4608:             '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 4609:             $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4610:             '</span>'.$additional.
 4611:             '</td>'.
 4612:             '</tr>';
 4613:         $itemcount ++;
 4614:     }
 4615:     return ($datatable,$itemcount);
 4616: }
 4617: 
 4618: sub print_ltitools {
 4619:     my ($dom,$settings,$rowtotal) = @_;
 4620:     my $rownum = 0;
 4621:     my $css_class;
 4622:     my $itemcount = 1;
 4623:     my $maxnum = 0;
 4624:     my %ordered;
 4625:     if (ref($settings) eq 'HASH') {
 4626:         foreach my $item (keys(%{$settings})) {
 4627:             if (ref($settings->{$item}) eq 'HASH') {
 4628:                 my $num = $settings->{$item}{'order'};
 4629:                 $ordered{$num} = $item;
 4630:             }
 4631:         }
 4632:     }
 4633:     my $confname = $dom.'-domainconfig';
 4634:     my $switchserver = &check_switchserver($dom,$confname);
 4635:     my $maxnum = scalar(keys(%ordered));
 4636:     my $datatable;
 4637:     my %lt = &ltitools_names();
 4638:     my @courseroles = ('cc','in','ta','ep','st');
 4639:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 4640:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 4641:     if (keys(%ordered)) {
 4642:         my @items = sort { $a <=> $b } keys(%ordered);
 4643:         for (my $i=0; $i<@items; $i++) {
 4644:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4645:             my $item = $ordered{$items[$i]};
 4646:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 4647:             if (ref($settings->{$item}) eq 'HASH') {
 4648:                 $title = $settings->{$item}->{'title'};
 4649:                 $url = $settings->{$item}->{'url'};
 4650:                 $key = $settings->{$item}->{'key'};
 4651:                 $secret = $settings->{$item}->{'secret'};
 4652:                 $lifetime = $settings->{$item}->{'lifetime'};
 4653:                 my $image = $settings->{$item}->{'image'};
 4654:                 if ($image ne '') {
 4655:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 4656:                 }
 4657:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 4658:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 4659:                 } else {
 4660:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 4661:                 }
 4662:             }
 4663:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 4664:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 4665:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 4666:             for (my $k=0; $k<=$maxnum; $k++) {
 4667:                 my $vpos = $k+1;
 4668:                 my $selstr;
 4669:                 if ($k == $i) {
 4670:                     $selstr = ' selected="selected" ';
 4671:                 }
 4672:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4673:             }
 4674:             $datatable .= '</select>'.('&nbsp;'x2).
 4675:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 4676:                 &mt('Delete?').'</label></span></td>'.
 4677:                 '<td colspan="2">'.
 4678:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4679:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 4680:                 ('&nbsp;'x2).
 4681:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 4682:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 4683:                 ('&nbsp;'x2).
 4684:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 4685:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4686:                 ('&nbsp;'x2).
 4687:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 4688:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 4689:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 4690:                 '<br /><br />'.
 4691:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 4692:                 ' value="'.$url.'" /></span>'.
 4693:                 ('&nbsp;'x2).
 4694:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 4695:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 4696:                 ('&nbsp;'x2).
 4697:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 4698:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 4699:                 ('&nbsp;'x2).
 4700:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 4701:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 4702:                 '<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>'.
 4703:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 4704:                 '</fieldset>'.
 4705:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4706:                 '<span class="LC_nobreak">'.&mt('Display target:');
 4707:             my %currdisp;
 4708:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 4709:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 4710:                     $currdisp{'window'} = ' checked="checked"';
 4711:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 4712:                     $currdisp{'tab'} = ' checked="checked"';
 4713:                 } else {
 4714:                     $currdisp{'iframe'} = ' checked="checked"';
 4715:                 }
 4716:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 4717:                     $currdisp{'width'} = $1;
 4718:                 }
 4719:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 4720:                      $currdisp{'height'} = $1;
 4721:                 }
 4722:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 4723:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 4724:             } else {
 4725:                 $currdisp{'iframe'} = ' checked="checked"';
 4726:             }
 4727:             foreach my $disp ('iframe','tab','window') {
 4728:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 4729:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 4730:             }
 4731:             $datatable .= ('&nbsp;'x4);
 4732:             foreach my $dimen ('width','height') {
 4733:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4734:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 4735:                               ('&nbsp;'x2);
 4736:             }
 4737:             $datatable .= '</span><br />'.
 4738:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4739:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 4740:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4741:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 4742:                           '</textarea></div><div style=""></div><br />';
 4743:             my %units = (
 4744:                           'passback' => 'days',
 4745:                           'roster'   => 'seconds',
 4746:                         );
 4747:             foreach my $extra ('passback','roster') {
 4748:                 my $validsty = 'none';
 4749:                 my $currvalid;
 4750:                 my $checkedon = '';
 4751:                 my $checkedoff = ' checked="checked"';
 4752:                 if ($settings->{$item}->{$extra}) {
 4753:                     $checkedon = $checkedoff;
 4754:                     $checkedoff = '';
 4755:                     $validsty = 'inline-block';
 4756:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 4757:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 4758:                     }
 4759:                 }
 4760:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 4761:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 4762:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 4763:                               &mt('No').'</label>'.('&nbsp;'x2).
 4764:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 4765:                               &mt('Yes').'</label></span></div>'.
 4766:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 4767:                               '<span class="LC_nobreak">'.
 4768:                               &mt("at least [_1] $units{$extra} after launch",
 4769:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 4770:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 4771:             }
 4772:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 4773:             if ($imgsrc) {
 4774:                 $datatable .= $imgsrc.
 4775:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 4776:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 4777:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 4778:             } else {
 4779:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4780:             }
 4781:             if ($switchserver) {
 4782:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4783:             } else {
 4784:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 4785:             }
 4786:             $datatable .= '</span></fieldset>';
 4787:             my (%checkedfields,%rolemaps,$userincdom);
 4788:             if (ref($settings->{$item}) eq 'HASH') {
 4789:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 4790:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 4791:                 }
 4792:                 $userincdom = $settings->{$item}->{'incdom'};
 4793:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 4794:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 4795:                     $checkedfields{'roles'} = 1;
 4796:                 }
 4797:             }
 4798:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4799:                           '<span class="LC_nobreak">';
 4800:             my $userfieldstyle = 'display:none;';
 4801:             my $seluserdom = '';
 4802:             my $unseluserdom = ' selected="selected"';
 4803:             foreach my $field (@fields) {
 4804:                 my ($checked,$onclick,$id,$spacer);
 4805:                 if ($checkedfields{$field}) {
 4806:                     $checked = ' checked="checked"';
 4807:                 }
 4808:                 if ($field eq 'user') {
 4809:                     $id = ' id="ltitools_user_field_'.$i.'"';
 4810:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 4811:                     if ($checked) {
 4812:                         $userfieldstyle = 'display:inline-block';
 4813:                         if ($userincdom) {
 4814:                             $seluserdom = $unseluserdom;
 4815:                             $unseluserdom = '';
 4816:                         }
 4817:                     }
 4818:                 } else {
 4819:                     $spacer = ('&nbsp;' x2);
 4820:                 }
 4821:                 $datatable .= '<label>'.
 4822:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 4823:                               $lt{$field}.'</label>'.$spacer;
 4824:             }
 4825:             $datatable .= '</span>';
 4826:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 4827:                           '<span class="LC_nobreak"> : '.
 4828:                           '<select name="ltitools_userincdom_'.$i.'">'.
 4829:                           '<option value="">'.&mt('Select').'</option>'.
 4830:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 4831:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 4832:                           '</select></span></div>';
 4833:             $datatable .= '</fieldset>'.
 4834:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 4835:             foreach my $role (@courseroles) {
 4836:                 my ($selected,$selectnone);
 4837:                 if (!$rolemaps{$role}) {
 4838:                     $selectnone = ' selected="selected"';
 4839:                 }
 4840:                 $datatable .= '<td style="text-align: center">'. 
 4841:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 4842:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 4843:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 4844:                 foreach my $ltirole (@ltiroles) {
 4845:                     unless ($selectnone) {
 4846:                         if ($rolemaps{$role} eq $ltirole) {
 4847:                             $selected = ' selected="selected"';
 4848:                         } else {
 4849:                             $selected = '';
 4850:                         }
 4851:                     }
 4852:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 4853:                 }
 4854:                 $datatable .= '</select></td>';
 4855:             }
 4856:             $datatable .= '</tr></table></fieldset>';
 4857:             my %courseconfig;
 4858:             if (ref($settings->{$item}) eq 'HASH') {
 4859:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 4860:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 4861:                 }
 4862:             }
 4863:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 4864:             foreach my $item ('label','title','target','linktext','explanation','append') {
 4865:                 my $checked;
 4866:                 if ($courseconfig{$item}) {
 4867:                     $checked = ' checked="checked"';
 4868:                 }
 4869:                 $datatable .= '<label>'.
 4870:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 4871:                        $lt{'crs'.$item}.'</label>&nbsp; '."\n";
 4872:             }
 4873:             $datatable .= '</span></fieldset>'.
 4874:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 4875:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 4876:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 4877:                 my %custom = %{$settings->{$item}->{'custom'}};
 4878:                 if (keys(%custom) > 0) {
 4879:                     foreach my $key (sort(keys(%custom))) {
 4880:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 4881:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 4882:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 4883:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 4884:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 4885:                     }
 4886:                 }
 4887:             }
 4888:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 4889:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 4890:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 4891:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 4892:             $datatable .= '</table></fieldset></td></tr>'."\n";
 4893:             $itemcount ++;
 4894:         }
 4895:     }
 4896:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4897:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 4898:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 4899:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 4900:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 4901:     for (my $k=0; $k<$maxnum+1; $k++) {
 4902:         my $vpos = $k+1;
 4903:         my $selstr;
 4904:         if ($k == $maxnum) {
 4905:             $selstr = ' selected="selected" ';
 4906:         }
 4907:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 4908:     }
 4909:     $datatable .= '</select>&nbsp;'."\n".
 4910:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 4911:                   '<td colspan="2">'.
 4912:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 4913:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 4914:                   ('&nbsp;'x2).
 4915:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 4916:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 4917:                   ('&nbsp;'x2).
 4918:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 4919:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 4920:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 4921:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 4922:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 4923:                   '<br />'.
 4924:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 4925:                   ('&nbsp;'x2).
 4926:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 4927:                   ('&nbsp;'x2).
 4928:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 4929:                   ('&nbsp;'x2).
 4930:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 4931:                   '<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".
 4932:                   '</fieldset>'.
 4933:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 4934:                   '<span class="LC_nobreak">'.&mt('Display target:');
 4935:     my %defaultdisp;
 4936:     $defaultdisp{'iframe'} = ' checked="checked"';
 4937:     foreach my $disp ('iframe','tab','window') {
 4938:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 4939:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 4940:     }
 4941:     $datatable .= ('&nbsp;'x4);
 4942:     foreach my $dimen ('width','height') {
 4943:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 4944:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 4945:                       ('&nbsp;'x2);
 4946:     }
 4947:     $datatable .= '</span><br />'.
 4948:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 4949:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 4950:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 4951:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 4952:                   '</div><div style=""></div><br />';
 4953:     my %units = (
 4954:                   'passback' => 'days',
 4955:                   'roster'   => 'seconds',
 4956:                 );
 4957:     my %defaulttimes = (
 4958:                      'passback' => '7',
 4959:                      'roster'   => '300',
 4960:                    );
 4961:     foreach my $extra ('passback','roster') {
 4962:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 4963:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 4964:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 4965:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 4966:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 4967:                       &mt('Yes').'</label></span></div>'.
 4968:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 4969:                       '<span class="LC_nobreak">'.
 4970:                       &mt("at least [_1] $units{$extra} after launch",
 4971:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 4972:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 4973:     }
 4974:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 4975:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 4976:     if ($switchserver) {
 4977:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 4978:     } else {
 4979:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 4980:     }
 4981:     $datatable .= '</span></fieldset>'.
 4982:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 4983:                   '<span class="LC_nobreak">';
 4984:     foreach my $field (@fields) {
 4985:         my ($id,$onclick,$spacer);
 4986:         if ($field eq 'user') {
 4987:             $id = ' id="ltitools_user_field_add"';
 4988:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 4989:         } else {
 4990:             $spacer = ('&nbsp;' x2);
 4991:         }
 4992:         $datatable .= '<label>'.
 4993:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 4994:                       $lt{$field}.'</label>'.$spacer;
 4995:     }
 4996:     $datatable .= '</span>'.
 4997:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 4998:                   '<span class="LC_nobreak"> : '.
 4999:                   '<select name="ltitools_userincdom_add">'.
 5000:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5001:                   '<option value="0">'.&mt('username').'</option>'.
 5002:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5003:                   '</select></span></div></fieldset>';
 5004:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5005:     foreach my $role (@courseroles) {
 5006:         my ($checked,$checkednone);
 5007:         $datatable .= '<td style="text-align: center">'.
 5008:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5009:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5010:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5011:         foreach my $ltirole (@ltiroles) {
 5012:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5013:         }
 5014:         $datatable .= '</select></td>';
 5015:     }
 5016:     $datatable .= '</tr></table></fieldset>'.
 5017:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5018:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5019:         $datatable .= '<label>'.
 5020:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5021:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5022:     }
 5023:     $datatable .= '</span></fieldset>'.
 5024:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5025:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5026:                   '<tr><td><span class="LC_nobreak">'.
 5027:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5028:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5029:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5030:                   '</table></fieldset>'."\n".
 5031:                   '</td>'."\n".
 5032:                   '</tr>'."\n";
 5033:     $itemcount ++;
 5034:     return $datatable;
 5035: }
 5036: 
 5037: sub ltitools_names {
 5038:     my %lt = &Apache::lonlocal::texthash(
 5039:                                           'title'          => 'Title',
 5040:                                           'version'        => 'Version',
 5041:                                           'msgtype'        => 'Message Type',
 5042:                                           'sigmethod'      => 'Signature Method',
 5043:                                           'url'            => 'URL',
 5044:                                           'key'            => 'Key',
 5045:                                           'lifetime'       => 'Nonce lifetime (s)',
 5046:                                           'secret'         => 'Secret',
 5047:                                           'icon'           => 'Icon',   
 5048:                                           'user'           => 'User',
 5049:                                           'fullname'       => 'Full Name',
 5050:                                           'firstname'      => 'First Name',
 5051:                                           'lastname'       => 'Last Name',
 5052:                                           'email'          => 'E-mail',
 5053:                                           'roles'          => 'Role',
 5054:                                           'window'         => 'Window',
 5055:                                           'tab'            => 'Tab',
 5056:                                           'iframe'         => 'iFrame',
 5057:                                           'height'         => 'Height',
 5058:                                           'width'          => 'Width',
 5059:                                           'linktext'       => 'Default Link Text',
 5060:                                           'explanation'    => 'Default Explanation',
 5061:                                           'passback'       => 'Tool can return grades:',
 5062:                                           'roster'         => 'Tool can retrieve roster:',
 5063:                                           'crstarget'      => 'Display target',
 5064:                                           'crslabel'       => 'Course label',
 5065:                                           'crstitle'       => 'Course title', 
 5066:                                           'crslinktext'    => 'Link Text',
 5067:                                           'crsexplanation' => 'Explanation',
 5068:                                           'crsappend'      => 'Provider URL',
 5069:                                         );
 5070:     return %lt;
 5071: }
 5072: 
 5073: sub print_proctoring {
 5074:     my ($dom,$settings,$rowtotal) = @_;
 5075:     my $itemcount = 1;
 5076:     my (%ordered,%providernames,%current,%currentdef);
 5077:     my $confname = $dom.'-domainconfig';
 5078:     my $switchserver = &check_switchserver($dom,$confname);
 5079:     if (ref($settings) eq 'HASH') {
 5080:         foreach my $item (keys(%{$settings})) {
 5081:             if (ref($settings->{$item}) eq 'HASH') {
 5082:                 my $num = $settings->{$item}{'order'};
 5083:                 $ordered{$num} = $item;
 5084:             }
 5085:         }
 5086:     } else {
 5087:         %ordered = (
 5088:                      1 => 'proctorio',
 5089:                      2 => 'examity',
 5090:                    );
 5091:     }
 5092:     %providernames = &proctoring_providernames();
 5093:     my $maxnum = scalar(keys(%ordered));
 5094:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5095:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5096:     if (ref($requref) eq 'HASH') {
 5097:         %requserfields = %{$requref};
 5098:     }
 5099:     if (ref($opturef) eq 'HASH') {
 5100:         %optuserfields = %{$opturef};
 5101:     }
 5102:     if (ref($defref) eq 'HASH') {
 5103:         %defaults = %{$defref};
 5104:     }
 5105:     if (ref($extref) eq 'HASH') {
 5106:         %extended = %{$extref};
 5107:     }
 5108:     if (ref($crsref) eq 'HASH') {
 5109:         %crsconf = %{$crsref};
 5110:     }
 5111:     if (ref($rolesref) eq 'ARRAY') {
 5112:         @courseroles = @{$rolesref};
 5113:     }
 5114:     if (ref($ltiref) eq 'ARRAY') {
 5115:         @ltiroles = @{$ltiref};
 5116:     }
 5117:     my $datatable;
 5118:     my $css_class;
 5119:     if (keys(%ordered)) {
 5120:         my @items = sort { $a <=> $b } keys(%ordered);
 5121:         for (my $i=0; $i<@items; $i++) {
 5122:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5123:             my $provider = $ordered{$items[$i]};
 5124:             my $optionsty = 'none';
 5125:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5126:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5127:             if (ref($settings) eq 'HASH') {
 5128:                 if (ref($settings->{$provider}) eq 'HASH') {
 5129:                     %current = %{$settings->{$provider}};
 5130:                     if ($current{'available'}) {
 5131:                         $optionsty = 'block';
 5132:                         $available = 1;
 5133:                     }
 5134:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5135:                         $lifetime = $current{'lifetime'};
 5136:                     }
 5137:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5138:                         $version = $current{'version'};
 5139:                     }
 5140:                     if ($current{'image'} ne '') {
 5141:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5142:                     }
 5143:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5144:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5145:                     }
 5146:                     $userincdom = $current{'incdom'};
 5147:                     if (ref($current{'roles'}) eq 'HASH') {
 5148:                         %rolemaps = %{$current{'roles'}};
 5149:                         $checkedfields{'roles'} = 1;
 5150:                     }
 5151:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5152:                         foreach my $val (@{$current{'defaults'}}) {
 5153:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5154:                                 $inuse{$val} = 1;
 5155:                             } else {
 5156:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5157:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5158:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5159:                                             $inuse{$poss} = $val;
 5160:                                             last;
 5161:                                         }
 5162:                                     }
 5163:                                 }
 5164:                             }
 5165:                         }
 5166:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5167:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5168:                             my $currval = $current{'defaults'}{$key}; 
 5169:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5170:                                 $inuse{$key} = 1;
 5171:                             } else {
 5172:                                 my $match;
 5173:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5174:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5175:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5176:                                             $inuse{$poss} = $key;
 5177:                                             last;
 5178:                                         }
 5179:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5180:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5181:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5182:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5183:                                                     $currentdef{$inner} = $currval;
 5184:                                                     $match = 1;
 5185:                                                     last;
 5186:                                                 }
 5187:                                             } elsif ($inner eq $key) {
 5188:                                                 $currentdef{$key} = $currval;
 5189:                                                 $match = 1;
 5190:                                                 last;
 5191:                                             }
 5192:                                         }
 5193:                                     }
 5194:                                     last if ($match);
 5195:                                 }
 5196:                             }
 5197:                         }
 5198:                     }
 5199:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5200:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5201:                     }
 5202:                 }
 5203:             }
 5204:             my %lt = &proctoring_titles($provider);
 5205:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5206:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5207:             my %checkedavailable = (
 5208:                                    yes => '',
 5209:                                    no  => ' checked="checked"',
 5210:                                  );
 5211:             if ($available) {
 5212:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5213:                 $checkedavailable{'no'} = '';
 5214:             }
 5215:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5216:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5217:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 5218:             for (my $k=0; $k<$maxnum; $k++) {
 5219:                 my $vpos = $k+1;
 5220:                 my $selstr;
 5221:                 if ($k == $i) {
 5222:                     $selstr = ' selected="selected" ';
 5223:                 }
 5224:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5225:             }
 5226:             if ($version eq '') {
 5227:                 if ($provider eq 'proctorio') {
 5228:                     $version = '1.0';
 5229:                 } elsif ($provider eq 'examity') {
 5230:                     $version = '1.1';
 5231:                 }
 5232:             }
 5233:             if ($lifetime eq '') {
 5234:                 $lifetime = '300';
 5235:             }
 5236:             $datatable .=
 5237:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 5238:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 5239:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5240:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 5241:                 '</td>'.
 5242:                 '<td colspan="2">'.
 5243:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 5244:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 5245:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 5246:                 ('&nbsp;'x2).
 5247:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 5248:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5249:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5250:                 ('&nbsp;'x2).
 5251:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 5252:                 '<br />'.
 5253:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 5254:                 '<br />'.
 5255:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 5256:                 ('&nbsp;'x2).
 5257:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 5258:                 '<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";
 5259:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5260:             if ($imgsrc) {
 5261:                 $datatable .= $imgsrc.
 5262:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 5263:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 5264:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 5265:             }
 5266:             $datatable .= '&nbsp;';
 5267:             if ($switchserver) {
 5268:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5269:             } else {
 5270:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 5271:             }
 5272:             unless ($imgsrc) {
 5273:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 5274:             }
 5275:             $datatable .= '</fieldset>'."\n";
 5276:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 5277:                 if (@{$requserfields{$provider}} > 0) {
 5278:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 5279:                     foreach my $field (@{$requserfields{$provider}}) {
 5280:                         $datatable .= '<span class="LC_nobreak">'.
 5281:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 5282:                                       $lt{$field}.'</label>';
 5283:                         if ($field eq 'user') {
 5284:                             my $seluserdom = '';
 5285:                             my $unseluserdom = ' selected="selected"';
 5286:                             if ($userincdom) {
 5287:                                 $seluserdom = $unseluserdom;
 5288:                                 $unseluserdom = '';
 5289:                             }
 5290:                             $datatable .= ':&nbsp;'.
 5291:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 5292:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 5293:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 5294:                                 '</select>&nbsp;';
 5295:                         } else {
 5296:                             $datatable .= '&nbsp;';
 5297:                             if ($field eq 'roles') {
 5298:                                 $showroles = 1; 
 5299:                             } 
 5300:                         }
 5301:                         $datatable .= '</span> ';
 5302:                     }
 5303:                 }
 5304:                 $datatable .= '</fieldset>'."\n";
 5305:             }
 5306:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 5307:                 if (@{$optuserfields{$provider}} > 0) {
 5308:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 5309:                     foreach my $field (@{$optuserfields{$provider}}) {
 5310:                         my $checked;
 5311:                         if ($checkedfields{$field}) {
 5312:                             $checked = ' checked="checked"';
 5313:                         }
 5314:                         $datatable .= '<span class="LC_nobreak">'.
 5315:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 5316:                     }
 5317:                     $datatable .= '</fieldset>'."\n";
 5318:                 }
 5319:             }
 5320:             if (ref($defaults{$provider}) eq 'ARRAY') {
 5321:                 if (@{$defaults{$provider}}) {
 5322:                     my (%options,@selectboxes);
 5323:                     if (ref($extended{$provider}) eq 'HASH') {
 5324:                         %options = %{$extended{$provider}};
 5325:                     }
 5326:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 5327:                     my ($rem,$numinrow,$dropdowns);
 5328:                     if ($provider eq 'proctorio') { 
 5329:                         $datatable .= '<table>';
 5330:                         $numinrow = 4;
 5331:                     }
 5332:                     my $i = 0;
 5333:                     foreach my $field (@{$defaults{$provider}}) {
 5334:                         my $checked;
 5335:                         if ($inuse{$field}) {
 5336:                             $checked = ' checked="checked"';
 5337:                         }
 5338:                         if ($provider eq 'examity') {
 5339:                             if ($field eq 'display') {
 5340:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 5341:                                 foreach my $option ('iframe','tab','window') {
 5342:                                     my $checkdisp;
 5343:                                     if ($currentdef{'target'} eq $option) {
 5344:                                         $checkdisp = ' checked="checked"';
 5345:                                     }
 5346:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 5347:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 5348:                                 }
 5349:                                 $datatable .= ('&nbsp;'x4);
 5350:                                 foreach my $dimen ('width','height') {
 5351:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 5352:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 5353:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 5354:                                                   ('&nbsp;'x2);
 5355:                                 }
 5356:                                 $datatable .= '</span><br />'.
 5357:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 5358:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 5359:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 5360:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 5361:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 5362:                                               $currentdef{'explanation'}.
 5363:                                               '</textarea></div><div style=""></div><br />';
 5364:                             }
 5365:                         } else {
 5366:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 5367:                                 my ($output,$selnone);
 5368:                                 unless ($checked) {
 5369:                                     $selnone = ' selected="selected"';
 5370:                                 }
 5371:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 5372:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 5373:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 5374:                                 foreach my $option (@{$options{$field}}) {
 5375:                                     my $sel; 
 5376:                                     if ($inuse{$field} eq $option) {
 5377:                                         $sel = ' selected="selected"';
 5378:                                     }
 5379:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 5380:                                 }
 5381:                                 $output .= '</select></span>';
 5382:                                 push(@selectboxes,$output);
 5383:                             } else {
 5384:                                 $rem = $i%($numinrow);
 5385:                                 if ($rem == 0) {
 5386:                                     if ($i > 0) {
 5387:                                         $datatable .= '</tr>';
 5388:                                     }
 5389:                                     $datatable .= '<tr>';
 5390:                                 }
 5391:                                 $datatable .= '<td class="LC_left_item">'.
 5392:                                               '<span class="LC_nobreak">'.
 5393:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 5394:                                               $fieldtitles{$field}.'</label></span></td>';
 5395:                                 $i++;
 5396:                             }
 5397:                         }
 5398:                     }
 5399:                     if ($provider eq 'proctorio') {
 5400:                         if ($numinrow) {
 5401:                             $rem = $i%$numinrow;
 5402:                         }
 5403:                         my $colsleft = $numinrow - $rem;
 5404:                         if ($colsleft > 1) {
 5405:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5406:                         } else {
 5407:                             $datatable .= '<td class="LC_left_item">';
 5408:                         }
 5409:                         $datatable .= '&nbsp;'.
 5410:                                       '</td></tr></table>';
 5411:                         if (@selectboxes) {
 5412:                             $datatable .= '<hr /><table>';
 5413:                             $numinrow = 2;
 5414:                             for (my $i=0; $i<@selectboxes; $i++) {
 5415:                                 $rem = $i%($numinrow);
 5416:                                 if ($rem == 0) {
 5417:                                     if ($i > 0) {
 5418:                                         $datatable .= '</tr>';
 5419:                                     }
 5420:                                     $datatable .= '<tr>';
 5421:                                 }
 5422:                                 $datatable .= '<td class="LC_left_item">'.
 5423:                                               $selectboxes[$i].'</td>';
 5424:                             }
 5425:                             if ($numinrow) {
 5426:                                 $rem = $i%$numinrow;
 5427:                             }
 5428:                             $colsleft = $numinrow - $rem;
 5429:                             if ($colsleft > 1) {
 5430:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5431:                             } else {
 5432:                                 $datatable .= '<td class="LC_left_item">';
 5433:                             }
 5434:                             $datatable .= '&nbsp;'.
 5435:                                           '</td></tr></table>';
 5436:                         }
 5437:                     }
 5438:                     $datatable .= '</fieldset>';
 5439:                 }
 5440:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 5441:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5442:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 5443:                     my ($rem,$numinrow);
 5444:                     if ($provider eq 'proctorio') {
 5445:                         $datatable .= '<table>';
 5446:                         $numinrow = 4;
 5447:                     }
 5448:                     my $i = 0;
 5449:                     foreach my $item (@{$crsconf{$provider}}) {
 5450:                         my $name;
 5451:                         if ($provider eq 'examity') {
 5452:                             $name = $lt{'crs'.$item};
 5453:                         } elsif ($provider eq 'proctorio') {
 5454:                             $name = $fieldtitles{$item};
 5455:                             $rem = $i%($numinrow);
 5456:                             if ($rem == 0) {
 5457:                                 if ($i > 0) {
 5458:                                     $datatable .= '</tr>';
 5459:                                 }
 5460:                                 $datatable .= '<tr>';
 5461:                             }
 5462:                             $datatable .= '<td class="LC_left_item>';
 5463:                         }
 5464:                         my $checked;
 5465:                         if ($crsconfig{$item}) {
 5466:                             $checked = ' checked="checked"';
 5467:                         }
 5468:                         $datatable .= '<span class="LC_nobreak"><label>'.
 5469:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 5470:                                       $name.'</label></span>';
 5471:                         if ($provider eq 'examity') {
 5472:                             $datatable .= '&nbsp; ';
 5473:                         }
 5474:                         $datatable .= "\n";
 5475:                         $i++;
 5476:                     }
 5477:                     if ($provider eq 'proctorio') {
 5478:                         if ($numinrow) {
 5479:                             $rem = $i%$numinrow;
 5480:                         }
 5481:                         my $colsleft = $numinrow - $rem;
 5482:                         if ($colsleft > 1) {
 5483:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 5484:                         } else {
 5485:                             $datatable .= '<td class="LC_left_item">';
 5486:                         }
 5487:                         $datatable .= '&nbsp;'.
 5488:                                       '</td></tr></table>';
 5489:                     }
 5490:                     $datatable .= '</fieldset>';
 5491:                 }
 5492:                 if ($showroles) {
 5493:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5494:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 5495:                     foreach my $role (@courseroles) {
 5496:                         my ($selected,$selectnone);
 5497:                         if (!$rolemaps{$role}) {
 5498:                             $selectnone = ' selected="selected"';
 5499:                         }
 5500:                         $datatable .= '<td style="text-align: center">'.
 5501:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5502:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 5503:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5504:                         foreach my $ltirole (@ltiroles) {
 5505:                             unless ($selectnone) {
 5506:                                 if ($rolemaps{$role} eq $ltirole) {
 5507:                                     $selected = ' selected="selected"';
 5508:                                 } else {
 5509:                                     $selected = '';
 5510:                                 }
 5511:                             }
 5512:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5513:                         }
 5514:                         $datatable .= '</select></td>';
 5515:                     }
 5516:                     $datatable .= '</tr></table></fieldset>'.
 5517:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 5518:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 5519:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5520:                                   '<tr><td></td><td>lms</td>'.
 5521:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 5522:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 5523:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 5524:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 5525:                         my %custom = %{$settings->{$provider}->{'custom'}};
 5526:                         if (keys(%custom) > 0) {
 5527:                             foreach my $key (sort(keys(%custom))) {
 5528:                                 next if ($key eq 'lms');
 5529:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 5530:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 5531:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5532:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 5533:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 5534:                             }
 5535:                         }
 5536:                     }
 5537:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 5538:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 5539:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 5540:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 5541:                                   '</table></fieldset></td></tr>'."\n";
 5542:                 }
 5543:                 $datatable .= '</td></tr>';
 5544:             }
 5545:             $itemcount ++;
 5546:         }
 5547:     }
 5548:     return $datatable;
 5549: }
 5550: 
 5551: sub proctoring_data {
 5552:     my $requserfields = {
 5553:                       proctorio => ['user'],
 5554:                       examity   => ['roles','user'],
 5555:                      };
 5556:     my $optuserfields = {
 5557:                         proctorio => ['fullname'],
 5558:                         examity   => ['fullname','firstname','lastname','email'],
 5559:                      };
 5560:     my $defaults = {
 5561:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 5562:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 5563:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 5564:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 5565:                                 'reentry','calculator','whiteboard'],
 5566:                   examity   => ['display'],
 5567:                 };
 5568:     my $extended = { 
 5569:                   proctorio => {
 5570:                                  verifyid => ['verifyidauto','verifyidlive'],
 5571:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 5572:                                  tabslinks => ['notabs','linksonly'],
 5573:                                  reentry => ['noreentry','agentreentry'],
 5574:                                  calculator => ['calculatorbasic','calculatorsci'],
 5575:                                },
 5576:                   examity => {
 5577:                                display => {
 5578:                                            target      => ['iframe','tab','window'],
 5579:                                            width       => '',
 5580:                                            height      => '',
 5581:                                            linktext    => '',
 5582:                                            explanation => '',
 5583:                                           },
 5584:                              },
 5585:                 };
 5586:     my $crsconf = {
 5587:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 5588:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 5589:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 5590:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 5591:                                'reentry','calculator','whiteboard'],
 5592:                  examity => ['label','title','target','linktext','explanation','append'],
 5593:                };
 5594:     my $courseroles = ['cc','in','ta','ep','st'];
 5595:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 5596:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 5597: }
 5598: 
 5599: sub proctoring_titles {
 5600:     my ($item) = @_;
 5601:     my (%common_lt,%custom_lt);
 5602:     %common_lt = &Apache::lonlocal::texthash (
 5603:                      'avai'      => 'Available?',
 5604:                      'base'      => 'Basic Settings',
 5605:                      'requ'      => 'User data required to be sent on launch',
 5606:                      'optu'      => 'User data optionally sent on launch',
 5607:                      'udsl'      => 'User data sent on launch',
 5608:                      'defa'      => 'Defaults for items configurable in course',
 5609:                      'sigmethod' => 'Signature Method',
 5610:                      'key'       => 'Key',
 5611:                      'lifetime'  => 'Nonce lifetime (s)',
 5612:                      'secret'    => 'Secret',
 5613:                      'icon'      => 'Icon',
 5614:                      'fullname'  => 'Full Name',
 5615:                      'visible'   => 'Visible input',
 5616:                      'username'  => 'username',
 5617:                      'user'      => 'User',
 5618:                  );
 5619:     if ($item eq 'proctorio') {
 5620:         %custom_lt = &Apache::lonlocal::texthash (
 5621:                          'version'        => 'OAuth version',
 5622:                          'url'            => 'API URL',
 5623:                          'uname:dom'      => 'username-domain',
 5624:         );
 5625:     } elsif ($item eq 'examity') {
 5626:         %custom_lt = &Apache::lonlocal::texthash (
 5627:                          'version'        => 'LTI Version',
 5628:                          'url'            => 'URL',
 5629:                          'uname:dom'      => 'username:domain',
 5630:                          'msgtype'        => 'Message Type',
 5631:                          'firstname'      => 'First Name',
 5632:                          'lastname'       => 'Last Name',
 5633:                          'email'          => 'E-mail',
 5634:                          'roles'          => 'Role',
 5635:                          'crstarget'      => 'Display target',
 5636:                          'crslabel'       => 'Course label',
 5637:                          'crstitle'       => 'Course title', 
 5638:                          'crslinktext'    => 'Link Text',
 5639:                          'crsexplanation' => 'Explanation',
 5640:                          'crsappend'      => 'Provider URL',
 5641:         );
 5642:     }
 5643:     my %lt = (%common_lt,%custom_lt);
 5644:     return %lt;
 5645: }
 5646: 
 5647: sub proctoring_fieldtitles {
 5648:     my ($item) = @_;
 5649:     if ($item eq 'proctorio') {
 5650:         return &Apache::lonlocal::texthash (
 5651:                   'recordvideo' => 'Record video',
 5652:                   'recordaudio' => 'Record audio',
 5653:                   'recordscreen' => 'Record screen',
 5654:                   'recordwebtraffic' => 'Record web traffic',
 5655:                   'recordroomstart' => 'Record room scan',
 5656:                   'verifyvideo' => 'Verify webcam',
 5657:                   'verifyaudio' => 'Verify microphone',
 5658:                   'verifydesktop' => 'Verify desktop recording',
 5659:                   'verifyid' => 'Photo ID verification',
 5660:                   'verifysignature' => 'Require signature',
 5661:                   'fullscreen' => 'Fullscreen',
 5662:                   'clipboard' => 'Disable copy/paste',
 5663:                   'tabslinks' => 'New tabs/windows',
 5664:                   'closetabs' => 'Close other tabs',
 5665:                   'onescreen' => 'Limit to single screen',
 5666:                   'print' => 'Disable Printing',
 5667:                   'downloads' => 'Disable Downloads',
 5668:                   'cache' => 'Empty cache after exam',
 5669:                   'rightclick' => 'Disable right click',
 5670:                   'reentry' => 'Re-entry to exam',
 5671:                   'calculator' => 'Onscreen calculator',
 5672:                   'whiteboard' => 'Onscreen whiteboard',
 5673:                   'verifyidauto' => 'Automated verification',
 5674:                   'verifyidlive' => 'Live agent verification',
 5675:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 5676:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 5677:                   'fullscreensever' => 'Forced, navigation away ends exam',
 5678:                   'notabs' => 'Disaallowed',
 5679:                   'linksonly' => 'Allowed from links in exam',
 5680:                   'noreentry' => 'Disallowed',
 5681:                   'agentreentry' => 'Agent required for re-entry',
 5682:                   'calculatorbasic' => 'Basic',
 5683:                   'calculatorsci' => 'Scientific',
 5684:         );
 5685:     } elsif ($item eq 'examity') {
 5686:         return &Apache::lonlocal::texthash (
 5687:                 'target'         => 'Display target',   
 5688:                 'window'         => 'Window',
 5689:                 'tab'            => 'Tab',
 5690:                 'iframe'         => 'iFrame',
 5691:                 'height'         => 'Height (pixels)',
 5692:                 'width'          => 'Width (pixels)',
 5693:                 'linktext'       => 'Default Link Text',
 5694:                 'explanation'    => 'Default Explanation',
 5695:                 'append'         => 'Provider URL',
 5696:         );
 5697:     }
 5698: }
 5699: 
 5700: sub proctoring_providernames {
 5701:     return (
 5702:              proctorio => 'Proctorio',
 5703:              examity   => 'Examity',
 5704:            );
 5705: }
 5706: 
 5707: sub print_lti {
 5708:     my ($dom,$settings,$rowtotal) = @_;
 5709:     my $itemcount = 1;
 5710:     my $maxnum = 0;
 5711:     my $css_class;
 5712:     my %ordered;
 5713:     if (ref($settings) eq 'HASH') {
 5714:         foreach my $item (keys(%{$settings})) {
 5715:             if (ref($settings->{$item}) eq 'HASH') {
 5716:                 my $num = $settings->{$item}{'order'};
 5717:                 $ordered{$num} = $item;
 5718:             }
 5719:         }
 5720:     }
 5721:     my $maxnum = scalar(keys(%ordered));
 5722:     my $datatable;
 5723:     my %lt = &lti_names();
 5724:     if (keys(%ordered)) {
 5725:         my @items = sort { $a <=> $b } keys(%ordered);
 5726:         for (my $i=0; $i<@items; $i++) {
 5727:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5728:             my $item = $ordered{$items[$i]};
 5729:             my ($key,$secret,$lifetime,$consumer,$requser,$current);
 5730:             if (ref($settings->{$item}) eq 'HASH') {
 5731:                 $key = $settings->{$item}->{'key'};
 5732:                 $secret = $settings->{$item}->{'secret'};
 5733:                 $lifetime = $settings->{$item}->{'lifetime'};
 5734:                 $consumer = $settings->{$item}->{'consumer'};
 5735:                 $requser = $settings->{$item}->{'requser'};
 5736:                 $current = $settings->{$item};
 5737:             }
 5738:             my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 5739:             my %checkedrequser = (
 5740:                                    yes => ' checked="checked"',
 5741:                                    no  => '',
 5742:                                  );
 5743:             if (!$requser) {
 5744:                 $checkedrequser{'no'} = $checkedrequser{'yes'};
 5745:                 $checkedrequser{'yes'} = '';
 5746:             }
 5747:             my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 5748:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5749:                          .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 5750:             for (my $k=0; $k<=$maxnum; $k++) {
 5751:                 my $vpos = $k+1;
 5752:                 my $selstr;
 5753:                 if ($k == $i) {
 5754:                     $selstr = ' selected="selected" ';
 5755:                 }
 5756:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5757:             }
 5758:             $datatable .= '</select>'.('&nbsp;'x2).
 5759:                 '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 5760:                 &mt('Delete?').'</label></span></td>'.
 5761:                 '<td colspan="2">'.
 5762:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5763:                 '<span class="LC_nobreak">'.$lt{'consumer'}.
 5764:                 ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 5765:                 ('&nbsp;'x2).
 5766:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 5767:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5768:                 ('&nbsp;'x2).
 5769:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 5770:                 'value="'.$lifetime.'" size="3" /></span>'.
 5771:                 ('&nbsp;'x2).
 5772:                  '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 5773:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5774:                  '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 5775:                 '<br /><br />'.
 5776:                 '<span class="LC_nobreak">'.$lt{'key'}.
 5777:                 ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 5778:                 ('&nbsp;'x2).
 5779:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 5780:                 '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 5781:                 '<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>'.
 5782:                 '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 5783:                 '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 5784:             $itemcount ++;
 5785:         }
 5786:     }
 5787:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5788:     my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 5789:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5790:                   '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 5791:                   '<select name="lti_pos_add"'.$chgstr.'>';
 5792:     for (my $k=0; $k<$maxnum+1; $k++) {
 5793:         my $vpos = $k+1;
 5794:         my $selstr;
 5795:         if ($k == $maxnum) {
 5796:             $selstr = ' selected="selected" ';
 5797:         }
 5798:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5799:     }
 5800:     $datatable .= '</select>&nbsp;'."\n".
 5801:                   '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5802:                   '<td colspan="2">'.
 5803:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5804:                   '<span class="LC_nobreak">'.$lt{'consumer'}.
 5805:                   ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 5806:                   ('&nbsp;'x2).
 5807:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 5808:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5809:                   ('&nbsp;'x2).
 5810:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 5811:                   ('&nbsp;'x2).
 5812:                   '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 5813:                   '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 5814:                   '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 5815:                   '<br /><br />'.
 5816:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 5817:                   ('&nbsp;'x2).
 5818:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 5819:                   '<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".
 5820:                   '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 5821:                   '</td>'."\n".
 5822:                   '</tr>'."\n";
 5823:     $$rowtotal ++;
 5824:     return $datatable;;
 5825: }
 5826: 
 5827: sub lti_names {
 5828:     my %lt = &Apache::lonlocal::texthash(
 5829:                                           'version'   => 'LTI Version',
 5830:                                           'url'       => 'URL',
 5831:                                           'key'       => 'Key',
 5832:                                           'lifetime'  => 'Nonce lifetime (s)',
 5833:                                           'consumer'  => 'Consumer',
 5834:                                           'secret'    => 'Secret',
 5835:                                           'requser'   => "User's identity sent",
 5836:                                           'email'     => 'Email address',
 5837:                                           'sourcedid' => 'User ID',
 5838:                                           'other'     => 'Other',
 5839:                                           'passback'  => 'Can return grades to Consumer:',
 5840:                                           'roster'    => 'Can retrieve roster from Consumer:',
 5841:                                           'topmenu'   => 'Display LON-CAPA page header',
 5842:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 5843:                                         );
 5844:     return %lt;
 5845: }
 5846: 
 5847: sub lti_options {
 5848:     my ($num,$current,$itemcount,%lt) = @_;
 5849:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 5850:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 5851:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 5852:     $checked{'makecrs'}{'N'} = '  checked="checked"';
 5853:     $checked{'mapcrstype'} = {};
 5854:     $checked{'makeuser'} = {};
 5855:     $checked{'selfenroll'} = {};
 5856:     $checked{'crssec'} = {};
 5857:     $checked{'crssecsrc'} = {};
 5858:     $checked{'lcauth'} = {};
 5859:     $checked{'menuitem'} = {};
 5860:     if ($num eq 'add') {
 5861:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 5862:     }
 5863:     my $userfieldsty = 'none';
 5864:     my $crsfieldsty = 'none';
 5865:     my $crssecfieldsty = 'none';
 5866:     my $secsrcfieldsty = 'none';
 5867:     my $callbacksty = 'none';
 5868:     my $passbacksty = 'none';
 5869:     my $optionsty = 'block';
 5870:     my $lcauthparm;
 5871:     my $lcauthparmstyle = 'display:none';
 5872:     my $lcauthparmtext;
 5873:     my $menusty;
 5874:     my $numinrow = 4;
 5875:     my %menutitles = &ltimenu_titles();
 5876: 
 5877:     if (ref($current) eq 'HASH') {
 5878:         if (!$current->{'requser'}) {
 5879:             $optionsty = 'none';
 5880:         }
 5881:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 5882:             $checked{'mapuser'}{'sourcedid'} = '';
 5883:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 5884:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 5885:             } else {
 5886:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 5887:                 $userfield = $current->{'mapuser'};
 5888:                 $userfieldsty = 'inline-block';
 5889:             }
 5890:         }
 5891:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 5892:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 5893:             if ($current->{'mapcrs'} eq 'context_id') {
 5894:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 5895:             } else {
 5896:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 5897:                 $cidfield = $current->{'mapcrs'};
 5898:                 $crsfieldsty = 'inline-block';
 5899:             }
 5900:         }
 5901:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 5902:             foreach my $type (@{$current->{'mapcrstype'}}) {
 5903:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 5904:             }
 5905:         }
 5906:         if ($current->{'makecrs'}) {
 5907:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 5908:         }
 5909:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 5910:             foreach my $role (@{$current->{'makeuser'}}) {
 5911:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 5912:             }
 5913:         }
 5914:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 5915:             $checked{'lcauth'}{$1} = ' checked="checked"';
 5916:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 5917:                 $lcauthparm = $current->{'lcauthparm'};
 5918:                 $lcauthparmstyle = 'display:table-row'; 
 5919:                 if ($current->{'lcauth'} eq 'localauth') {
 5920:                     $lcauthparmtext = &mt('Local auth argument');
 5921:                 } else {
 5922:                     $lcauthparmtext = &mt('Kerberos domain');
 5923:                 }
 5924:             }
 5925:         }
 5926:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 5927:             foreach my $role (@{$current->{'selfenroll'}}) {
 5928:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 5929:             }
 5930:         }
 5931:         if (ref($current->{'maproles'}) eq 'HASH') {
 5932:             %rolemaps = %{$current->{'maproles'}};
 5933:         }
 5934:         if ($current->{'section'} ne '') {
 5935:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 5936:             $crssecfieldsty = 'inline-block';
 5937:             if ($current->{'section'} eq 'course_section_sourcedid') {
 5938:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 5939:             } else {
 5940:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 5941:                 $crssecsrc = $current->{'section'};
 5942:                 $secsrcfieldsty = 'inline-block';
 5943:             }
 5944:         } else {
 5945:             $checked{'crssec'}{'N'} = ' checked="checked"';
 5946:         }
 5947:         if ($current->{'callback'} ne '') {
 5948:             $callback = $current->{'callback'};
 5949:             $checked{'callback'}{'Y'} = ' checked="checked"';
 5950:             $callbacksty = 'inline-block';
 5951:         } else {
 5952:             $checked{'callback'}{'N'} = ' checked="checked"';
 5953:         }
 5954:         if ($current->{'topmenu'}) {
 5955:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 5956:         } else {
 5957:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 5958:         }
 5959:         if ($current->{'inlinemenu'}) {
 5960:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 5961:         } else {
 5962:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 5963:         }
 5964:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 5965:             $menusty = 'inline-block';
 5966:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 5967:                 foreach my $item (@{$current->{'lcmenu'}}) {
 5968:                     if (exists($menutitles{$item})) {
 5969:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 5970:                     }
 5971:                 }
 5972:             }
 5973:         } else {
 5974:             $menusty = 'none';
 5975:         }
 5976:     } else {
 5977:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 5978:         $checked{'crssec'}{'N'} = ' checked="checked"';
 5979:         $checked{'callback'}{'N'} = ' checked="checked"';
 5980:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 5981:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 5982:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 5983:         $menusty = 'inline-block'; 
 5984:     }
 5985:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 5986:     my %coursetypetitles = &Apache::lonlocal::texthash (
 5987:                                official   => 'Official',
 5988:                                unofficial => 'Unofficial',
 5989:                                community  => 'Community',
 5990:                                textbook   => 'Textbook',
 5991:                                placement  => 'Placement Test',
 5992:                                lti        => 'LTI Provider',
 5993:     );
 5994:     my @authtypes = ('internal','krb4','krb5','localauth');
 5995:     my %shortauth = (
 5996:                      internal => 'int',
 5997:                      krb4 => 'krb4',
 5998:                      krb5 => 'krb5',
 5999:                      localauth  => 'loc'
 6000:                     );
 6001:     my %authnames = &authtype_names();
 6002:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6003:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6004:     my @courseroles = ('cc','in','ta','ep','st');
 6005:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6006:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6007:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6008:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6009:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6010:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6011:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6012:     my $output = '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6013:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6014:     foreach my $option ('sourcedid','email','other') {
 6015:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6016:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6017:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6018:     }
 6019:     $output .= '</span></div>'.
 6020:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6021:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6022:                'value="'.$userfield.'" /></div></fieldset>'.
 6023:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 6024:     foreach my $ltirole (@lticourseroles) {
 6025:         my ($selected,$selectnone);
 6026:         if ($rolemaps{$ltirole} eq '') {
 6027:             $selectnone = ' selected="selected"';
 6028:         }
 6029:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 6030:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 6031:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6032:         foreach my $role (@courseroles) {
 6033:             unless ($selectnone) {
 6034:                 if ($rolemaps{$ltirole} eq $role) {
 6035:                     $selected = ' selected="selected"';
 6036:                 } else {
 6037:                     $selected = '';
 6038:                 }
 6039:             }
 6040:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 6041:                        &Apache::lonnet::plaintext($role,'Course').
 6042:                        '</option>';
 6043:         }
 6044:         $output .= '</select></td>';
 6045:     }
 6046:     $output .= '</tr></table></fieldset>'.
 6047:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6048:     foreach my $ltirole (@ltiroles) {
 6049:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6050:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 6051:     }
 6052:     $output .= '</fieldset>'.
 6053:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 6054:                '<table>'.
 6055:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 6056:                '</table>'.
 6057:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 6058:                '<td class="LC_left_item">';
 6059:     foreach my $auth ('lti',@authtypes) {
 6060:         my $authtext;
 6061:         if ($auth eq 'lti') {
 6062:             $authtext = &mt('None');
 6063:         } else {
 6064:             $authtext = $authnames{$shortauth{$auth}};
 6065:         }
 6066:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 6067:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 6068:                    $authtext.'</label></span> &nbsp;';
 6069:     }
 6070:     $output .= '</td></tr>'.
 6071:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 6072:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 6073:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 6074:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 6075:                '</table></fieldset>'.
 6076:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 6077:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 6078:                &mt('Unique course identifier').':&nbsp;';
 6079:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 6080:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 6081:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 6082:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6083:     }
 6084:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 6085:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 6086:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6087:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 6088:     foreach my $type (@coursetypes) {
 6089:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 6090:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 6091:                    ('&nbsp;'x2);
 6092:     }
 6093:     $output .= '</span></fieldset>'.
 6094:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Creating courses').'</legend>'.
 6095:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 6096:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 6097:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6098:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 6099:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 6100:                '</fieldset>'.
 6101:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 6102:     foreach my $lticrsrole (@lticourseroles) {
 6103:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 6104:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 6105:     }
 6106:     $output .= '</fieldset>'.
 6107:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course options').'</legend>'.
 6108:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 6109:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 6110:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6111:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 6112:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 6113:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 6114:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 6115:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 6116:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 6117:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 6118:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 6119:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 6120:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 6121:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 6122:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 6123:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 6124:     foreach my $extra ('roster','passback') {
 6125:         my $checkedon = '';
 6126:         my $checkedoff = ' checked="checked"';
 6127:         if ($extra eq 'passback') {
 6128:             $pb1p1chk = ' checked="checked"';
 6129:             $pb1p0chk = '';
 6130:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 6131:         } else {
 6132:             $onclickpb = ''; 
 6133:         }
 6134:         if (ref($current) eq 'HASH') {
 6135:             if (($current->{$extra})) {
 6136:                 $checkedon = $checkedoff;
 6137:                 $checkedoff = '';
 6138:                 if ($extra eq 'passback') {
 6139:                     $passbacksty = 'inline-block';
 6140:                 }
 6141:                 if ($current->{'passbackformat'} eq '1.0') {
 6142:                     $pb1p0chk =  ' checked="checked"';
 6143:                     $pb1p1chk = '';
 6144:                 }
 6145:             }
 6146:         }
 6147:         $output .= $lt{$extra}.'&nbsp;'.
 6148:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 6149:                    &mt('No').'</label>'.('&nbsp;'x2).
 6150:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 6151:                    &mt('Yes').'</label><br />';
 6152:     }
 6153:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 6154:                '<span class="LC_nobreak">'.&mt('Grade format').
 6155:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 6156:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 6157:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 6158:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 6159:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6160:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback on logout').':&nbsp;'.
 6161:                '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6162:                $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6163:                '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6164:                $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6165:                '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6166:                '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6167:                '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6168:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6169:                '<fieldset class="ltioption_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Course defaults (Course Coordinator can override)').'</legend>'.
 6170:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 6171:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 6172:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6173:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 6174:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 6175:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6176:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 6177:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 6178:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6179:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 6180:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 6181:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'. 
 6182:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 6183:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 6184:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 6185:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 6186:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 6187:                    ('&nbsp;'x2);
 6188:     }
 6189:     $output .= '</span></div></fieldset>';
 6190: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 6191: #
 6192: #    $output .= '</fieldset>'.
 6193: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 6194:     return $output;
 6195: }
 6196: 
 6197: sub ltimenu_titles {
 6198:     return &Apache::lonlocal::texthash(
 6199:                                         fullname    => 'Full name',
 6200:                                         coursetitle => 'Course title',
 6201:                                         role        => 'Role',
 6202:                                         logout      => 'Logout',
 6203:                                         grades      => 'Grades',
 6204:     );
 6205: }
 6206: 
 6207: sub print_coursedefaults {
 6208:     my ($position,$dom,$settings,$rowtotal) = @_;
 6209:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 6210:     my $itemcount = 1;
 6211:     my %choices =  &Apache::lonlocal::texthash (
 6212:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 6213:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 6214:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 6215:         coursecredits        => 'Credits can be specified for courses',
 6216:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 6217:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 6218:         texengine            => 'Default method to display mathematics',
 6219:         postsubmit           => 'Disable submit button/keypress following student submission',
 6220:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 6221:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 6222:     );
 6223:     my %staticdefaults = (
 6224:                            anonsurvey_threshold => 10,
 6225:                            uploadquota          => 500,
 6226:                            postsubmit           => 60,
 6227:                            mysqltables          => 172800,
 6228:                          );
 6229:     if ($position eq 'top') {
 6230:         %defaultchecked = (
 6231:                             'canuse_pdfforms' => 'off',
 6232:                             'uselcmath'       => 'on',
 6233:                             'usejsme'         => 'on',
 6234:                             'canclone'        => 'none',
 6235:                           );
 6236:         @toggles = ('canuse_pdfforms','uselcmath','usejsme');
 6237:         my $deftex = $Apache::lonnet::deftex;
 6238:         if (ref($settings) eq 'HASH') {
 6239:             if ($settings->{'texengine'}) {
 6240:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 6241:                     $deftex = $settings->{'texengine'};
 6242:                 }
 6243:             }
 6244:         }
 6245:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6246:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 6247:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 6248:                        '</span></td><td class="LC_right_item">'.
 6249:                        '<select name="texengine">'."\n";
 6250:         my %texoptions = (
 6251:                             MathJax  => 'MathJax',
 6252:                             mimetex  => &mt('Convert to Images'),
 6253:                             tth      => &mt('TeX to HTML'),
 6254:                          );
 6255:         foreach my $renderer ('MathJax','mimetex','tth') {
 6256:             my $selected = '';
 6257:             if ($renderer eq $deftex) {
 6258:                 $selected = ' selected="selected"';
 6259:             }
 6260:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 6261:         }
 6262:         $mathdisp .= '</select></td></tr>'."\n";
 6263:         $itemcount ++;
 6264:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 6265:                                                      \%choices,$itemcount);
 6266:         $datatable = $mathdisp.$datatable;
 6267:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6268:         $datatable .=
 6269:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 6270:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 6271:             '</span></td><td class="LC_left_item">';
 6272:         my $currcanclone = 'none';
 6273:         my $onclick;
 6274:         my @cloneoptions = ('none','domain');
 6275:         my %clonetitles = &Apache::lonlocal::texthash (
 6276:                              none     => 'No additional course requesters',
 6277:                              domain   => "Any course requester in course's domain",
 6278:                              instcode => 'Course requests for official courses ...',
 6279:                           );
 6280:         my (%codedefaults,@code_order,@posscodes);
 6281:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 6282:                                                     \@code_order) eq 'ok') {
 6283:             if (@code_order > 0) {
 6284:                 push(@cloneoptions,'instcode');
 6285:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 6286:             }
 6287:         }
 6288:         if (ref($settings) eq 'HASH') {
 6289:             if ($settings->{'canclone'}) {
 6290:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 6291:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 6292:                         if (@code_order > 0) {
 6293:                             $currcanclone = 'instcode';
 6294:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 6295:                         }
 6296:                     }
 6297:                 } elsif ($settings->{'canclone'} eq 'domain') {
 6298:                     $currcanclone = $settings->{'canclone'};
 6299:                 }
 6300:             }
 6301:         }
 6302:         foreach my $option (@cloneoptions) {
 6303:             my ($checked,$additional);
 6304:             if ($currcanclone eq $option) {
 6305:                 $checked = ' checked="checked"';
 6306:             }
 6307:             if ($option eq 'instcode') {
 6308:                 if (@code_order) {
 6309:                     my $show = 'none';
 6310:                     if ($checked) {
 6311:                         $show = 'block';
 6312:                     }
 6313:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 6314:                                   &mt('Institutional codes for new and cloned course have identical:').
 6315:                                   '<br />';
 6316:                     foreach my $item (@code_order) {
 6317:                         my $codechk;
 6318:                         if ($checked) {
 6319:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 6320:                                 $codechk = ' checked="checked"';
 6321:                             }
 6322:                         }
 6323:                         $additional .= '<label>'.
 6324:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 6325:                                        $item.'</label>';
 6326:                     }
 6327:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 6328:                 }
 6329:             }
 6330:             $datatable .=
 6331:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 6332:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 6333:                 '</label>&nbsp;'.$additional.'</span><br />';
 6334:         }
 6335:         $datatable .= '</td>'.
 6336:                       '</tr>';
 6337:         $itemcount ++;
 6338:     } else {
 6339:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6340:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 6341:         my $currusecredits = 0;
 6342:         my $postsubmitclient = 1;
 6343:         my @types = ('official','unofficial','community','textbook','placement');
 6344:         if (ref($settings) eq 'HASH') {
 6345:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 6346:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 6347:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 6348:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 6349:                 }
 6350:             }
 6351:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 6352:                 foreach my $type (@types) {
 6353:                     next if ($type eq 'community');
 6354:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 6355:                     if ($defcredits{$type} ne '') {
 6356:                         $currusecredits = 1;
 6357:                     }
 6358:                 }
 6359:             }
 6360:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 6361:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 6362:                     $postsubmitclient = 0;
 6363:                     foreach my $type (@types) {
 6364:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6365:                     }
 6366:                 } else {
 6367:                     foreach my $type (@types) {
 6368:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 6369:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 6370:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 6371:                             } else {
 6372:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6373:                             }
 6374:                         } else {
 6375:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6376:                         }
 6377:                     }
 6378:                 }
 6379:             } else {
 6380:                 foreach my $type (@types) {
 6381:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6382:                 }
 6383:             }
 6384:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 6385:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 6386:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 6387:                 }
 6388:             } else {
 6389:                 foreach my $type (@types) {
 6390:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 6391:                 }
 6392:             }
 6393:         } else {
 6394:             foreach my $type (@types) {
 6395:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 6396:             }
 6397:         }
 6398:         if (!$currdefresponder) {
 6399:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 6400:         } elsif ($currdefresponder < 1) {
 6401:             $currdefresponder = 1;
 6402:         }
 6403:         foreach my $type (@types) {
 6404:             if ($curruploadquota{$type} eq '') {
 6405:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 6406:             }
 6407:         }
 6408:         $datatable .=
 6409:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6410:                 $choices{'anonsurvey_threshold'}.
 6411:                 '</span></td>'.
 6412:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 6413:                 '<input type="text" name="anonsurvey_threshold"'.
 6414:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 6415:                 '</td></tr>'."\n";
 6416:         $itemcount ++;
 6417:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6418:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6419:                       $choices{'uploadquota'}.
 6420:                       '</span></td>'.
 6421:                       '<td style="text-align: right" class="LC_right_item">'.
 6422:                       '<table><tr>';
 6423:         foreach my $type (@types) {
 6424:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6425:                            '<input type="text" name="uploadquota_'.$type.'"'.
 6426:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 6427:         }
 6428:         $datatable .= '</tr></table></td></tr>'."\n";
 6429:         $itemcount ++;
 6430:         my $onclick = "toggleDisplay(this.form,'credits');";
 6431:         my $display = 'none';
 6432:         if ($currusecredits) {
 6433:             $display = 'block';
 6434:         }
 6435:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 6436:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 6437:         foreach my $type (@types) {
 6438:             next if ($type eq 'community');
 6439:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6440:                            '<input type="text" name="'.$type.'_credits"'.
 6441:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 6442:         }
 6443:         $additional .= '</tr></table></div>'."\n";
 6444:         %defaultchecked = ('coursecredits' => 'off');
 6445:         @toggles = ('coursecredits');
 6446:         my $current = {
 6447:                         'coursecredits' => $currusecredits,
 6448:                       };
 6449:         (my $table,$itemcount) =
 6450:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 6451:                                \%choices,$itemcount,$onclick,$additional,'left');
 6452:         $datatable .= $table;
 6453:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 6454:         my $display = 'none';
 6455:         if ($postsubmitclient) {
 6456:             $display = 'block';
 6457:         }
 6458:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 6459:                       &mt('Number of seconds submit is disabled').'<br />'.
 6460:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 6461:                       '<table><tr>';
 6462:         foreach my $type (@types) {
 6463:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6464:                            '<input type="text" name="'.$type.'_timeout" value="'.
 6465:                            $deftimeout{$type}.'" size="5" /></td>';
 6466:         }
 6467:         $additional .= '</tr></table></div>'."\n";
 6468:         %defaultchecked = ('postsubmit' => 'on');
 6469:         @toggles = ('postsubmit');
 6470:         $current = {
 6471:                        'postsubmit' => $postsubmitclient,
 6472:                    };
 6473:         ($table,$itemcount) =
 6474:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 6475:                                \%choices,$itemcount,$onclick,$additional,'left');
 6476:         $datatable .= $table;
 6477:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6478:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6479:                       $choices{'mysqltables'}.
 6480:                       '</span></td>'.
 6481:                       '<td style="text-align: right" class="LC_right_item">'.
 6482:                       '<table><tr>';
 6483:         foreach my $type (@types) {
 6484:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 6485:                            '<input type="text" name="mysqltables_'.$type.'"'.
 6486:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 6487:         }
 6488:         $datatable .= '</tr></table></td></tr>'."\n";
 6489:         $itemcount ++;
 6490: 
 6491:     }
 6492:     $$rowtotal += $itemcount;
 6493:     return $datatable;
 6494: }
 6495: 
 6496: sub print_selfenrollment {
 6497:     my ($position,$dom,$settings,$rowtotal) = @_;
 6498:     my ($css_class,$datatable);
 6499:     my $itemcount = 1;
 6500:     my @types = ('official','unofficial','community','textbook','placement');
 6501:     if (($position eq 'top') || ($position eq 'middle')) {
 6502:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 6503:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 6504:         my @rows;
 6505:         my $key;
 6506:         if ($position eq 'top') {
 6507:             $key = 'admin'; 
 6508:             if (ref($rowsref) eq 'ARRAY') {
 6509:                 @rows = @{$rowsref};
 6510:             }
 6511:         } elsif ($position eq 'middle') {
 6512:             $key = 'default';
 6513:             @rows = ('types','registered','approval','limit');
 6514:         }
 6515:         foreach my $row (@rows) {
 6516:             if (defined($titlesref->{$row})) {
 6517:                 $itemcount ++;
 6518:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6519:                 $datatable .= '<tr'.$css_class.'>'.
 6520:                               '<td>'.$titlesref->{$row}.'</td>'.
 6521:                               '<td class="LC_left_item">'.
 6522:                               '<table><tr>';
 6523:                 my (%current,%currentcap);
 6524:                 if (ref($settings) eq 'HASH') {
 6525:                     if (ref($settings->{$key}) eq 'HASH') {
 6526:                         foreach my $type (@types) {
 6527:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 6528:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 6529:                             }
 6530:                             if (($row eq 'limit') && ($key eq 'default')) {
 6531:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 6532:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 6533:                                 }
 6534:                             }
 6535:                         }
 6536:                     }
 6537:                 }
 6538:                 my %roles = (
 6539:                              '0' => &Apache::lonnet::plaintext('dc'),
 6540:                             ); 
 6541:             
 6542:                 foreach my $type (@types) {
 6543:                     unless (($row eq 'registered') && ($key eq 'default')) {
 6544:                         $datatable .= '<th>'.&mt($type).'</th>';
 6545:                     }
 6546:                 }
 6547:                 unless (($row eq 'registered') && ($key eq 'default')) {
 6548:                     $datatable .= '</tr><tr>';
 6549:                 }
 6550:                 foreach my $type (@types) {
 6551:                     if ($type eq 'community') {
 6552:                         $roles{'1'} = &mt('Community personnel');
 6553:                     } else {
 6554:                         $roles{'1'} = &mt('Course personnel');
 6555:                     }
 6556:                     $datatable .= '<td style="vertical-align: top">';
 6557:                     if ($position eq 'top') {
 6558:                         my %checked;
 6559:                         if ($current{$type} eq '0') {
 6560:                             $checked{'0'} = ' checked="checked"';
 6561:                         } else {
 6562:                             $checked{'1'} = ' checked="checked"';
 6563:                         }
 6564:                         foreach my $role ('1','0') {
 6565:                             $datatable .= '<span class="LC_nobreak"><label>'.
 6566:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 6567:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 6568:                                           $roles{$role}.'</label></span> ';
 6569:                         }
 6570:                     } else {
 6571:                         if ($row eq 'types') {
 6572:                             my %checked;
 6573:                             if ($current{$type} =~ /^(all|dom)$/) {
 6574:                                 $checked{$1} = ' checked="checked"';
 6575:                             } else {
 6576:                                 $checked{''} = ' checked="checked"';
 6577:                             }
 6578:                             foreach my $val ('','dom','all') {
 6579:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6580:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6581:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6582:                             }
 6583:                         } elsif ($row eq 'registered') {
 6584:                             my %checked;
 6585:                             if ($current{$type} eq '1') {
 6586:                                 $checked{'1'} = ' checked="checked"';
 6587:                             } else {
 6588:                                 $checked{'0'} = ' checked="checked"';
 6589:                             }
 6590:                             foreach my $val ('0','1') {
 6591:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6592:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6593:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6594:                             }
 6595:                         } elsif ($row eq 'approval') {
 6596:                             my %checked;
 6597:                             if ($current{$type} =~ /^([12])$/) {
 6598:                                 $checked{$1} = ' checked="checked"';
 6599:                             } else {
 6600:                                 $checked{'0'} = ' checked="checked"';
 6601:                             }
 6602:                             for my $val (0..2) {
 6603:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6604:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6605:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6606:                             }
 6607:                         } elsif ($row eq 'limit') {
 6608:                             my %checked;
 6609:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 6610:                                 $checked{$1} = ' checked="checked"';
 6611:                             } else {
 6612:                                 $checked{'none'} = ' checked="checked"';
 6613:                             }
 6614:                             my $cap;
 6615:                             if ($currentcap{$type} =~ /^\d+$/) {
 6616:                                 $cap = $currentcap{$type};
 6617:                             }
 6618:                             foreach my $val ('none','allstudents','selfenrolled') {
 6619:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 6620:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 6621:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 6622:                             }
 6623:                             $datatable .= '<br />'.
 6624:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 6625:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 6626:                                           '</span>'; 
 6627:                         }
 6628:                     }
 6629:                     $datatable .= '</td>';
 6630:                 }
 6631:                 $datatable .= '</tr>';
 6632:             }
 6633:             $datatable .= '</table></td></tr>';
 6634:         }
 6635:     } elsif ($position eq 'bottom') {
 6636:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 6637:     }
 6638:     $$rowtotal += $itemcount;
 6639:     return $datatable;
 6640: }
 6641: 
 6642: sub print_validation_rows {
 6643:     my ($caller,$dom,$settings,$rowtotal) = @_;
 6644:     my ($itemsref,$namesref,$fieldsref);
 6645:     if ($caller eq 'selfenroll') { 
 6646:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 6647:     } elsif ($caller eq 'requestcourses') {
 6648:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 6649:     }
 6650:     my %currvalidation;
 6651:     if (ref($settings) eq 'HASH') {
 6652:         if (ref($settings->{'validation'}) eq 'HASH') {
 6653:             %currvalidation = %{$settings->{'validation'}};
 6654:         }
 6655:     }
 6656:     my $datatable;
 6657:     my $itemcount = 0;
 6658:     foreach my $item (@{$itemsref}) {
 6659:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6660:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 6661:                       $namesref->{$item}.
 6662:                       '</span></td>'.
 6663:                       '<td class="LC_left_item">';
 6664:         if (($item eq 'url') || ($item eq 'button')) {
 6665:             $datatable .= '<span class="LC_nobreak">'.
 6666:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 6667:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 6668:         } elsif ($item eq 'fields') {
 6669:             my @currfields;
 6670:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 6671:                 @currfields = @{$currvalidation{$item}};
 6672:             }
 6673:             foreach my $field (@{$fieldsref}) {
 6674:                 my $check = '';
 6675:                 if (grep(/^\Q$field\E$/,@currfields)) {
 6676:                     $check = ' checked="checked"';
 6677:                 }
 6678:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6679:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 6680:                               ' value="'.$field.'"'.$check.' />'.$field.
 6681:                               '</label></span> ';
 6682:             }
 6683:         } elsif ($item eq 'markup') {
 6684:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 6685:                            $currvalidation{$item}.
 6686:                               '</textarea>';
 6687:         }
 6688:         $datatable .= '</td></tr>'."\n";
 6689:         if (ref($rowtotal)) {
 6690:             $itemcount ++;
 6691:         }
 6692:     }
 6693:     if ($caller eq 'requestcourses') {
 6694:         my %currhash;
 6695:         if (ref($settings) eq 'HASH') {
 6696:             if (ref($settings->{'validation'}) eq 'HASH') {
 6697:                 if ($settings->{'validation'}{'dc'} ne '') {
 6698:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 6699:                 }
 6700:             }
 6701:         }
 6702:         my $numinrow = 2;
 6703:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 6704:                                                        'validationdc',%currhash);
 6705:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 6706:         $datatable .= '<tr'.$css_class.'><td>';
 6707:         if ($numdc > 1) {
 6708:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 6709:         } else {
 6710:             $datatable .=  &mt('Course creation processed as: ');
 6711:         }
 6712:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 6713:         $itemcount ++;
 6714:     }
 6715:     if (ref($rowtotal)) {
 6716:         $$rowtotal += $itemcount;
 6717:     }
 6718:     return $datatable;
 6719: }
 6720: 
 6721: sub print_privacy {
 6722:     my ($position,$dom,$settings,$rowtotal) = @_;
 6723:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 6724:     my $itemcount = 0;
 6725:     unless ($position eq 'top') {
 6726:         @items = ('domain','author','course','community');
 6727:         %names = &Apache::lonlocal::texthash (
 6728:                      domain => 'Assigned domain role(s)',
 6729:                      author => 'Assigned co-author role(s)',
 6730:                      course => 'Assigned course role(s)',
 6731:                      community => 'Assigned community role',
 6732:                  );
 6733:         $numinrow = 4;
 6734:         ($othertitle,$usertypes,$types) =
 6735:             &Apache::loncommon::sorted_inst_types($dom);
 6736:     }
 6737:     if (($position eq 'top') || ($position eq 'middle')) {
 6738:         my (%by_ip,%by_location,@intdoms,@instdoms);
 6739:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 6740:         if ($position eq 'top') {
 6741:             my %curr;
 6742:             my @options = ('none','user','domain','auto');
 6743:             my %titles = &Apache::lonlocal::texthash (
 6744:                 none   => 'Not allowed',
 6745:                 user   => 'User authorizes',
 6746:                 domain => 'DC authorizes',
 6747:                 auto   => 'Unrestricted',
 6748:                 instdom => 'Other domain shares institution/provider',
 6749:                 extdom => 'Other domain has different institution/provider',
 6750:             );
 6751:             my %names = &Apache::lonlocal::texthash (
 6752:                 domain => 'Domain role',
 6753:                 author => 'Co-author role',
 6754:                 course => 'Course role',
 6755:                 community => 'Community role',
 6756:             );
 6757:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 6758:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 6759:             foreach my $domtype ('instdom','extdom') {
 6760:                 my (%checked,$skip);
 6761:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6762:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 6763:                               '<td class="LC_left_item">';
 6764:                 if ($domtype eq 'instdom') {
 6765:                     unless (@instdoms > 1) {
 6766:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 6767:                         $skip = 1;
 6768:                     }
 6769:                 } elsif ($domtype eq 'extdom') {
 6770:                     if (keys(%by_location) == 0) {
 6771:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 6772:                         $skip = 1;
 6773:                     }
 6774:                 }
 6775:                 unless ($skip) {
 6776:                     foreach my $roletype ('domain','author','course','community') {
 6777:                         $checked{'auto'} = ' checked="checked"';
 6778:                         if (ref($settings) eq 'HASH') {
 6779:                             if (ref($settings->{approval}) eq 'HASH') {
 6780:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 6781:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 6782:                                         $checked{$1} = ' checked="checked"';
 6783:                                         $checked{'auto'} = '';
 6784:                                     }
 6785:                                 }
 6786:                             }
 6787:                         }
 6788:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 6789:                         foreach my $option (@options) {
 6790:                             $datatable .= '<span class="LC_nobreak"><label>'.
 6791:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 6792:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 6793:                                           '</label></span>&nbsp; ';
 6794:                         }
 6795:                         $datatable .= '</fieldset>';
 6796:                     }
 6797:                 }
 6798:                 $datatable .= '</td></tr>';
 6799:                 $itemcount ++;
 6800:             }
 6801:         } elsif ($position eq 'middle') {
 6802:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 6803:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6804:                     foreach my $item (@{$types}) {
 6805:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 6806:                                                                $numinrow,$itemcount,'','','','','',
 6807:                                                                '',$usertypes->{$item});
 6808:                         $itemcount ++;
 6809:                     }
 6810:                 }
 6811:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 6812:                                                        $numinrow,$itemcount,'','','','','',
 6813:                                                        '',$othertitle);
 6814:                 $itemcount ++;
 6815:             } else {
 6816:                 my (@insttypes,%insttitles);
 6817:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6818:                     @insttypes = @{$types};
 6819:                     %insttitles = %{$usertypes};
 6820:                 }
 6821:                 foreach my $item (@insttypes,'default') {
 6822:                     my $title;
 6823:                     if ($item eq 'default') {
 6824:                         $title = $othertitle;
 6825:                     } else {
 6826:                         $title = $insttitles{$item};
 6827:                     }
 6828:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6829:                     $datatable .= '<tr'.$css_class.'>'.
 6830:                                   '<td class="LC_left_item">'.$title.'</td>'.
 6831:                                   '<td class="LC_left_item">'.
 6832:                                   &mt('Nothing to set here, as there are no other domains').
 6833:                                   '</td></tr>';
 6834:                     $itemcount ++;
 6835:                 }
 6836:             }
 6837:         }
 6838:     } else {
 6839:         my $prefix;
 6840:         if ($position eq 'lower') {
 6841:             $prefix = 'priv';
 6842:         } else {
 6843:             $prefix = 'unpriv';
 6844:         }
 6845:         foreach my $item (@items) {
 6846:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 6847:                                                    $numinrow,$itemcount,'','','','','',
 6848:                                                    '',$names{$item});
 6849:             $itemcount ++;
 6850:         }
 6851:     }
 6852:     if (ref($rowtotal)) {
 6853:         $$rowtotal += $itemcount;
 6854:     }
 6855:     return $datatable;
 6856: }
 6857: 
 6858: sub print_passwords {
 6859:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 6860:     my ($datatable,$css_class);
 6861:     my $itemcount = 0;
 6862:     my %titles = &Apache::lonlocal::texthash (
 6863:         captcha        => '"Forgot Password" CAPTCHA validation',
 6864:         link           => 'Reset link expiration (hours)',
 6865:         case           => 'Case-sensitive usernames/e-mail',
 6866:         prelink        => 'Information required (form 1)',
 6867:         postlink       => 'Information required (form 2)',
 6868:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 6869:         customtext     => 'Domain specific text (HTML)',
 6870:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 6871:         intauth_check  => 'Check bcrypt cost if authenticated',
 6872:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 6873:         permanent      => 'Permanent e-mail address',
 6874:         critical       => 'Critical notification address',
 6875:         notify         => 'Notification address',
 6876:         min            => 'Minimum password length',
 6877:         max            => 'Maximum password length',
 6878:         chars          => 'Required characters',
 6879:         expire         => 'Password expiration (days)',
 6880:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 6881:     );
 6882:     if ($position eq 'top') {
 6883:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 6884:         my $shownlinklife = 2;
 6885:         my $prelink = 'both';
 6886:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 6887:         if (ref($settings) eq 'HASH') {
 6888:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 6889:                 $shownlinklife = $settings->{resetlink};
 6890:             }
 6891:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 6892:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 6893:             }
 6894:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 6895:                 $prelink = $settings->{resetprelink};
 6896:             }
 6897:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 6898:                 %postlink = %{$settings->{resetpostlink}};
 6899:             }
 6900:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 6901:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 6902:             }
 6903:             if ($settings->{resetremove}) {
 6904:                 $nostdtext = 1;
 6905:             }
 6906:             if ($settings->{resetcustom}) {
 6907:                 $customurl = $settings->{resetcustom};
 6908:             }
 6909:         } else {
 6910:             if (ref($types) eq 'ARRAY') {
 6911:                 foreach my $item (@{$types}) {
 6912:                     $casesens{$item} = 1;
 6913:                     $postlink{$item} = ['username','email'];
 6914:                 }
 6915:             }
 6916:             $casesens{'default'} = 1;
 6917:             $postlink{'default'} = ['username','email'];
 6918:             $prelink = 'both';
 6919:             %emailsrc = (
 6920:                           permanent => 1,
 6921:                           critical  => 1,
 6922:                           notify    => 1,
 6923:             );
 6924:         }
 6925:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 6926:         $itemcount ++;
 6927:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6928:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 6929:                       '<td class="LC_left_item">'.
 6930:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 6931:                       'name="passwords_link" size="3" /></td></tr>';
 6932:         $itemcount ++;
 6933:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6934:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 6935:                       '<td class="LC_left_item">';
 6936:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6937:             foreach my $item (@{$types}) {
 6938:                 my $checkedcase;
 6939:                 if ($casesens{$item}) {
 6940:                     $checkedcase = ' checked="checked"';
 6941:                 }
 6942:                 $datatable .= '<span class="LC_nobreak"><label>'.
 6943:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 6944:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 6945:                               '</span>&nbsp;&nbsp; ';
 6946:             }
 6947:         }
 6948:         my $checkedcase;
 6949:         if ($casesens{'default'}) {
 6950:             $checkedcase = ' checked="checked"';
 6951:         }
 6952:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 6953:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 6954:                       $othertitle.'</label></span></td>';
 6955:         $itemcount ++;
 6956:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6957:         my %checkedpre = (
 6958:                              both => ' checked="checked"',
 6959:                              either => '',
 6960:                          );
 6961:         if ($prelink eq 'either') {
 6962:             $checkedpre{either} = ' checked="checked"';
 6963:             $checkedpre{both} = '';
 6964:         }
 6965:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 6966:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 6967:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 6968:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 6969:                       '<span class="LC_nobreak"><label>'.
 6970:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 6971:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 6972:         $itemcount ++;
 6973:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6974:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 6975:                       '<td class="LC_left_item">';
 6976:         my %postlinked;
 6977:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 6978:             foreach my $item (@{$types}) {
 6979:                 undef(%postlinked);
 6980:                 $datatable .= '<fieldset style="display: inline-block;">'.
 6981:                               '<legend>'.$usertypes->{$item}.'</legend>';
 6982:                 if (ref($postlink{$item}) eq 'ARRAY') {
 6983:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 6984:                 }
 6985:                 foreach my $field ('email','username') {
 6986:                     my $checked;
 6987:                     if ($postlinked{$field}) {
 6988:                         $checked = ' checked="checked"';
 6989:                     }
 6990:                     $datatable .= '<span class="LC_nobreak"><label>'.
 6991:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 6992:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 6993:                                   '<span>&nbsp;&nbsp; ';
 6994:                 }
 6995:                 $datatable .= '</fieldset>';
 6996:             }
 6997:         }
 6998:         if (ref($postlink{'default'}) eq 'ARRAY') {
 6999:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 7000:         }
 7001:         $datatable .= '<fieldset style="display: inline-block;">'.
 7002:                       '<legend>'.$othertitle.'</legend>';
 7003:         foreach my $field ('email','username') {
 7004:             my $checked;
 7005:             if ($postlinked{$field}) {
 7006:                 $checked = ' checked="checked"';
 7007:             }
 7008:             $datatable .= '<span class="LC_nobreak"><label>'.
 7009:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 7010:                           $field.'"'.$checked.' />'.$field.'</label>'.
 7011:                           '<span>&nbsp;&nbsp; ';
 7012:         }
 7013:         $datatable .= '</fieldset></td></tr>';
 7014:         $itemcount ++;
 7015:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7016:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 7017:                       '<td class="LC_left_item">';
 7018:         foreach my $type ('permanent','critical','notify') {
 7019:             my $checkedemail;
 7020:             if ($emailsrc{$type}) {
 7021:                 $checkedemail = ' checked="checked"';
 7022:             }
 7023:             $datatable .= '<span class="LC_nobreak"><label>'.
 7024:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 7025:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 7026:                           '<span>&nbsp;&nbsp; ';
 7027:         }
 7028:         $datatable .= '</td></tr>';
 7029:         $itemcount ++;
 7030:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7031:         my $switchserver = &check_switchserver($dom,$confname);
 7032:         my ($showstd,$noshowstd);
 7033:         if ($nostdtext) {
 7034:             $noshowstd = ' checked="checked"';
 7035:         } else {
 7036:             $showstd = ' checked="checked"';
 7037:         }
 7038:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 7039:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7040:                       &mt('Retain standard text:').
 7041:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 7042:                       &mt('Yes').'</label>'.'&nbsp;'.
 7043:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 7044:                       &mt('No').'</label></span><br />'.
 7045:                       '<span class="LC_fontsize_small">'.
 7046:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 7047:                       &mt('Include custom text:');
 7048:         if ($customurl) {
 7049:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 7050:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 7051:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 7052:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 7053:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 7054:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 7055:         }
 7056:         if ($switchserver) {
 7057:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 7058:         } else {
 7059:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 7060:                          '<input type="file" name="passwords_customfile" /></span>';
 7061:         }
 7062:         $datatable .= '</td></tr>';
 7063:     } elsif ($position eq 'middle') {
 7064:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 7065:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 7066:         my %defaults;
 7067:         if (ref($domconf{'defaults'}) eq 'HASH') {
 7068:             %defaults = %{$domconf{'defaults'}};
 7069:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 7070:                 $defaults{'intauth_cost'} = 10;
 7071:             }
 7072:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 7073:                 $defaults{'intauth_check'} = 0;
 7074:             }
 7075:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 7076:                 $defaults{'intauth_switch'} = 0;
 7077:             }
 7078:         } else {
 7079:             %defaults = (
 7080:                           'intauth_cost'   => 10,
 7081:                           'intauth_check'  => 0,
 7082:                           'intauth_switch' => 0,
 7083:                         );
 7084:         }
 7085:         foreach my $item (@items) {
 7086:             if ($itemcount%2) {
 7087:                 $css_class = '';
 7088:             } else {
 7089:                 $css_class = ' class="LC_odd_row" ';
 7090:             }
 7091:             $datatable .= '<tr'.$css_class.'>'.
 7092:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 7093:                           '</span></td><td class="LC_left_item" colspan="3">';
 7094:             if ($item eq 'intauth_switch') {
 7095:                 my @options = (0,1,2);
 7096:                 my %optiondesc = &Apache::lonlocal::texthash (
 7097:                                    0 => 'No',
 7098:                                    1 => 'Yes',
 7099:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 7100:                                  );
 7101:                 $datatable .= '<table width="100%">';
 7102:                 foreach my $option (@options) {
 7103:                     my $checked = ' ';
 7104:                     if ($defaults{$item} eq $option) {
 7105:                         $checked = ' checked="checked"';
 7106:                     }
 7107:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 7108:                                   '<label><input type="radio" name="'.$item.
 7109:                                   '" value="'.$option.'"'.$checked.' />'.
 7110:                                   $optiondesc{$option}.'</label></span></td></tr>';
 7111:                 }
 7112:                 $datatable .= '</table>';
 7113:             } elsif ($item eq 'intauth_check') {
 7114:                 my @options = (0,1,2);
 7115:                 my %optiondesc = &Apache::lonlocal::texthash (
 7116:                                    0 => 'No',
 7117:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 7118:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 7119:                                  );
 7120:                 $datatable .= '<table width="100%">';
 7121:                 foreach my $option (@options) {
 7122:                     my $checked = ' ';
 7123:                     my $onclick;
 7124:                     if ($defaults{$item} eq $option) {
 7125:                         $checked = ' checked="checked"';
 7126:                     }
 7127:                     if ($option == 2) {
 7128:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 7129:                     }
 7130:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 7131:                                   '<label><input type="radio" name="'.$item.
 7132:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 7133:                                   $optiondesc{$option}.'</label></span></td></tr>';
 7134:                 }
 7135:                 $datatable .= '</table>';
 7136:             } else {
 7137:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 7138:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 7139:             }
 7140:             $datatable .= '</td></tr>';
 7141:             $itemcount ++;
 7142:         }
 7143:     } elsif ($position eq 'lower') {
 7144:         my ($min,$max,%chars,$expire,$numsaved);
 7145:         $min = $Apache::lonnet::passwdmin;
 7146:         if (ref($settings) eq 'HASH') {
 7147:             if ($settings->{min}) {
 7148:                 $min = $settings->{min};
 7149:             }
 7150:             if ($settings->{max}) {
 7151:                 $max = $settings->{max};
 7152:             }
 7153:             if (ref($settings->{chars}) eq 'ARRAY') {
 7154:                 map { $chars{$_} = 1; } (@{$settings->{chars}});
 7155:             }
 7156:             if ($settings->{expire}) {
 7157:                 $expire = $settings->{expire};
 7158:             }
 7159:             if ($settings->{numsaved}) {
 7160:                 $numsaved = $settings->{numsaved};
 7161:             }
 7162:         }
 7163:         my %rulenames = &Apache::lonlocal::texthash(
 7164:                                                      uc => 'At least one upper case letter',
 7165:                                                      lc => 'At least one lower case letter',
 7166:                                                      num => 'At least one number',
 7167:                                                      spec => 'At least one non-alphanumeric',
 7168:                                                    );
 7169:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7170:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 7171:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7172:                       '<input type="text" name="passwords_min" value="'.$min.'" size="3" '.
 7173:                       'onblur="javascript:warnIntPass(this);" />'.
 7174:                       '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 7175:                       '</span></td></tr>';
 7176:         $itemcount ++;
 7177:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7178:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 7179:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7180:                       '<input type="text" name="passwords_max" value="'.$max.'" size="3" '.
 7181:                       'onblur="javascript:warnIntPass(this);" />'.
 7182:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 7183:                       '</span></td></tr>';
 7184:         $itemcount ++;
 7185:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7186:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 7187:                       '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 7188:                       '</span></td>';
 7189:         my $numinrow = 2;
 7190:         my @possrules = ('uc','lc','num','spec');
 7191:         $datatable .= '<td class="LC_left_item"><table>';
 7192:         for (my $i=0; $i<@possrules; $i++) {
 7193:             my ($rem,$checked);
 7194:             if ($chars{$possrules[$i]}) {
 7195:                 $checked = ' checked="checked"';
 7196:             }
 7197:             $rem = $i%($numinrow);
 7198:             if ($rem == 0) {
 7199:                 if ($i > 0) {
 7200:                     $datatable .= '</tr>';
 7201:                 }
 7202:                 $datatable .= '<tr>';
 7203:             }
 7204:             $datatable .= '<td><span class="LC_nobreak"><label>'.
 7205:                           '<input type="checkbox" name="passwords_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 7206:                           $rulenames{$possrules[$i]}.'</label></span></td>';
 7207:         }
 7208:         my $rem = @possrules%($numinrow);
 7209:         my $colsleft = $numinrow - $rem;
 7210:         if ($colsleft > 1 ) {
 7211:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7212:                           '&nbsp;</td>';
 7213:         } elsif ($colsleft == 1) {
 7214:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7215:         }
 7216:         $datatable .='</table></td></tr>';
 7217:         $itemcount ++;
 7218:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7219:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 7220:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7221:                       '<input type="text" name="passwords_expire" value="'.$expire.'" size="4" '.
 7222:                       'onblur="javascript:warnIntPass(this);" />'.
 7223:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 7224:                       '</span></td></tr>';
 7225:         $itemcount ++;
 7226:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7227:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 7228:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7229:                       '<input type="text" name="passwords_numsaved" value="'.$numsaved.'" size="3" '.
 7230:                       'onblur="javascript:warnIntPass(this);" />'. 
 7231:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 7232:                       '</span></td></tr>';
 7233:     } else {
 7234:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7235:         my %ownerchg = (
 7236:                           by  => {},
 7237:                           for => {},
 7238:                        );
 7239:         my %ownertitles = &Apache::lonlocal::texthash (
 7240:                             by  => 'Course owner status(es) allowed',
 7241:                             for => 'Student status(es) allowed',
 7242:                           );
 7243:         if (ref($settings) eq 'HASH') {
 7244:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 7245:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 7246:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 7247:                 }
 7248:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 7249:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 7250:                 }
 7251:             }
 7252:         }
 7253:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7254:         $datatable .= '<tr '.$css_class.'>'.
 7255:                       '<td>'.
 7256:                       &mt('Requirements').'<ul>'.
 7257:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 7258:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 7259:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 7260:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 7261:                       '</ul>'.
 7262:                       '</td>'.
 7263:                       '<td class="LC_left_item">';
 7264:         foreach my $item ('by','for') {
 7265:             $datatable .= '<fieldset style="display: inline-block;">'.
 7266:                           '<legend>'.$ownertitles{$item}.'</legend>';
 7267:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7268:                 foreach my $type (@{$types}) {
 7269:                     my $checked;
 7270:                     if ($ownerchg{$item}{$type}) {
 7271:                         $checked = ' checked="checked"';
 7272:                     }
 7273:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7274:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 7275:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 7276:                                   '</span>&nbsp;&nbsp; ';
 7277:                 }
 7278:             }
 7279:             my $checked;
 7280:             if ($ownerchg{$item}{'default'}) {
 7281:                 $checked = ' checked="checked"';
 7282:             }
 7283:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7284:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 7285:                           $othertitle.'</label></span></fieldset>';
 7286:         }
 7287:         $datatable .= '</td></tr>';
 7288:     }
 7289:     return $datatable;
 7290: }
 7291: 
 7292: sub print_wafproxy {
 7293:     my ($position,$dom,$settings,$rowtotal) = @_;
 7294:     my $css_class;
 7295:     my $itemcount = 0;
 7296:     my $datatable;
 7297:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7298:     my (%othercontrol,%otherdoms,%aliases,%values,$setdom,$showdom);
 7299:     my %lt = &wafproxy_titles();
 7300:     foreach my $server (sort(keys(%servers))) {
 7301:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 7302:         next if ($serverhome eq '');
 7303:         my $serverdom;
 7304:         if ($serverhome ne $server) {
 7305:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 7306:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 7307:                 $othercontrol{$server} = $serverdom;
 7308:             }
 7309:         } else {
 7310:             $serverdom = &Apache::lonnet::host_domain($server);
 7311:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 7312:             if ($serverdom ne $dom) {
 7313:                 $othercontrol{$server} = $serverdom;
 7314:             } else {
 7315:                 $setdom = 1;
 7316:                 if (ref($settings) eq 'HASH') {
 7317:                     if (ref($settings->{'alias'}) eq 'HASH') {
 7318:                         $aliases{$dom} = $settings->{'alias'};
 7319:                         if ($aliases{$dom} ne '') {
 7320:                             $showdom = 1;
 7321:                         }
 7322:                     }
 7323:                 }
 7324:             }
 7325:         }
 7326:     }
 7327:     if ($setdom) {
 7328:         %{$values{$dom}} = ();
 7329:         if (ref($settings) eq 'HASH') {
 7330:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7331:                 $values{$dom}{$item} = $settings->{$item};
 7332:             }
 7333:         }
 7334:     }
 7335:     if (keys(%othercontrol)) {
 7336:         %otherdoms = reverse(%othercontrol);
 7337:         foreach my $domain (keys(%otherdoms)) {
 7338:             %{$values{$domain}} = ();
 7339:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 7340:             if (ref($config{'wafproxy'}) eq 'HASH') {
 7341:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 7342:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7343:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 7344:                 }
 7345:             }
 7346:         }
 7347:     }
 7348:     if ($position eq 'top') {
 7349:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7350:         my %aliasinfo;
 7351:         foreach my $server (sort(keys(%servers))) {
 7352:             $itemcount ++;
 7353:             my $dom_in_effect;
 7354:             my $aliasrows = '<tr>'.
 7355:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7356:                             &mt('Hostname').':&nbsp;'.
 7357:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 7358:             if ($othercontrol{$server}) {
 7359:                 $dom_in_effect = $othercontrol{$server};
 7360:                 my $current;
 7361:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 7362:                     $current = $aliases{$dom_in_effect}{$server};
 7363:                 }
 7364:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7365:                               &mt('Alias').':&nbsp';
 7366:                 if ($current) {
 7367:                     $aliasrows .= $current;
 7368:                 } else {
 7369:                     $aliasrows .= &mt('None');
 7370:                 }
 7371:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 7372:                               &mt('controlled by domain: [_1]',
 7373:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 7374:             } else {
 7375:                 $dom_in_effect = $dom;
 7376:                 my $current;
 7377:                 if (ref($aliases{$dom}) eq 'HASH') {
 7378:                     if ($aliases{$dom}{$server}) {
 7379:                         $current = $aliases{$dom}{$server};
 7380:                     }
 7381:                 }
 7382:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 7383:                               &mt('Alias').':&nbsp;'.
 7384:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 7385:                               'value="'.$current.'" size="30" /></td>';
 7386:             }
 7387:             $aliasrows .= '</tr>';
 7388:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 7389:         }
 7390:         if ($aliasinfo{$dom}) {
 7391:             my ($onclick,$wafon,$wafoff,$showtable);
 7392:             $onclick = ' onclick="javascript:toggleWAF();"';
 7393:             $wafoff = ' checked="checked"';
 7394:             $showtable = ' style="display:none";';
 7395:             if ($showdom) {
 7396:                 $wafon = $wafoff;
 7397:                 $wafoff = '';
 7398:                 $showtable = ' style="display:inline;"';
 7399:             }
 7400:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7401:             $datatable = '<tr'.$css_class.'>'.
 7402:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 7403:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 7404:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 7405:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 7406:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 7407:                          &mt('No').'</label></span></td>'.
 7408:                          '<td class="LC_left_item">'.
 7409:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 7410:                          '</table></td></tr>';
 7411:             $itemcount++;
 7412:         }
 7413:         if (keys(%otherdoms)) {
 7414:             foreach my $key (sort(keys(%otherdoms))) {
 7415:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7416:                 $datatable .= '<tr'.$css_class.'>'.
 7417:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 7418:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 7419:                               '</table></td></tr>';
 7420:                 $itemcount++;
 7421:             }
 7422:         }
 7423:     } else {
 7424:         my %ip_methods = &remoteip_methods();
 7425:         if ($setdom) {
 7426:             $itemcount ++;
 7427:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7428:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 7429:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 7430:             $wafstyle = ' style="display:none;"';
 7431:             $nowafstyle = ' style="display:table-row;"';
 7432:             $currwafdisplay = ' style="display: none"';
 7433:             $wafrangestyle = ' style="display: none"';
 7434:             $curr_remotip = 'n';
 7435:             $ssltossl = ' checked="checked"';
 7436:             if ($showdom) {
 7437:                 $wafstyle = ' style="display:table-row;"';
 7438:                 $nowafstyle =  ' style="display:none;"';
 7439:                 if (keys(%{$values{$dom}})) {
 7440:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 7441:                         $curr_remotip = $values{$dom}{remoteip};
 7442:                     }
 7443:                     if ($curr_remotip eq 'h') {
 7444:                         $currwafdisplay = ' style="display:table-row"';
 7445:                         $wafrangestyle = ' style="display:inline-block;"';
 7446:                     }
 7447:                     if ($values{$dom}{'sslopt'}) {
 7448:                         $alltossl = ' checked="checked"';
 7449:                         $ssltossl = '';
 7450:                     }
 7451:                 }
 7452:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 7453:                     $vpndircheck = ' checked="checked"';
 7454:                     $currwafvpn = ' style="display:table-row;"';
 7455:                     $wafrangestyle = ' style="display:inline-block;"';
 7456:                 } else {
 7457:                     $vpnaliascheck = ' checked="checked"';
 7458:                     $currwafvpn = ' style="display:none;"';
 7459:                 }
 7460:             }
 7461:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7462:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 7463:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 7464:                           '</tr>'.
 7465:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7466:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 7467:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 7468:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'</div></td>'.
 7469:                           '<td class="LC_left_item"><table>'.
 7470:                           '<tr>'.
 7471:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 7472:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 7473:             foreach my $option ('m','h','n') {
 7474:                 my $sel;
 7475:                 if ($option eq $curr_remotip) {
 7476:                    $sel = ' selected="selected"';
 7477:                 }
 7478:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 7479:                               $ip_methods{$option}.'</option>';
 7480:             }
 7481:             $datatable .= '</select></td></tr>'."\n".
 7482:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 7483:                           $lt{'ipheader'}.':&nbsp;'.
 7484:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 7485:                           'name="wafproxy_ipheader" />'.
 7486:                           '</td></tr>'."\n".
 7487:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 7488:                           $lt{'trusted'}.':<br />'.
 7489:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 7490:                           $values{$dom}{'trusted'}.'</textarea>'.
 7491:                           '</td></tr>'."\n".
 7492:                           '<tr><td><hr /></td></tr>'."\n".
 7493:                           '<tr>'.
 7494:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 7495:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 7496:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 7497:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 7498:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 7499:             foreach my $item ('vpnint','vpnext') {
 7500:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 7501:                               '<td valign="top">'.$lt{$item}.':<br />'.
 7502:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 7503:                               $values{$dom}{$item}.'</textarea>'.
 7504:                               '</td></tr>'."\n";
 7505:             }
 7506:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 7507:                           '<tr>'.
 7508:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 7509:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 7510:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 7511:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 7512:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 7513:                           '</table></td></tr>';
 7514:         }
 7515:         if (keys(%otherdoms)) {
 7516:             foreach my $domain (sort(keys(%otherdoms))) {
 7517:                 $itemcount ++;
 7518:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7519:                 $datatable .= '<tr'.$css_class.'>'.
 7520:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 7521:                               '<td class="LC_left_item"><table>';
 7522:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 7523:                     my $showval = &mt('None');
 7524:                     if ($item eq 'ssl') {
 7525:                         $showval = $lt{'ssltossl'};
 7526:                     }
 7527:                     if ($values{$domain}{$item}) {
 7528:                         $showval = $values{$domain}{$item};
 7529:                         if ($item eq 'ssl') {
 7530:                             $showval = $lt{'alltossl'};
 7531:                         } elsif ($item eq 'remoteip') {
 7532:                             $showval = $ip_methods{$values{$domain}{$item}};
 7533:                         }
 7534:                     }
 7535:                     $datatable .= '<tr>'.
 7536:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 7537:                 }
 7538:                 $datatable .= '</table></td></tr>';
 7539:             }
 7540:         }
 7541:     }
 7542:     $$rowtotal += $itemcount;
 7543:     return $datatable;
 7544: }
 7545: 
 7546: sub wafproxy_titles {
 7547:     return &Apache::lonlocal::texthash(
 7548:                remoteip   => "Method for determining user's IP",
 7549:                ipheader   => 'Request header containing remote IP',
 7550:                trusted    => 'Trusted IP range(s)',
 7551:                vpnaccess  => 'Access from institutional VPN',
 7552:                vpndirect  => 'via regular hostname (no WAF)',
 7553:                vpnaliased => 'via aliased hostname (WAF)',
 7554:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 7555:                vpnext     => 'IP Range(s) for backend WAF connections',
 7556:                sslopt     => 'Forwarding http/https',
 7557:                alltossl   => 'WAF forwards both http and https requests to https',
 7558:                ssltossl   => 'WAF forwards http requests to http and https to https',
 7559:            );
 7560: }
 7561: 
 7562: sub remoteip_methods {
 7563:     return &Apache::lonlocal::texthash(
 7564:               m => 'Use Apache mod_remoteip',
 7565:               h => 'Use headers parsed by LON-CAPA',
 7566:               n => 'Not in use',
 7567:            );
 7568: }
 7569: 
 7570: sub print_usersessions {
 7571:     my ($position,$dom,$settings,$rowtotal) = @_;
 7572:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 7573:     my (%by_ip,%by_location,@intdoms,@instdoms);
 7574:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7575: 
 7576:     my @alldoms = &Apache::lonnet::all_domains();
 7577:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7578:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7579:     my %altids = &id_for_thisdom(%servers);
 7580:     if ($position eq 'top') {
 7581:         if (keys(%serverhomes) > 1) {
 7582:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 7583:             my ($curroffloadnow,$curroffloadoth);
 7584:             if (ref($settings) eq 'HASH') {
 7585:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 7586:                     $curroffloadnow = $settings->{'offloadnow'};
 7587:                 }
 7588:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 7589:                     $curroffloadoth = $settings->{'offloadoth'};
 7590:                 }
 7591:             }
 7592:             my $other_insts = scalar(keys(%by_location));
 7593:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 7594:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 7595:         } else {
 7596:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 7597:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 7598:                           '</td></tr>';
 7599:         }
 7600:     } else {
 7601:         my %titles = &usersession_titles();
 7602:         my ($prefix,@types);
 7603:         if ($position eq 'bottom') {
 7604:             $prefix = 'remote';
 7605:             @types = ('version','excludedomain','includedomain');
 7606:         } else {
 7607:             $prefix = 'hosted';
 7608:             @types = ('excludedomain','includedomain');
 7609:         }
 7610:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7611:     }
 7612:     $$rowtotal += $itemcount;
 7613:     return $datatable;
 7614: }
 7615: 
 7616: sub rules_by_location {
 7617:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 7618:     my ($datatable,$itemcount,$css_class);
 7619:     if (keys(%{$by_location}) == 0) {
 7620:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7621:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 7622:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 7623:                      '</td></tr>';
 7624:         $itemcount = 1;
 7625:     } else {
 7626:         $itemcount = 0;
 7627:         my $numinrow = 5;
 7628:         my (%current,%checkedon,%checkedoff);
 7629:         my @locations = sort(keys(%{$by_location}));
 7630:         foreach my $type (@{$types}) {
 7631:             $checkedon{$type} = '';
 7632:             $checkedoff{$type} = ' checked="checked"';
 7633:         }
 7634:         if (ref($settings) eq 'HASH') {
 7635:             if (ref($settings->{$prefix}) eq 'HASH') {
 7636:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 7637:                     $current{$key} = $settings->{$prefix}{$key};
 7638:                     if ($key eq 'version') {
 7639:                         if ($current{$key} ne '') {
 7640:                             $checkedon{$key} = ' checked="checked"';
 7641:                             $checkedoff{$key} = '';
 7642:                         }
 7643:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 7644:                         $checkedon{$key} = ' checked="checked"';
 7645:                         $checkedoff{$key} = '';
 7646:                     }
 7647:                 }
 7648:             }
 7649:         }
 7650:         foreach my $type (@{$types}) {
 7651:             next if ($type ne 'version' && !@locations);
 7652:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7653:             $datatable .= '<tr'.$css_class.'>
 7654:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 7655:                            <span class="LC_nobreak">&nbsp;
 7656:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 7657:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 7658:             if ($type eq 'version') {
 7659:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 7660:                 my $selector = '<select name="'.$prefix.'_version">';
 7661:                 foreach my $version (@lcversions) {
 7662:                     my $selected = '';
 7663:                     if ($current{'version'} eq $version) {
 7664:                         $selected = ' selected="selected"';
 7665:                     }
 7666:                     $selector .= ' <option value="'.$version.'"'.
 7667:                                  $selected.'>'.$version.'</option>';
 7668:                 }
 7669:                 $selector .= '</select> ';
 7670:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 7671:             } else {
 7672:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 7673:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 7674:                              ' />'.('&nbsp;'x2).
 7675:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 7676:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 7677:                              "\n".
 7678:                              '</div><div><table>';
 7679:                 my $rem;
 7680:                 for (my $i=0; $i<@locations; $i++) {
 7681:                     my ($showloc,$value,$checkedtype);
 7682:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 7683:                         my $ip = $by_location->{$locations[$i]}->[0];
 7684:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7685:                             $value = join(':',@{$by_ip->{$ip}});
 7686:                             $showloc = join(', ',@{$by_ip->{$ip}});
 7687:                             if (ref($current{$type}) eq 'ARRAY') {
 7688:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 7689:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 7690:                                         $checkedtype = ' checked="checked"';
 7691:                                         last;
 7692:                                     }
 7693:                                 }
 7694:                             }
 7695:                         }
 7696:                     }
 7697:                     $rem = $i%($numinrow);
 7698:                     if ($rem == 0) {
 7699:                         if ($i > 0) {
 7700:                             $datatable .= '</tr>';
 7701:                         }
 7702:                         $datatable .= '<tr>';
 7703:                     }
 7704:                     $datatable .= '<td class="LC_left_item">'.
 7705:                                   '<span class="LC_nobreak"><label>'.
 7706:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 7707:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 7708:                                   '</label></span></td>';
 7709:                 }
 7710:                 $rem = @locations%($numinrow);
 7711:                 my $colsleft = $numinrow - $rem;
 7712:                 if ($colsleft > 1 ) {
 7713:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7714:                                   '&nbsp;</td>';
 7715:                 } elsif ($colsleft == 1) {
 7716:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7717:                 }
 7718:                 $datatable .= '</tr></table>';
 7719:             }
 7720:             $datatable .= '</td></tr>';
 7721:             $itemcount ++;
 7722:         }
 7723:     }
 7724:     return ($datatable,$itemcount);
 7725: }
 7726: 
 7727: sub print_ssl {
 7728:     my ($position,$dom,$settings,$rowtotal) = @_;
 7729:     my ($css_class,$datatable);
 7730:     my $itemcount = 1;
 7731:     if ($position eq 'top') {
 7732:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7733:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7734:         my $same_institution;
 7735:         if ($intdom ne '') {
 7736:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 7737:             if (ref($internet_names) eq 'ARRAY') {
 7738:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 7739:                     $same_institution = 1;
 7740:                 }
 7741:             }
 7742:         }
 7743:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7744:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 7745:         if ($same_institution) {
 7746:             my %domservers = &Apache::lonnet::get_servers($dom);
 7747:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 7748:         } else {
 7749:             $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.");
 7750:         }
 7751:         $datatable .= '</td></tr>';
 7752:         $itemcount ++;
 7753:     } else {
 7754:         my %titles = &ssl_titles();
 7755:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7756:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7757:         my @alldoms = &Apache::lonnet::all_domains();
 7758:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7759:         my @domservers = &Apache::lonnet::get_servers($dom);
 7760:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7761:         my %altids = &id_for_thisdom(%servers);
 7762:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 7763:             my $legacy;
 7764:             unless (ref($settings) eq 'HASH') {
 7765:                 my $name;
 7766:                 if ($position eq 'connto') {
 7767:                     $name = 'loncAllowInsecure';
 7768:                 } else {
 7769:                     $name = 'londAllowInsecure';
 7770:                 }
 7771:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 7772:                 my @ids=&Apache::lonnet::current_machine_ids();
 7773:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 7774:                     my %what = (
 7775:                                    $name => 1,
 7776:                                );
 7777:                     my ($result,$returnhash) =
 7778:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 7779:                     if ($result eq 'ok') {
 7780:                         if (ref($returnhash) eq 'HASH') {
 7781:                             $legacy = $returnhash->{$name};
 7782:                         }
 7783:                     }
 7784:                 } else {
 7785:                     $legacy = $Apache::lonnet::perlvar{$name};
 7786:                 }
 7787:             }
 7788:             foreach my $type ('dom','intdom','other') {
 7789:                 my %checked;
 7790:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7791:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 7792:                               '<td class="LC_right_item">';
 7793:                 my $skip; 
 7794:                 if ($type eq 'dom') {
 7795:                     unless (keys(%servers) > 1) {
 7796:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 7797:                         $skip = 1;
 7798:                     }
 7799:                 }
 7800:                 if ($type eq 'intdom') {
 7801:                     unless (@instdoms > 1) {
 7802:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 7803:                         $skip = 1;
 7804:                     } 
 7805:                 } elsif ($type eq 'other') {
 7806:                     if (keys(%by_location) == 0) {
 7807:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 7808:                         $skip = 1;
 7809:                     }
 7810:                 }
 7811:                 unless ($skip) {
 7812:                     $checked{'yes'} = ' checked="checked"'; 
 7813:                     if (ref($settings) eq 'HASH') {
 7814:                         if (ref($settings->{$position}) eq 'HASH') {
 7815:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 7816:                                 $checked{$1} = $checked{'yes'};
 7817:                                 delete($checked{'yes'}); 
 7818:                             }
 7819:                         }
 7820:                     } else {
 7821:                         if ($legacy == 0) {
 7822:                             $checked{'req'} = $checked{'yes'};
 7823:                             delete($checked{'yes'});    
 7824:                         }
 7825:                     }
 7826:                     foreach my $option ('no','yes','req') {
 7827:                         $datatable .= '<span class="LC_nobreak"><label>'.
 7828:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 7829:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7830:                                       '</label></span>'.('&nbsp;'x2);
 7831:                     }
 7832:                 }
 7833:                 $datatable .= '</td></tr>';
 7834:                 $itemcount ++; 
 7835:             }
 7836:         } else {
 7837:             my $prefix = 'replication';
 7838:             my @types = ('certreq','nocertreq');
 7839:             if (keys(%by_location) == 0) {
 7840:                 $datatable .= '<tr'.$css_class.'><td>'.
 7841:                               &mt('Nothing to set here, as there are no other institutions').
 7842:                               '</td></tr>';
 7843:                 $itemcount ++;
 7844:             } else {
 7845:                 ($datatable,$itemcount) = 
 7846:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7847:             }
 7848:         }
 7849:     }
 7850:     $$rowtotal += $itemcount;
 7851:     return $datatable;
 7852: }
 7853: 
 7854: sub ssl_titles {
 7855:     return &Apache::lonlocal::texthash (
 7856:                dom           => 'LON-CAPA servers/VMs from same domain',
 7857:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 7858:                other         => 'External LON-CAPA servers/VMs',
 7859:                connto        => 'Connections to other servers',
 7860:                connfrom      => 'Connections from other servers',
 7861:                replication   => 'Replicating content to other institutions',
 7862:                certreq       => 'Client certificate required, but specific domains exempt',
 7863:                nocertreq     => 'No client certificate required, except for specific domains',
 7864:                no            => 'SSL not used',
 7865:                yes           => 'SSL Optional (used if available)',
 7866:                req           => 'SSL Required',
 7867:     );
 7868: }
 7869: 
 7870: sub print_trust {
 7871:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 7872:     my ($css_class,$datatable,%checked,%choices);
 7873:     my (%by_ip,%by_location,@intdoms,@instdoms);
 7874:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7875:     my $itemcount = 1;
 7876:     my %titles = &trust_titles();
 7877:     my @types = ('exc','inc');
 7878:     if ($prefix eq 'top') {
 7879:         $prefix = 'content';
 7880:     } elsif ($prefix eq 'bottom') {
 7881:         $prefix = 'msg';
 7882:     }
 7883:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7884:     $$rowtotal += $itemcount;
 7885:     return $datatable;
 7886: }
 7887: 
 7888: sub trust_titles {
 7889:     return &Apache::lonlocal::texthash(
 7890:                content  => "Access to this domain's content by others",
 7891:                shared   => "Access to other domain's content by this domain",
 7892:                enroll   => "Enrollment in this domain's courses by others", 
 7893:                othcoau  => "Co-author roles in this domain for others",
 7894:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 7895:                domroles => "Domain roles in this domain assignable to others",
 7896:                catalog  => "Course Catalog for this domain displayed elsewhere",
 7897:                reqcrs   => "Requests for creation of courses in this domain by others",
 7898:                msg      => "Users in other domains can send messages to this domain",
 7899:                exc      => "Allow all, but exclude specific domains",
 7900:                inc      => "Deny all, but include specific domains",
 7901:            );
 7902: } 
 7903: 
 7904: sub build_location_hashes {
 7905:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 7906:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 7907:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 7908:     my %iphost = &Apache::lonnet::get_iphost();
 7909:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 7910:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 7911:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 7912:         foreach my $id (@{$iphost{$primary_ip}}) {
 7913:             my $intdom = &Apache::lonnet::internet_dom($id);
 7914:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 7915:                 push(@{$intdoms},$intdom);
 7916:             }
 7917:         }
 7918:     }
 7919:     foreach my $ip (keys(%iphost)) {
 7920:         if (ref($iphost{$ip}) eq 'ARRAY') {
 7921:             foreach my $id (@{$iphost{$ip}}) {
 7922:                 my $location = &Apache::lonnet::internet_dom($id);
 7923:                 if ($location) {
 7924:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 7925:                         my $dom = &Apache::lonnet::host_domain($id);
 7926:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 7927:                             push(@{$instdoms},$dom);
 7928:                         }
 7929:                         next;
 7930:                     }
 7931:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7932:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 7933:                             push(@{$by_ip->{$ip}},$location);
 7934:                         }
 7935:                     } else {
 7936:                         $by_ip->{$ip} = [$location];
 7937:                     }
 7938:                 }
 7939:             }
 7940:         }
 7941:     }
 7942:     foreach my $ip (sort(keys(%{$by_ip}))) {
 7943:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7944:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 7945:             my $first = $by_ip->{$ip}->[0];
 7946:             if (ref($by_location->{$first}) eq 'ARRAY') {
 7947:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 7948:                     push(@{$by_location->{$first}},$ip);
 7949:                 }
 7950:             } else {
 7951:                 $by_location->{$first} = [$ip];
 7952:             }
 7953:         }
 7954:     }
 7955:     return;
 7956: }
 7957: 
 7958: sub current_offloads_to {
 7959:     my ($dom,$settings,$servers) = @_;
 7960:     my (%spareid,%otherdomconfigs);
 7961:     if (ref($servers) eq 'HASH') {
 7962:         foreach my $lonhost (sort(keys(%{$servers}))) {
 7963:             my $gotspares;
 7964:             if (ref($settings) eq 'HASH') {
 7965:                 if (ref($settings->{'spares'}) eq 'HASH') {
 7966:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 7967:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 7968:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 7969:                         $gotspares = 1;
 7970:                     }
 7971:                 }
 7972:             }
 7973:             unless ($gotspares) {
 7974:                 my $gotspares;
 7975:                 my $serverhomeID =
 7976:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 7977:                 my $serverhomedom =
 7978:                     &Apache::lonnet::host_domain($serverhomeID);
 7979:                 if ($serverhomedom ne $dom) {
 7980:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 7981:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 7982:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 7983:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 7984:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 7985:                                 $gotspares = 1;
 7986:                             }
 7987:                         }
 7988:                     } else {
 7989:                         $otherdomconfigs{$serverhomedom} =
 7990:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 7991:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 7992:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 7993:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 7994:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 7995:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 7996:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 7997:                                         $gotspares = 1;
 7998:                                     }
 7999:                                 }
 8000:                             }
 8001:                         }
 8002:                     }
 8003:                 }
 8004:             }
 8005:             unless ($gotspares) {
 8006:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8007:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8008:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8009:                } else {
 8010:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 8011:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 8012:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 8013:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 8014:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 8015:                     } else {
 8016:                         my %what = (
 8017:                              spareid => 1,
 8018:                         );
 8019:                         my ($result,$returnhash) = 
 8020:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 8021:                         if ($result eq 'ok') { 
 8022:                             if (ref($returnhash) eq 'HASH') {
 8023:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 8024:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 8025:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 8026:                                 }
 8027:                             }
 8028:                         }
 8029:                     }
 8030:                 }
 8031:             }
 8032:         }
 8033:     }
 8034:     return %spareid;
 8035: }
 8036: 
 8037: sub spares_row {
 8038:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 8039:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 8040:     my $css_class;
 8041:     my $numinrow = 4;
 8042:     my $itemcount = 1;
 8043:     my $datatable;
 8044:     my %typetitles = &sparestype_titles();
 8045:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8046:         foreach my $server (sort(keys(%{$servers}))) {
 8047:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 8048:             my ($othercontrol,$serverdom);
 8049:             if ($serverhome ne $server) {
 8050:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 8051:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8052:             } else {
 8053:                 $serverdom = &Apache::lonnet::host_domain($server);
 8054:                 if ($serverdom ne $dom) {
 8055:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8056:                 }
 8057:             }
 8058:             next unless (ref($spareid->{$server}) eq 'HASH');
 8059:             my ($checkednow,$checkedoth);
 8060:             if (ref($curroffloadnow) eq 'HASH') {
 8061:                 if ($curroffloadnow->{$server}) {
 8062:                     $checkednow = ' checked="checked"';
 8063:                 }
 8064:             }
 8065:             if (ref($curroffloadoth) eq 'HASH') {
 8066:                 if ($curroffloadoth->{$server}) {
 8067:                     $checkedoth = ' checked="checked"';
 8068:                 }
 8069:             }
 8070:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8071:             $datatable .= '<tr'.$css_class.'>
 8072:                            <td rowspan="2">
 8073:                             <span class="LC_nobreak">'.
 8074:                           &mt('[_1] when busy, offloads to:'
 8075:                               ,'<b>'.$server.'</b>').'</span><br />'.
 8076:                           '<span class="LC_nobreak">'."\n".
 8077:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 8078:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 8079:                           "\n";
 8080:             if ($other_insts) {
 8081:                 $datatable .= '<br />'.
 8082:                               '<span class="LC_nobreak">'."\n".
 8083:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 8084:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 8085:                           "\n";
 8086:             }
 8087:             my (%current,%canselect);
 8088:             my @choices = 
 8089:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 8090:             foreach my $type ('primary','default') {
 8091:                 if (ref($spareid->{$server}) eq 'HASH') {
 8092:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 8093:                         my @spares = @{$spareid->{$server}{$type}};
 8094:                         if (@spares > 0) {
 8095:                             if ($othercontrol) {
 8096:                                 $current{$type} = join(', ',@spares);
 8097:                             } else {
 8098:                                 $current{$type} .= '<table>';
 8099:                                 my $numspares = scalar(@spares);
 8100:                                 for (my $i=0;  $i<@spares; $i++) {
 8101:                                     my $rem = $i%($numinrow);
 8102:                                     if ($rem == 0) {
 8103:                                         if ($i > 0) {
 8104:                                             $current{$type} .= '</tr>';
 8105:                                         }
 8106:                                         $current{$type} .= '<tr>';
 8107:                                     }
 8108:                                     $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;'.
 8109:                                                        $spareid->{$server}{$type}[$i].
 8110:                                                        '</label></td>'."\n";
 8111:                                 }
 8112:                                 my $rem = @spares%($numinrow);
 8113:                                 my $colsleft = $numinrow - $rem;
 8114:                                 if ($colsleft > 1 ) {
 8115:                                     $current{$type} .= '<td colspan="'.$colsleft.
 8116:                                                        '" class="LC_left_item">'.
 8117:                                                        '&nbsp;</td>';
 8118:                                 } elsif ($colsleft == 1) {
 8119:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 8120:                                 }
 8121:                                 $current{$type} .= '</tr></table>';
 8122:                             }
 8123:                         }
 8124:                     }
 8125:                     if ($current{$type} eq '') {
 8126:                         $current{$type} = &mt('None specified');
 8127:                     }
 8128:                     if ($othercontrol) {
 8129:                         if ($type eq 'primary') {
 8130:                             $canselect{$type} = $othercontrol;
 8131:                         }
 8132:                     } else {
 8133:                         $canselect{$type} = 
 8134:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 8135:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 8136:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 8137:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 8138:                         if (@choices > 0) {
 8139:                             foreach my $lonhost (@choices) {
 8140:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 8141:                             }
 8142:                         }
 8143:                         $canselect{$type} .= '</select>'."\n";
 8144:                     }
 8145:                 } else {
 8146:                     $current{$type} = &mt('Could not be determined');
 8147:                     if ($type eq 'primary') {
 8148:                         $canselect{$type} =  $othercontrol;
 8149:                     }
 8150:                 }
 8151:                 if ($type eq 'default') {
 8152:                     $datatable .= '<tr'.$css_class.'>';
 8153:                 }
 8154:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 8155:                               '<td>'.$current{$type}.'</td>'."\n".
 8156:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 8157:             }
 8158:             $itemcount ++;
 8159:         }
 8160:     }
 8161:     $$rowtotal += $itemcount;
 8162:     return $datatable;
 8163: }
 8164: 
 8165: sub possible_newspares {
 8166:     my ($server,$currspares,$serverhomes,$altids) = @_;
 8167:     my $serverhostname = &Apache::lonnet::hostname($server);
 8168:     my %excluded;
 8169:     if ($serverhostname ne '') {
 8170:         %excluded = (
 8171:                        $serverhostname => 1,
 8172:                     );
 8173:     }
 8174:     if (ref($currspares) eq 'HASH') {
 8175:         foreach my $type (keys(%{$currspares})) {
 8176:             if (ref($currspares->{$type}) eq 'ARRAY') {
 8177:                 if (@{$currspares->{$type}} > 0) {
 8178:                     foreach my $curr (@{$currspares->{$type}}) {
 8179:                         my $hostname = &Apache::lonnet::hostname($curr);
 8180:                         $excluded{$hostname} = 1;
 8181:                     }
 8182:                 }
 8183:             }
 8184:         }
 8185:     }
 8186:     my @choices;
 8187:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8188:         if (keys(%{$serverhomes}) > 1) {
 8189:             foreach my $name (sort(keys(%{$serverhomes}))) {
 8190:                 unless ($excluded{$name}) {
 8191:                     if (exists($altids->{$serverhomes->{$name}})) {
 8192:                         push(@choices,$altids->{$serverhomes->{$name}});
 8193:                     } else {
 8194:                         push(@choices,$serverhomes->{$name});
 8195:                     }
 8196:                 }
 8197:             }
 8198:         }
 8199:     }
 8200:     return sort(@choices);
 8201: }
 8202: 
 8203: sub print_loadbalancing {
 8204:     my ($dom,$settings,$rowtotal) = @_;
 8205:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8206:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8207:     my $numinrow = 1;
 8208:     my $datatable;
 8209:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8210:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 8211:     if (ref($settings) eq 'HASH') {
 8212:         %existing = %{$settings};
 8213:     }
 8214:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 8215:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 8216:                                   \%currtargets,\%currrules,\%currcookies);
 8217:     } else {
 8218:         return;
 8219:     }
 8220:     my ($othertitle,$usertypes,$types) =
 8221:         &Apache::loncommon::sorted_inst_types($dom);
 8222:     my $rownum = 8;
 8223:     if (ref($types) eq 'ARRAY') {
 8224:         $rownum += scalar(@{$types});
 8225:     }
 8226:     my @css_class = ('LC_odd_row','LC_even_row');
 8227:     my $balnum = 0;
 8228:     my $islast;
 8229:     my (@toshow,$disabledtext);
 8230:     if (keys(%currbalancer) > 0) {
 8231:         @toshow = sort(keys(%currbalancer));
 8232:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 8233:             push(@toshow,'');
 8234:         }
 8235:     } else {
 8236:         @toshow = ('');
 8237:         $disabledtext = &mt('No existing load balancer');
 8238:     }
 8239:     foreach my $lonhost (@toshow) {
 8240:         if ($balnum == scalar(@toshow)-1) {
 8241:             $islast = 1;
 8242:         } else {
 8243:             $islast = 0;
 8244:         }
 8245:         my $cssidx = $balnum%2;
 8246:         my $targets_div_style = 'display: none';
 8247:         my $disabled_div_style = 'display: block';
 8248:         my $homedom_div_style = 'display: none';
 8249:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 8250:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8251:                       '<p>';
 8252:         if ($lonhost eq '') {
 8253:             $datatable .= '<span class="LC_nobreak">';
 8254:             if (keys(%currbalancer) > 0) {
 8255:                 $datatable .= &mt('Add balancer:');
 8256:             } else {
 8257:                 $datatable .= &mt('Enable balancer:');
 8258:             }
 8259:             $datatable .= '&nbsp;'.
 8260:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 8261:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 8262:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 8263:                           '<option value="" selected="selected">'.&mt('None').
 8264:                           '</option>'."\n";
 8265:             foreach my $server (sort(keys(%servers))) {
 8266:                 next if ($currbalancer{$server});
 8267:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 8268:             }
 8269:             $datatable .=
 8270:                 '</select>'."\n".
 8271:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 8272:         } else {
 8273:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 8274:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 8275:                            &mt('Stop balancing').'</label>'.
 8276:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 8277:             $targets_div_style = 'display: block';
 8278:             $disabled_div_style = 'display: none';
 8279:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 8280:                 $homedom_div_style = 'display: block';
 8281:             }
 8282:         }
 8283:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8284:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 8285:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 8286:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 8287:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 8288:         my @sparestypes = ('primary','default');
 8289:         my %typetitles = &sparestype_titles();
 8290:         my %hostherechecked = (
 8291:                                   no => ' checked="checked"',
 8292:                               );
 8293:         my %balcookiechecked = (
 8294:                                   no => ' checked="checked"', 
 8295:                                );
 8296:         foreach my $sparetype (@sparestypes) {
 8297:             my $targettable;
 8298:             for (my $i=0; $i<$numspares; $i++) {
 8299:                 my $checked;
 8300:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 8301:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8302:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8303:                             $checked = ' checked="checked"';
 8304:                         }
 8305:                     }
 8306:                 }
 8307:                 my ($chkboxval,$disabled);
 8308:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 8309:                     $chkboxval = $spares[$i];
 8310:                 }
 8311:                 if (exists($currbalancer{$spares[$i]})) {
 8312:                     $disabled = ' disabled="disabled"';
 8313:                 }
 8314:                 $targettable .=
 8315:                     '<td><span class="LC_nobreak"><label>'.
 8316:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 8317:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 8318:                     '</span></label></span></td>';
 8319:                 my $rem = $i%($numinrow);
 8320:                 if ($rem == 0) {
 8321:                     if (($i > 0) && ($i < $numspares-1)) {
 8322:                         $targettable .= '</tr>';
 8323:                     }
 8324:                     if ($i < $numspares-1) {
 8325:                         $targettable .= '<tr>';
 8326:                     }
 8327:                 }
 8328:             }
 8329:             if ($targettable ne '') {
 8330:                 my $rem = $numspares%($numinrow);
 8331:                 my $colsleft = $numinrow - $rem;
 8332:                 if ($colsleft > 1 ) {
 8333:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8334:                                     '&nbsp;</td>';
 8335:                 } elsif ($colsleft == 1) {
 8336:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 8337:                 }
 8338:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 8339:                                '<table><tr>'.$targettable.'</tr></table><br />';
 8340:             }
 8341:             $hostherechecked{$sparetype} = '';
 8342:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 8343:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8344:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8345:                         $hostherechecked{$sparetype} = ' checked="checked"';
 8346:                         $hostherechecked{'no'} = '';
 8347:                     }
 8348:                 }
 8349:             }
 8350:         }
 8351:         if ($currcookies{$lonhost}) {
 8352:             %balcookiechecked = (
 8353:                                     yes => ' checked="checked"',
 8354:                                 );
 8355:         }
 8356:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 8357:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 8358:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 8359:         foreach my $sparetype (@sparestypes) {
 8360:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 8361:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 8362:                           '</i></label><br />';
 8363:         }
 8364:         $datatable .= &mt('Use balancer cookie').'<br />'.
 8365:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 8366:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 8367:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 8368:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 8369:                       '</div></td></tr>'.
 8370:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 8371:                                            $othertitle,$usertypes,$types,\%servers,
 8372:                                            \%currbalancer,$lonhost,
 8373:                                            $targets_div_style,$homedom_div_style,
 8374:                                            $css_class[$cssidx],$balnum,$islast);
 8375:         $$rowtotal += $rownum;
 8376:         $balnum ++;
 8377:     }
 8378:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 8379:     return $datatable;
 8380: }
 8381: 
 8382: sub get_loadbalancers_config {
 8383:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 8384:     return unless ((ref($servers) eq 'HASH') &&
 8385:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 8386:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 8387:                    (ref($currcookies) eq 'HASH'));
 8388:     if (keys(%{$existing}) > 0) {
 8389:         my $oldlonhost;
 8390:         foreach my $key (sort(keys(%{$existing}))) {
 8391:             if ($key eq 'lonhost') {
 8392:                 $oldlonhost = $existing->{'lonhost'};
 8393:                 $currbalancer->{$oldlonhost} = 1;
 8394:             } elsif ($key eq 'targets') {
 8395:                 if ($oldlonhost) {
 8396:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 8397:                 }
 8398:             } elsif ($key eq 'rules') {
 8399:                 if ($oldlonhost) {
 8400:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 8401:                 }
 8402:             } elsif (ref($existing->{$key}) eq 'HASH') {
 8403:                 $currbalancer->{$key} = 1;
 8404:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 8405:                 $currrules->{$key} = $existing->{$key}{'rules'};
 8406:                 if ($existing->{$key}{'cookie'}) {
 8407:                     $currcookies->{$key} = 1;
 8408:                 }
 8409:             }
 8410:         }
 8411:     } else {
 8412:         my ($balancerref,$targetsref) =
 8413:                 &Apache::lonnet::get_lonbalancer_config($servers);
 8414:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 8415:             foreach my $server (sort(keys(%{$balancerref}))) {
 8416:                 $currbalancer->{$server} = 1;
 8417:                 $currtargets->{$server} = $targetsref->{$server};
 8418:             }
 8419:         }
 8420:     }
 8421:     return;
 8422: }
 8423: 
 8424: sub loadbalancing_rules {
 8425:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 8426:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 8427:         $css_class,$balnum,$islast) = @_;
 8428:     my $output;
 8429:     my $num = 0;
 8430:     my ($alltypes,$othertypes,$titles) =
 8431:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 8432:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 8433:         foreach my $type (@{$alltypes}) {
 8434:             $num ++;
 8435:             my $current;
 8436:             if (ref($currrules) eq 'HASH') {
 8437:                 $current = $currrules->{$type};
 8438:             }
 8439:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8440:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 8441:                     $current = '';
 8442:                 }
 8443:             }
 8444:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 8445:                                              $servers,$currbalancer,$lonhost,$dom,
 8446:                                              $targets_div_style,$homedom_div_style,
 8447:                                              $css_class,$balnum,$num,$islast);
 8448:         }
 8449:     }
 8450:     return $output;
 8451: }
 8452: 
 8453: sub loadbalancing_titles {
 8454:     my ($dom,$intdom,$usertypes,$types) = @_;
 8455:     my %othertypes = (
 8456:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 8457:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 8458:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 8459:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 8460:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 8461:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 8462:                      );
 8463:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 8464:     my @available;
 8465:     if (ref($types) eq 'ARRAY') {
 8466:         @available = @{$types};
 8467:     }
 8468:     unless (grep(/^default$/,@available)) {
 8469:         push(@available,'default');
 8470:     }
 8471:     unshift(@alltypes,@available);
 8472:     my %titles;
 8473:     foreach my $type (@alltypes) {
 8474:         if ($type =~ /^_LC_/) {
 8475:             $titles{$type} = $othertypes{$type};
 8476:         } elsif ($type eq 'default') {
 8477:             $titles{$type} = &mt('All users from [_1]',$dom);
 8478:             if (ref($types) eq 'ARRAY') {
 8479:                 if (@{$types} > 0) {
 8480:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 8481:                 }
 8482:             }
 8483:         } elsif (ref($usertypes) eq 'HASH') {
 8484:             $titles{$type} = $usertypes->{$type};
 8485:         }
 8486:     }
 8487:     return (\@alltypes,\%othertypes,\%titles);
 8488: }
 8489: 
 8490: sub loadbalance_rule_row {
 8491:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 8492:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 8493:     my @rulenames;
 8494:     my %ruletitles = &offloadtype_text();
 8495:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 8496:         @rulenames = ('balancer','offloadedto','specific');
 8497:     } else {
 8498:         @rulenames = ('default','homeserver');
 8499:         if ($type eq '_LC_external') {
 8500:             push(@rulenames,'externalbalancer');
 8501:         } else {
 8502:             push(@rulenames,'specific');
 8503:         }
 8504:         push(@rulenames,'none');
 8505:     }
 8506:     my $style = $targets_div_style;
 8507:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8508:         $style = $homedom_div_style;
 8509:     }
 8510:     my $space;
 8511:     if ($islast && $num == 1) {
 8512:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 8513:     }
 8514:     my $output =
 8515:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 8516:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 8517:         '<td valaign="top">'.$space.
 8518:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 8519:     for (my $i=0; $i<@rulenames; $i++) {
 8520:         my $rule = $rulenames[$i];
 8521:         my ($checked,$extra);
 8522:         if ($rulenames[$i] eq 'default') {
 8523:             $rule = '';
 8524:         }
 8525:         if ($rulenames[$i] eq 'specific') {
 8526:             if (ref($servers) eq 'HASH') {
 8527:                 my $default;
 8528:                 if (($current ne '') && (exists($servers->{$current}))) {
 8529:                     $checked = ' checked="checked"';
 8530:                 }
 8531:                 unless ($checked) {
 8532:                     $default = ' selected="selected"';
 8533:                 }
 8534:                 $extra =
 8535:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8536:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8537:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 8538:                     '<option value=""'.$default.'></option>'."\n";
 8539:                 foreach my $server (sort(keys(%{$servers}))) {
 8540:                     if (ref($currbalancer) eq 'HASH') {
 8541:                         next if (exists($currbalancer->{$server}));
 8542:                     }
 8543:                     my $selected;
 8544:                     if ($server eq $current) {
 8545:                         $selected = ' selected="selected"';
 8546:                     }
 8547:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 8548:                 }
 8549:                 $extra .= '</select>';
 8550:             }
 8551:         } elsif ($rule eq $current) {
 8552:             $checked = ' checked="checked"';
 8553:         }
 8554:         $output .= '<span class="LC_nobreak"><label>'.
 8555:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 8556:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 8557:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 8558:                    ')"'.$checked.' />&nbsp;';
 8559:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 8560:             $output .= $ruletitles{'particular'};
 8561:         } else {
 8562:             $output .= $ruletitles{$rulenames[$i]};
 8563:         }
 8564:         $output .= '</label>'.$extra.'</span><br />'."\n";
 8565:     }
 8566:     $output .= '</div></td></tr>'."\n";
 8567:     return $output;
 8568: }
 8569: 
 8570: sub offloadtype_text {
 8571:     my %ruletitles = &Apache::lonlocal::texthash (
 8572:            'default'          => 'Offloads to default destinations',
 8573:            'homeserver'       => "Offloads to user's home server",
 8574:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 8575:            'specific'         => 'Offloads to specific server',
 8576:            'none'             => 'No offload',
 8577:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 8578:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 8579:            'particular'       => 'Session hosted (after re-auth) on server:',
 8580:     );
 8581:     return %ruletitles;
 8582: }
 8583: 
 8584: sub sparestype_titles {
 8585:     my %typestitles = &Apache::lonlocal::texthash (
 8586:                           'primary' => 'primary',
 8587:                           'default' => 'default',
 8588:                       );
 8589:     return %typestitles;
 8590: }
 8591: 
 8592: sub contact_titles {
 8593:     my %titles = &Apache::lonlocal::texthash (
 8594:                    'supportemail'    => 'Support E-mail address',
 8595:                    'adminemail'      => 'Default Server Admin E-mail address',
 8596:                    'errormail'       => 'Error reports to be e-mailed to',
 8597:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 8598:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 8599:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 8600:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 8601:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 8602:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 8603:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 8604:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 8605:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 8606:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 8607:                    'errorweights'    => 'Weights used to compute error count',
 8608:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 8609:                  );
 8610:     my %short_titles = &Apache::lonlocal::texthash (
 8611:                            adminemail   => 'Admin E-mail address',
 8612:                            supportemail => 'Support E-mail',
 8613:                        );   
 8614:     return (\%titles,\%short_titles);
 8615: }
 8616: 
 8617: sub helpform_fields {
 8618:     my %titles =  &Apache::lonlocal::texthash (
 8619:                        'username'   => 'Name',
 8620:                        'user'       => 'Username/domain',
 8621:                        'phone'      => 'Phone',
 8622:                        'cc'         => 'Cc e-mail',
 8623:                        'course'     => 'Course Details',
 8624:                        'section'    => 'Sections',
 8625:                        'screenshot' => 'File upload',
 8626:     );
 8627:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 8628:     my %possoptions = (
 8629:                         username     => ['yes','no','req'],
 8630:                         phone        => ['yes','no','req'],
 8631:                         user         => ['yes','no'],
 8632:                         cc           => ['yes','no'],
 8633:                         course       => ['yes','no'],
 8634:                         section      => ['yes','no'],
 8635:                         screenshot   => ['yes','no'],
 8636:                       );
 8637:     my %fieldoptions = &Apache::lonlocal::texthash (
 8638:                          'yes'  => 'Optional',
 8639:                          'req'  => 'Required',
 8640:                          'no'   => "Not shown",
 8641:     );
 8642:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 8643: }
 8644: 
 8645: sub tool_titles {
 8646:     my %titles = &Apache::lonlocal::texthash (
 8647:                      aboutme    => 'Personal web page',
 8648:                      blog       => 'Blog',
 8649:                      webdav     => 'WebDAV',
 8650:                      portfolio  => 'Portfolio',
 8651:                      official   => 'Official courses (with institutional codes)',
 8652:                      unofficial => 'Unofficial courses',
 8653:                      community  => 'Communities',
 8654:                      textbook   => 'Textbook courses',
 8655:                      placement  => 'Placement tests',
 8656:                  );
 8657:     return %titles;
 8658: }
 8659: 
 8660: sub courserequest_titles {
 8661:     my %titles = &Apache::lonlocal::texthash (
 8662:                                    official   => 'Official',
 8663:                                    unofficial => 'Unofficial',
 8664:                                    community  => 'Communities',
 8665:                                    textbook   => 'Textbook',
 8666:                                    placement  => 'Placement tests',
 8667:                                    lti        => 'LTI Provider',
 8668:                                    norequest  => 'Not allowed',
 8669:                                    approval   => 'Approval by DC',
 8670:                                    validate   => 'With validation',
 8671:                                    autolimit  => 'Numerical limit',
 8672:                                    unlimited  => '(blank for unlimited)',
 8673:                  );
 8674:     return %titles;
 8675: }
 8676: 
 8677: sub authorrequest_titles {
 8678:     my %titles = &Apache::lonlocal::texthash (
 8679:                                    norequest  => 'Not allowed',
 8680:                                    approval   => 'Approval by Dom. Coord.',
 8681:                                    automatic  => 'Automatic approval',
 8682:                  );
 8683:     return %titles;
 8684: }
 8685: 
 8686: sub courserequest_conditions {
 8687:     my %conditions = &Apache::lonlocal::texthash (
 8688:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 8689:        validate   => '(Processing of request subject to institutional validation).',
 8690:                  );
 8691:     return %conditions;
 8692: }
 8693: 
 8694: 
 8695: sub print_usercreation {
 8696:     my ($position,$dom,$settings,$rowtotal) = @_;
 8697:     my $numinrow = 4;
 8698:     my $datatable;
 8699:     if ($position eq 'top') {
 8700:         $$rowtotal ++;
 8701:         my $rowcount = 0;
 8702:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 8703:         if (ref($rules) eq 'HASH') {
 8704:             if (keys(%{$rules}) > 0) {
 8705:                 $datatable .= &user_formats_row('username',$settings,$rules,
 8706:                                                 $ruleorder,$numinrow,$rowcount);
 8707:                 $$rowtotal ++;
 8708:                 $rowcount ++;
 8709:             }
 8710:         }
 8711:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 8712:         if (ref($idrules) eq 'HASH') {
 8713:             if (keys(%{$idrules}) > 0) {
 8714:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 8715:                                                 $idruleorder,$numinrow,$rowcount);
 8716:                 $$rowtotal ++;
 8717:                 $rowcount ++;
 8718:             }
 8719:         }
 8720:         if ($rowcount == 0) {
 8721:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 8722:             $$rowtotal ++;
 8723:             $rowcount ++;
 8724:         }
 8725:     } elsif ($position eq 'middle') {
 8726:         my @creators = ('author','course','requestcrs');
 8727:         my ($rules,$ruleorder) =
 8728:             &Apache::lonnet::inst_userrules($dom,'username');
 8729:         my %lt = &usercreation_types();
 8730:         my %checked;
 8731:         if (ref($settings) eq 'HASH') {
 8732:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 8733:                 foreach my $item (@creators) {
 8734:                     $checked{$item} = $settings->{'cancreate'}{$item};
 8735:                 }
 8736:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 8737:                 foreach my $item (@creators) {
 8738:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 8739:                         $checked{$item} = 'none';
 8740:                     }
 8741:                 }
 8742:             }
 8743:         }
 8744:         my $rownum = 0;
 8745:         foreach my $item (@creators) {
 8746:             $rownum ++;
 8747:             if ($checked{$item} eq '') {
 8748:                 $checked{$item} = 'any';
 8749:             }
 8750:             my $css_class;
 8751:             if ($rownum%2) {
 8752:                 $css_class = '';
 8753:             } else {
 8754:                 $css_class = ' class="LC_odd_row" ';
 8755:             }
 8756:             $datatable .= '<tr'.$css_class.'>'.
 8757:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 8758:                          '</span></td><td style="text-align: right">';
 8759:             my @options = ('any');
 8760:             if (ref($rules) eq 'HASH') {
 8761:                 if (keys(%{$rules}) > 0) {
 8762:                     push(@options,('official','unofficial'));
 8763:                 }
 8764:             }
 8765:             push(@options,'none');
 8766:             foreach my $option (@options) {
 8767:                 my $type = 'radio';
 8768:                 my $check = ' ';
 8769:                 if ($checked{$item} eq $option) {
 8770:                     $check = ' checked="checked" ';
 8771:                 } 
 8772:                 $datatable .= '<span class="LC_nobreak"><label>'.
 8773:                               '<input type="'.$type.'" name="can_createuser_'.
 8774:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 8775:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 8776:             }
 8777:             $datatable .= '</td></tr>';
 8778:         }
 8779:     } else {
 8780:         my @contexts = ('author','course','domain');
 8781:         my @authtypes = ('int','krb4','krb5','loc','lti');
 8782:         my %checked;
 8783:         if (ref($settings) eq 'HASH') {
 8784:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 8785:                 foreach my $item (@contexts) {
 8786:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 8787:                         foreach my $auth (@authtypes) {
 8788:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 8789:                                 $checked{$item}{$auth} = ' checked="checked" ';
 8790:                             }
 8791:                         }
 8792:                     }
 8793:                 }
 8794:             }
 8795:         } else {
 8796:             foreach my $item (@contexts) {
 8797:                 foreach my $auth (@authtypes) {
 8798:                     $checked{$item}{$auth} = ' checked="checked" ';
 8799:                 }
 8800:             }
 8801:         }
 8802:         my %title = &context_names();
 8803:         my %authname = &authtype_names();
 8804:         my $rownum = 0;
 8805:         my $css_class; 
 8806:         foreach my $item (@contexts) {
 8807:             if ($rownum%2) {
 8808:                 $css_class = '';
 8809:             } else {
 8810:                 $css_class = ' class="LC_odd_row" ';
 8811:             }
 8812:             $datatable .=   '<tr'.$css_class.'>'.
 8813:                             '<td>'.$title{$item}.
 8814:                             '</td><td class="LC_left_item">'.
 8815:                             '<span class="LC_nobreak">';
 8816:             foreach my $auth (@authtypes) {
 8817:                 $datatable .= '<label>'. 
 8818:                               '<input type="checkbox" name="'.$item.'_auth" '.
 8819:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 8820:                               $authname{$auth}.'</label>&nbsp;';
 8821:             }
 8822:             $datatable .= '</span></td></tr>';
 8823:             $rownum ++;
 8824:         }
 8825:         $$rowtotal += $rownum;
 8826:     }
 8827:     return $datatable;
 8828: }
 8829: 
 8830: sub print_selfcreation {
 8831:     my ($position,$dom,$settings,$rowtotal) = @_;
 8832:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 8833:         $emaildomain,$datatable);
 8834:     if (ref($settings) eq 'HASH') {
 8835:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 8836:             $createsettings = $settings->{'cancreate'};
 8837:             if (ref($createsettings) eq 'HASH') {
 8838:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 8839:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 8840:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 8841:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 8842:                         @selfcreate = ('email','login','sso');
 8843:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 8844:                         @selfcreate = ($createsettings->{'selfcreate'});
 8845:                     }
 8846:                 }
 8847:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 8848:                     $processing = $createsettings->{'selfcreateprocessing'};
 8849:                 }
 8850:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 8851:                     $emailoptions = $createsettings->{'emailoptions'};
 8852:                 }
 8853:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 8854:                     $emailverified = $createsettings->{'emailverified'};
 8855:                 }
 8856:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 8857:                     $emaildomain = $createsettings->{'emaildomain'};
 8858:                 }
 8859:             }
 8860:         }
 8861:     }
 8862:     my %radiohash;
 8863:     my $numinrow = 4;
 8864:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 8865:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8866:     if ($position eq 'top') {
 8867:         my %choices = &Apache::lonlocal::texthash (
 8868:                                                       cancreate_login      => 'Institutional Login',
 8869:                                                       cancreate_sso        => 'Institutional Single Sign On',
 8870:                                                   );
 8871:         my @toggles = sort(keys(%choices));
 8872:         my %defaultchecked = (
 8873:                                'cancreate_login' => 'off',
 8874:                                'cancreate_sso'   => 'off',
 8875:                              );
 8876:         my ($onclick,$itemcount);
 8877:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 8878:                                                      \%choices,$itemcount,$onclick);
 8879:         $$rowtotal += $itemcount;
 8880:         
 8881:         if (ref($usertypes) eq 'HASH') {
 8882:             if (keys(%{$usertypes}) > 0) {
 8883:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 8884:                                              $dom,$numinrow,$othertitle,
 8885:                                              'statustocreate',$rowtotal);
 8886:                 $$rowtotal ++;
 8887:             }
 8888:         }
 8889:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 8890:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 8891:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 8892:         my $rem;
 8893:         my $numperrow = 2;
 8894:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 8895:         $datatable .= '<tr'.$css_class.'>'.
 8896:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 8897:                      '<td class="LC_left_item">'."\n".
 8898:                      '<table>'."\n";
 8899:         for (my $i=0; $i<@fields; $i++) {
 8900:             $rem = $i%($numperrow);
 8901:             if ($rem == 0) {
 8902:                 if ($i > 0) {
 8903:                     $datatable .= '</tr>';
 8904:                 }
 8905:                 $datatable .= '<tr>';
 8906:             }
 8907:             my $currval;
 8908:             if (ref($createsettings) eq 'HASH') {
 8909:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 8910:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 8911:                 }
 8912:             }
 8913:             $datatable .= '<td class="LC_left_item">'.
 8914:                           '<span class="LC_nobreak">'.
 8915:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 8916:                           'value="'.$currval.'" size="10" />&nbsp;'.
 8917:                           $fieldtitles{$fields[$i]}.'</span></td>';
 8918:         }
 8919:         my $colsleft = $numperrow - $rem;
 8920:         if ($colsleft > 1 ) {
 8921:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8922:                          '&nbsp;</td>';
 8923:         } elsif ($colsleft == 1) {
 8924:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8925:         }
 8926:         $datatable .= '</tr></table></td></tr>';
 8927:         $$rowtotal ++;
 8928:     } elsif ($position eq 'middle') {
 8929:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 8930:         my @posstypes;
 8931:         if (ref($types) eq 'ARRAY') {
 8932:             @posstypes = @{$types};
 8933:         }
 8934:         unless (grep(/^default$/,@posstypes)) {
 8935:             push(@posstypes,'default');
 8936:         }
 8937:         my %usertypeshash;
 8938:         if (ref($usertypes) eq 'HASH') {
 8939:             %usertypeshash = %{$usertypes};
 8940:         }
 8941:         $usertypeshash{'default'} = $othertitle;
 8942:         foreach my $status (@posstypes) {
 8943:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 8944:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 8945:             $$rowtotal ++;
 8946:         }
 8947:     } else {
 8948:         my %choices = &Apache::lonlocal::texthash (
 8949:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 8950:                                                   );
 8951:         my @toggles = sort(keys(%choices));
 8952:         my %defaultchecked = (
 8953:                                'cancreate_email' => 'off',
 8954:                              );
 8955:         my $customclass = 'LC_selfcreate_email';
 8956:         my $classprefix = 'LC_canmodify_emailusername_';
 8957:         my $optionsprefix = 'LC_options_emailusername_';
 8958:         my $display = 'none';
 8959:         my $rowstyle = 'display:none';
 8960:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 8961:             $display = 'block';
 8962:             $rowstyle = 'display:table-row';
 8963:         }
 8964:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 8965:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 8966:                                                      \%choices,$$rowtotal,$onclick);
 8967:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 8968:                                          $rowstyle);
 8969:         $$rowtotal ++;
 8970:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 8971:                                       $rowstyle);
 8972:         $$rowtotal ++;
 8973:         my (@ordered,@posstypes,%usertypeshash);
 8974:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 8975:         my ($emailrules,$emailruleorder) =
 8976:             &Apache::lonnet::inst_userrules($dom,'email');
 8977:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8978:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8979:         if (ref($types) eq 'ARRAY') {
 8980:             @posstypes = @{$types};
 8981:         }
 8982:         if (@posstypes) {
 8983:             unless (grep(/^default$/,@posstypes)) {
 8984:                 push(@posstypes,'default');
 8985:             }
 8986:             if (ref($usertypes) eq 'HASH') {
 8987:                 %usertypeshash = %{$usertypes};
 8988:             }
 8989:             my $currassign;
 8990:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 8991:                 $currassign = {
 8992:                                   selfassign => $domdefaults{'inststatusguest'},
 8993:                               };
 8994:                 @ordered = @{$domdefaults{'inststatusguest'}};
 8995:             } else {
 8996:                 $currassign = { selfassign => [] };
 8997:             }
 8998:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 8999:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 9000:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 9001:                                          $numinrow,$othertitle,'selfassign',
 9002:                                          $rowtotal,$onclicktypes,$customclass,
 9003:                                          $rowstyle);
 9004:             $$rowtotal ++;
 9005:             $usertypeshash{'default'} = $othertitle;
 9006:             foreach my $status (@posstypes) {
 9007:                 my $css_class;
 9008:                 if ($$rowtotal%2) {
 9009:                     $css_class = 'LC_odd_row ';
 9010:                 }
 9011:                 $css_class .= $customclass;
 9012:                 my $rowid = $optionsprefix.$status;
 9013:                 my $hidden = 1;
 9014:                 my $currstyle = 'display:none';
 9015:                 if (grep(/^\Q$status\E$/,@ordered)) {
 9016:                     $currstyle = $rowstyle;
 9017:                     $hidden = 0; 
 9018:                 }
 9019:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9020:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 9021:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 9022:                 unless ($hidden) {
 9023:                     $$rowtotal ++;
 9024:                 }
 9025:             }
 9026:         } else {
 9027:             my $css_class;
 9028:             if ($$rowtotal%2) {
 9029:                 $css_class = 'LC_odd_row ';
 9030:             }
 9031:             $css_class .= $customclass;
 9032:             $usertypeshash{'default'} = $othertitle;
 9033:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9034:                                          $emailrules,$emailruleorder,$settings,'default','',
 9035:                                          $othertitle,$css_class,$rowstyle,$intdom);
 9036:             $$rowtotal ++;
 9037:         }
 9038:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 9039:         $numinrow = 1;
 9040:         if (@posstypes) {
 9041:             foreach my $status (@posstypes) {
 9042:                 my $rowid = $classprefix.$status;
 9043:                 my $datarowstyle = 'display:none';
 9044:                 if (grep(/^\Q$status\E$/,@ordered)) { 
 9045:                     $datarowstyle = $rowstyle; 
 9046:                 }
 9047:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 9048:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9049:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 9050:                 unless ($datarowstyle eq 'display:none') {
 9051:                     $$rowtotal ++;
 9052:                 }
 9053:             }
 9054:         } else {
 9055:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 9056:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9057:                                                    $infotitles,'',$customclass,$rowstyle);
 9058:         }
 9059:     }
 9060:     return $datatable;
 9061: }
 9062: 
 9063: sub selfcreate_javascript {
 9064:     return <<"ENDSCRIPT";
 9065: 
 9066: <script type="text/javascript">
 9067: // <![CDATA[
 9068: 
 9069: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 9070:     var x = document.getElementsByClassName(target);
 9071:     var insttypes = 0;
 9072:     var insttypeRegExp = new RegExp(prefix);
 9073:     if ((x.length != undefined) && (x.length > 0)) {
 9074:         if (form.elements[radio].length != undefined) {
 9075:             for (var i=0; i<form.elements[radio].length; i++) {
 9076:                 if (form.elements[radio][i].checked) {
 9077:                     if (form.elements[radio][i].value == 1) {
 9078:                         for (var j=0; j<x.length; j++) {
 9079:                             if (x[j].id == 'undefined') {
 9080:                                 x[j].style.display = 'table-row';
 9081:                             } else if (insttypeRegExp.test(x[j].id)) {
 9082:                                 insttypes ++;
 9083:                             } else {
 9084:                                 x[j].style.display = 'table-row';
 9085:                             }
 9086:                         }
 9087:                     } else {
 9088:                         for (var j=0; j<x.length; j++) {
 9089:                             x[j].style.display = 'none';
 9090:                         }
 9091:                     }
 9092:                     break;
 9093:                 }
 9094:             }
 9095:             if (insttypes > 0) {
 9096:                 toggleDataRow(form,checkbox,target,altprefix);
 9097:                 toggleDataRow(form,checkbox,target,prefix,1);
 9098:             }
 9099:         }
 9100:     }
 9101:     return;
 9102: }
 9103: 
 9104: function toggleDataRow(form,checkbox,target,prefix,docount) {
 9105:     if (form.elements[checkbox].length != undefined) {
 9106:         var count = 0;
 9107:         if (docount) {
 9108:             for (var i=0; i<form.elements[checkbox].length; i++) {
 9109:                 if (form.elements[checkbox][i].checked) {
 9110:                     count ++;
 9111:                 }
 9112:             }
 9113:         }
 9114:         for (var i=0; i<form.elements[checkbox].length; i++) {
 9115:             var type = form.elements[checkbox][i].value;
 9116:             if (document.getElementById(prefix+type)) {
 9117:                 if (form.elements[checkbox][i].checked) {
 9118:                     document.getElementById(prefix+type).style.display = 'table-row';
 9119:                     if (count % 2 == 1) {
 9120:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 9121:                     } else {
 9122:                         document.getElementById(prefix+type).className = target;
 9123:                     }
 9124:                     count ++;
 9125:                 } else {
 9126:                     document.getElementById(prefix+type).style.display = 'none';
 9127:                 }
 9128:             }
 9129:         }
 9130:     }
 9131:     return;
 9132: }
 9133: 
 9134: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 9135:     var caller = radio+'_'+status;
 9136:     if (form.elements[caller].length != undefined) {
 9137:         for (var i=0; i<form.elements[caller].length; i++) {
 9138:             if (form.elements[caller][i].checked) {
 9139:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 9140:                     var curr = form.elements[caller][i].value;
 9141:                     if (prefix) {
 9142:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 9143:                     }
 9144:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 9145:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 9146:                     if (curr == 'custom') {
 9147:                         if (prefix) { 
 9148:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 9149:                         }
 9150:                     } else if (curr == 'inst') {
 9151:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 9152:                     } else if (curr == 'noninst') {
 9153:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 9154:                     }
 9155:                     break;
 9156:                 }
 9157:             }
 9158:         }
 9159:     }
 9160: }
 9161: 
 9162: // ]]>
 9163: </script>
 9164: 
 9165: ENDSCRIPT
 9166: }
 9167: 
 9168: sub noninst_users {
 9169:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 9170:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
 9171:     my $class = 'LC_left_item';
 9172:     if ($css_class) {
 9173:         $css_class = ' class="'.$css_class.'"'; 
 9174:     }
 9175:     if ($rowid) {
 9176:         $rowid = ' id="'.$rowid.'"';
 9177:     }
 9178:     if ($rowstyle) {
 9179:         $rowstyle = ' style="'.$rowstyle.'"';
 9180:     }
 9181:     my ($output,$description);
 9182:     if ($type eq 'default') {
 9183:         $description = &mt('Requests for: [_1]',$typetitle);
 9184:     } else {
 9185:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 9186:     }
 9187:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 9188:               "<td>$description</td>\n".           
 9189:               '<td class="'.$class.'" colspan="2">'.
 9190:               '<table><tr>';
 9191:     my %headers = &Apache::lonlocal::texthash( 
 9192:               approve  => 'Processing',
 9193:               email    => 'E-mail',
 9194:               username => 'Username',
 9195:     );
 9196:     foreach my $item ('approve','email','username') {
 9197:         $output .= '<th>'.$headers{$item}.'</th>';
 9198:     }
 9199:     $output .= '</tr><tr>';
 9200:     foreach my $item ('approve','email','username') {
 9201:         $output .= '<td style="vertical-align: top">';
 9202:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 9203:         if ($item eq 'approve') {
 9204:             %choices = &Apache::lonlocal::texthash (
 9205:                                                      automatic => 'Automatically approved',
 9206:                                                      approval  => 'Queued for approval',
 9207:                                                    );
 9208:             @options = ('automatic','approval');
 9209:             $hashref = $processing;
 9210:             $defoption = 'automatic';
 9211:             $name = 'cancreate_emailprocess_'.$type;
 9212:         } elsif ($item eq 'email') {
 9213:             %choices = &Apache::lonlocal::texthash (
 9214:                                                      any     => 'Any e-mail',
 9215:                                                      inst    => 'Institutional only',
 9216:                                                      noninst => 'Non-institutional only',
 9217:                                                      custom  => 'Custom restrictions',
 9218:                                                    );
 9219:             @options = ('any','inst','noninst');
 9220:             my $showcustom;
 9221:             if (ref($emailrules) eq 'HASH') {
 9222:                 if (keys(%{$emailrules}) > 0) {
 9223:                     push(@options,'custom');
 9224:                     $showcustom = 'cancreate_emailrule';
 9225:                     if (ref($settings) eq 'HASH') {
 9226:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 9227:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 9228:                                 if (exists($emailrules->{$rule})) {
 9229:                                     $hascustom ++;
 9230:                                 }
 9231:                             }
 9232:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 9233:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 9234:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 9235:                                     if (exists($emailrules->{$rule})) {
 9236:                                         $hascustom ++;
 9237:                                     }
 9238:                                 }
 9239:                             }
 9240:                         }
 9241:                     }
 9242:                 }
 9243:             }
 9244:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 9245:                                                      "'cancreate_emaildomain','$type'".');"';
 9246:             $hashref = $emailoptions;
 9247:             $defoption = 'any';
 9248:             $name = 'cancreate_emailoptions_'.$type;
 9249:         } elsif ($item eq 'username') {
 9250:             %choices = &Apache::lonlocal::texthash (
 9251:                                                      all    => 'Same as e-mail',
 9252:                                                      first  => 'Omit @domain',
 9253:                                                      free   => 'Free to choose',
 9254:                                                    );
 9255:             @options = ('all','first','free');
 9256:             $hashref = $emailverified;
 9257:             $defoption = 'all';
 9258:             $name = 'cancreate_usernameoptions_'.$type;
 9259:         }
 9260:         foreach my $option (@options) {
 9261:             my $checked;
 9262:             if (ref($hashref) eq 'HASH') {
 9263:                 if ($type eq '') {
 9264:                     if (!exists($hashref->{'default'})) {
 9265:                         if ($option eq $defoption) {
 9266:                             $checked = ' checked="checked"';
 9267:                         }
 9268:                     } else {
 9269:                         if ($hashref->{'default'} eq $option) {
 9270:                             $checked = ' checked="checked"';
 9271:                         }
 9272:                     }
 9273:                 } else {
 9274:                     if (!exists($hashref->{$type})) {
 9275:                         if ($option eq $defoption) {
 9276:                             $checked = ' checked="checked"';
 9277:                         }
 9278:                     } else {
 9279:                         if ($hashref->{$type} eq $option) {
 9280:                             $checked = ' checked="checked"';
 9281:                         }
 9282:                     }
 9283:                 }
 9284:             } elsif (($item eq 'email') && ($hascustom)) {
 9285:                 if ($option eq 'custom') {
 9286:                     $checked = ' checked="checked"';
 9287:                 }
 9288:             } elsif ($option eq $defoption) {
 9289:                 $checked = ' checked="checked"';
 9290:             }
 9291:             $output .= '<span class="LC_nobreak"><label>'.
 9292:                        '<input type="radio" name="'.$name.'"'.
 9293:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 9294:                        $choices{$option}.'</label></span><br />';
 9295:             if ($item eq 'email') {
 9296:                 if ($option eq 'custom') {
 9297:                     my $id = 'cancreate_emailrule_'.$type;
 9298:                     my $display = 'none';
 9299:                     if ($checked) {
 9300:                         $display = 'inline';
 9301:                     }
 9302:                     my $numinrow = 2;
 9303:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 9304:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 9305:                                &user_formats_row('email',$settings,$emailrules,
 9306:                                                  $emailruleorder,$numinrow,'',$type);
 9307:                               '</table></fieldset>';
 9308:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 9309:                     my %text = &Apache::lonlocal::texthash (
 9310:                                                              inst    => 'must end:',
 9311:                                                              noninst => 'cannot end:',
 9312:                                                            );
 9313:                     my $value;
 9314:                     if (ref($emaildomain) eq 'HASH') {
 9315:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 9316:                             $value = $emaildomain->{$type}->{$option}; 
 9317:                         }
 9318:                     }
 9319:                     if ($value eq '') {
 9320:                         $value = '@'.$intdom;
 9321:                     }
 9322:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 9323:                     my $display = 'none';
 9324:                     if ($checked) {
 9325:                         $display = 'inline';
 9326:                     }
 9327:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 9328:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 9329:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 9330:                                '</div>';
 9331:                 }
 9332:             }
 9333:         }
 9334:         $output .= '</td>'."\n";
 9335:     }
 9336:     $output .= "</tr></table></td></tr>\n";
 9337:     return $output;
 9338: }
 9339: 
 9340: sub captcha_choice {
 9341:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 9342:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 9343:         $vertext,$currver);
 9344:     my %lt = &captcha_phrases();
 9345:     $keyentry = 'hidden';
 9346:     my $colspan=2;
 9347:     if ($context eq 'cancreate') {
 9348:         $rowname = &mt('CAPTCHA validation');
 9349:     } elsif ($context eq 'login') {
 9350:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 9351:     } elsif ($context eq 'passwords') {
 9352:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 9353:         $colspan=1;
 9354:     }
 9355:     if (ref($settings) eq 'HASH') {
 9356:         if ($settings->{'captcha'}) {
 9357:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 9358:         } else {
 9359:             $checked{'original'} = ' checked="checked"';
 9360:         }
 9361:         if ($settings->{'captcha'} eq 'recaptcha') {
 9362:             $pubtext = $lt{'pub'};
 9363:             $privtext = $lt{'priv'};
 9364:             $keyentry = 'text';
 9365:             $vertext = $lt{'ver'};
 9366:             $currver = $settings->{'recaptchaversion'};
 9367:             if ($currver ne '2') {
 9368:                 $currver = 1;
 9369:             }
 9370:         }
 9371:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 9372:             $currpub = $settings->{'recaptchakeys'}{'public'};
 9373:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 9374:         }
 9375:     } else {
 9376:         $checked{'original'} = ' checked="checked"';
 9377:     }
 9378:     my $css_class;
 9379:     if ($itemcount%2) {
 9380:         $css_class = 'LC_odd_row';
 9381:     }
 9382:     if ($customcss) {
 9383:         $css_class .= " $customcss";
 9384:     }
 9385:     $css_class =~ s/^\s+//;
 9386:     if ($css_class) {
 9387:         $css_class = ' class="'.$css_class.'"';
 9388:     }
 9389:     if ($rowstyle) {
 9390:         $css_class .= ' style="'.$rowstyle.'"';
 9391:     }
 9392:     my $output = '<tr'.$css_class.'>'.
 9393:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 9394:                  '<table><tr><td>'."\n";
 9395:     foreach my $option ('original','recaptcha','notused') {
 9396:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 9397:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 9398:                    $lt{$option}.'</label></span>';
 9399:         unless ($option eq 'notused') {
 9400:             $output .= ('&nbsp;'x2)."\n";
 9401:         }
 9402:     }
 9403: #
 9404: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 9405: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 9406: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 9407: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 9408: #
 9409:     $output .= '</td></tr>'."\n".
 9410:                '<tr><td class="LC_zero_height">'."\n".
 9411:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 9412:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 9413:                $currpub.'" size="40" /></span><br />'."\n".
 9414:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 9415:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 9416:                $currpriv.'" size="40" /></span><br />'.
 9417:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 9418:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 9419:                $currver.'" size="3" /></span><br />'.
 9420:                '</td></tr></table>'."\n".
 9421:                '</td></tr>';
 9422:     return $output;
 9423: }
 9424: 
 9425: sub user_formats_row {
 9426:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 9427:     my $output;
 9428:     my %text = (
 9429:                    'username' => 'new usernames',
 9430:                    'id'       => 'IDs',
 9431:                );
 9432:     unless ($type eq 'email') {
 9433:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 9434:         $output = '<tr '.$css_class.'>'.
 9435:                   '<td><span class="LC_nobreak">'.
 9436:                   &mt("Format rules to check for $text{$type}: ").
 9437:                   '</td><td class="LC_left_item" colspan="2"><table>';
 9438:     }
 9439:     my $rem;
 9440:     if (ref($ruleorder) eq 'ARRAY') {
 9441:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 9442:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 9443:                 my $rem = $i%($numinrow);
 9444:                 if ($rem == 0) {
 9445:                     if ($i > 0) {
 9446:                         $output .= '</tr>';
 9447:                     }
 9448:                     $output .= '<tr>';
 9449:                 }
 9450:                 my $check = ' ';
 9451:                 if (ref($settings) eq 'HASH') {
 9452:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 9453:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 9454:                             $check = ' checked="checked" ';
 9455:                         }
 9456:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 9457:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 9458:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 9459:                                 $check = ' checked="checked" ';
 9460:                             }
 9461:                         }
 9462:                     }
 9463:                 }
 9464:                 my $name = $type.'_rule';
 9465:                 if ($type eq 'email') {
 9466:                     $name .= '_'.$status;
 9467:                 }
 9468:                 $output .= '<td class="LC_left_item">'.
 9469:                            '<span class="LC_nobreak"><label>'.
 9470:                            '<input type="checkbox" name="'.$name.'" '.
 9471:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 9472:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 9473:             }
 9474:         }
 9475:         $rem = @{$ruleorder}%($numinrow);
 9476:     }
 9477:     my $colsleft;
 9478:     if ($rem) {
 9479:         $colsleft = $numinrow - $rem;
 9480:     }
 9481:     if ($colsleft > 1 ) {
 9482:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9483:                    '&nbsp;</td>';
 9484:     } elsif ($colsleft == 1) {
 9485:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9486:     }
 9487:     $output .= '</tr></table>';
 9488:     unless ($type eq 'email') {
 9489:         $output .= '</td></tr>';
 9490:     }
 9491:     return $output;
 9492: }
 9493: 
 9494: sub usercreation_types {
 9495:     my %lt = &Apache::lonlocal::texthash (
 9496:                     author     => 'When adding a co-author',
 9497:                     course     => 'When adding a user to a course',
 9498:                     requestcrs => 'When requesting a course',
 9499:                     any        => 'Any',
 9500:                     official   => 'Institutional only ',
 9501:                     unofficial => 'Non-institutional only',
 9502:                     none       => 'None',
 9503:     );
 9504:     return %lt;
 9505: }
 9506: 
 9507: sub selfcreation_types {
 9508:     my %lt = &Apache::lonlocal::texthash (
 9509:                     selfcreate => 'User creates own account',
 9510:                     any        => 'Any',
 9511:                     official   => 'Institutional only ',
 9512:                     unofficial => 'Non-institutional only',
 9513:                     email      => 'E-mail address',
 9514:                     login      => 'Institutional Login',
 9515:                     sso        => 'SSO',
 9516:              );
 9517: }
 9518: 
 9519: sub authtype_names {
 9520:     my %lt = &Apache::lonlocal::texthash(
 9521:                       int    => 'Internal',
 9522:                       krb4   => 'Kerberos 4',
 9523:                       krb5   => 'Kerberos 5',
 9524:                       loc    => 'Local',
 9525:                       lti    => 'LTI',
 9526:                   );
 9527:     return %lt;
 9528: }
 9529: 
 9530: sub context_names {
 9531:     my %context_title = &Apache::lonlocal::texthash(
 9532:        author => 'Creating users when an Author',
 9533:        course => 'Creating users when in a course',
 9534:        domain => 'Creating users when a Domain Coordinator',
 9535:     );
 9536:     return %context_title;
 9537: }
 9538: 
 9539: sub print_usermodification {
 9540:     my ($position,$dom,$settings,$rowtotal) = @_;
 9541:     my $numinrow = 4;
 9542:     my ($context,$datatable,$rowcount);
 9543:     if ($position eq 'top') {
 9544:         $rowcount = 0;
 9545:         $context = 'author'; 
 9546:         foreach my $role ('ca','aa') {
 9547:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9548:                                                    $numinrow,$rowcount);
 9549:             $$rowtotal ++;
 9550:             $rowcount ++;
 9551:         }
 9552:     } elsif ($position eq 'bottom') {
 9553:         $context = 'course';
 9554:         $rowcount = 0;
 9555:         foreach my $role ('st','ep','ta','in','cr') {
 9556:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9557:                                                    $numinrow,$rowcount);
 9558:             $$rowtotal ++;
 9559:             $rowcount ++;
 9560:         }
 9561:     }
 9562:     return $datatable;
 9563: }
 9564: 
 9565: sub print_defaults {
 9566:     my ($position,$dom,$settings,$rowtotal) = @_;
 9567:     my $rownum = 0;
 9568:     my ($datatable,$css_class,$titles);
 9569:     unless ($position eq 'bottom') {
 9570:         $titles = &defaults_titles($dom);
 9571:     }
 9572:     if ($position eq 'top') {
 9573:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 9574:                      'datelocale_def','portal_def');
 9575:         my %defaults;
 9576:         if (ref($settings) eq 'HASH') {
 9577:             %defaults = %{$settings};
 9578:         } else {
 9579:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9580:             foreach my $item (@items) {
 9581:                 $defaults{$item} = $domdefaults{$item};
 9582:             }
 9583:         }
 9584:         foreach my $item (@items) {
 9585:             if ($rownum%2) {
 9586:                 $css_class = '';
 9587:             } else {
 9588:                 $css_class = ' class="LC_odd_row" ';
 9589:             }
 9590:             $datatable .= '<tr'.$css_class.'>'.
 9591:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 9592:                           '</span></td><td class="LC_right_item" colspan="3">';
 9593:             if ($item eq 'auth_def') {
 9594:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
 9595:                 my %shortauth = (
 9596:                                  internal => 'int',
 9597:                                  krb4 => 'krb4',
 9598:                                  krb5 => 'krb5',
 9599:                                  localauth  => 'loc',
 9600:                                  lti => 'lti',
 9601:                                 );
 9602:                 my %authnames = &authtype_names();
 9603:                 foreach my $auth (@authtypes) {
 9604:                     my $checked = ' ';
 9605:                     if ($defaults{$item} eq $auth) {
 9606:                         $checked = ' checked="checked" ';
 9607:                     }
 9608:                     $datatable .= '<label><input type="radio" name="'.$item.
 9609:                                   '" value="'.$auth.'"'.$checked.'/>'.
 9610:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 9611:                 }
 9612:             } elsif ($item eq 'timezone_def') {
 9613:                 my $includeempty = 1;
 9614:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 9615:             } elsif ($item eq 'datelocale_def') {
 9616:                 my $includeempty = 1;
 9617:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 9618:             } elsif ($item eq 'lang_def') {
 9619:                 my $includeempty = 1;
 9620:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 9621:             } else {
 9622:                 my $size;
 9623:                 if ($item eq 'portal_def') {
 9624:                     $size = ' size="25"';
 9625:                 }
 9626:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 9627:                               $defaults{$item}.'"'.$size.' />';
 9628:             }
 9629:             $datatable .= '</td></tr>';
 9630:             $rownum ++;
 9631:         }
 9632:     } else {
 9633:         my %defaults;
 9634:         if (ref($settings) eq 'HASH') {
 9635:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9636:                 my $maxnum = @{$settings->{'inststatusorder'}};
 9637:                 for (my $i=0; $i<$maxnum; $i++) {
 9638:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 9639:                     my $item = $settings->{'inststatusorder'}->[$i];
 9640:                     my $title = $settings->{'inststatustypes'}->{$item};
 9641:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 9642:                     $datatable .= '<tr'.$css_class.'>'.
 9643:                                   '<td><span class="LC_nobreak">'.
 9644:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 9645:                     for (my $k=0; $k<=$maxnum; $k++) {
 9646:                         my $vpos = $k+1;
 9647:                         my $selstr;
 9648:                         if ($k == $i) {
 9649:                             $selstr = ' selected="selected" ';
 9650:                         }
 9651:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9652:                     }
 9653:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 9654:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 9655:                                   &mt('delete').'</span></td>'.
 9656:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 9657:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 9658:                                   '</span></td></tr>';
 9659:                 }
 9660:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 9661:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 9662:                 $datatable .= '<tr '.$css_class.'>'.
 9663:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 9664:                 for (my $k=0; $k<=$maxnum; $k++) {
 9665:                     my $vpos = $k+1;
 9666:                     my $selstr;
 9667:                     if ($k == $maxnum) {
 9668:                         $selstr = ' selected="selected" ';
 9669:                     }
 9670:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9671:                 }
 9672:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 9673:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 9674:                               '&nbsp;'.&mt('(new)').
 9675:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
 9676:                               &mt('Name displayed').':'.
 9677:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 9678:                               '</tr>'."\n";
 9679:                 $rownum ++;
 9680:             }
 9681:         }
 9682:     }
 9683:     $$rowtotal += $rownum;
 9684:     return $datatable;
 9685: }
 9686: 
 9687: sub get_languages_hash {
 9688:     my %langchoices;
 9689:     foreach my $id (&Apache::loncommon::languageids()) {
 9690:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 9691:         if ($code ne '') {
 9692:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 9693:         }
 9694:     }
 9695:     return %langchoices;
 9696: }
 9697: 
 9698: sub defaults_titles {
 9699:     my ($dom) = @_;
 9700:     my %titles = &Apache::lonlocal::texthash (
 9701:                    'auth_def'      => 'Default authentication type',
 9702:                    'auth_arg_def'  => 'Default authentication argument',
 9703:                    'lang_def'      => 'Default language',
 9704:                    'timezone_def'  => 'Default timezone',
 9705:                    'datelocale_def' => 'Default locale for dates',
 9706:                    'portal_def'     => 'Portal/Default URL',
 9707:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 9708:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 9709:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 9710:                  );
 9711:     if ($dom) {
 9712:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 9713:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 9714:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 9715:         $protocol = 'http' if ($protocol ne 'https');
 9716:         if ($uint_dom) {
 9717:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 9718:                                          $uint_dom);
 9719:         }
 9720:     }
 9721:     return (\%titles);
 9722: }
 9723: 
 9724: sub print_scantron {
 9725:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 9726:     if ($position eq 'top') {
 9727:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 9728:     } else {
 9729:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 9730:     }
 9731: }
 9732: 
 9733: sub scantron_javascript {
 9734:     return <<"ENDSCRIPT";
 9735: 
 9736: <script type="text/javascript">
 9737: // <![CDATA[
 9738: 
 9739: function toggleScantron(form) {
 9740:     var csvfieldset = new Array();
 9741:     if (document.getElementById('scantroncsv_cols')) {
 9742:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 9743:     }
 9744:     if (document.getElementById('scantroncsv_options')) {
 9745:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 9746:     }
 9747:     if (csvfieldset.length) {
 9748:         if (document.getElementById('scantronconfcsv')) {
 9749:             var scantroncsv = document.getElementById('scantronconfcsv');
 9750:             if (scantroncsv.checked) {
 9751:                 for (var i=0; i<csvfieldset.length; i++) {
 9752:                     csvfieldset[i].style.display = 'block';
 9753:                 }
 9754:             } else {
 9755:                 for (var i=0; i<csvfieldset.length; i++) {
 9756:                     csvfieldset[i].style.display = 'none';
 9757:                 }
 9758:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 9759:                 if (csvselects.length) {
 9760:                     for (var j=0; j<csvselects.length; j++) {
 9761:                         csvselects[j].selectedIndex = 0;
 9762:                     }
 9763:                 }
 9764:             }
 9765:         }
 9766:     }
 9767:     return;
 9768: }
 9769: // ]]>
 9770: </script>
 9771: 
 9772: ENDSCRIPT
 9773: 
 9774: }
 9775: 
 9776: sub print_scantronformat {
 9777:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 9778:     my $itemcount = 1;
 9779:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 9780:         %confhash);
 9781:     my $switchserver = &check_switchserver($dom,$confname);
 9782:     my %lt = &Apache::lonlocal::texthash (
 9783:                 default => 'Default bubblesheet format file error',
 9784:                 custom  => 'Custom bubblesheet format file error',
 9785:              );
 9786:     my %scantronfiles = (
 9787:         default => 'default.tab',
 9788:         custom => 'custom.tab',
 9789:     );
 9790:     foreach my $key (keys(%scantronfiles)) {
 9791:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 9792:                               .$scantronfiles{$key};
 9793:     }
 9794:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 9795:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 9796:         if (!$switchserver) {
 9797:             my $servadm = $r->dir_config('lonAdmEMail');
 9798:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 9799:             if ($configuserok eq 'ok') {
 9800:                 if ($author_ok eq 'ok') {
 9801:                     my %legacyfile = (
 9802:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 9803:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 9804:                     );
 9805:                     my %md5chk;
 9806:                     foreach my $type (keys(%legacyfile)) {
 9807:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 9808:                         chomp($md5chk{$type});
 9809:                     }
 9810:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 9811:                         foreach my $type (keys(%legacyfile)) {
 9812:                             ($scantronurls{$type},my $error) =
 9813:                                 &legacy_scantronformat($r,$dom,$confname,
 9814:                                                  $type,$legacyfile{$type},
 9815:                                                  $scantronurls{$type},
 9816:                                                  $scantronfiles{$type});
 9817:                             if ($error ne '') {
 9818:                                 $error{$type} = $error;
 9819:                             }
 9820:                         }
 9821:                         if (keys(%error) == 0) {
 9822:                             $is_custom = 1;
 9823:                             $confhash{'scantron'}{'scantronformat'} =
 9824:                                 $scantronurls{'custom'};
 9825:                             my $putresult =
 9826:                                 &Apache::lonnet::put_dom('configuration',
 9827:                                                          \%confhash,$dom);
 9828:                             if ($putresult ne 'ok') {
 9829:                                 $error{'custom'} =
 9830:                                     '<span class="LC_error">'.
 9831:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 9832:                             }
 9833:                         }
 9834:                     } else {
 9835:                         ($scantronurls{'default'},my $error) =
 9836:                             &legacy_scantronformat($r,$dom,$confname,
 9837:                                           'default',$legacyfile{'default'},
 9838:                                           $scantronurls{'default'},
 9839:                                           $scantronfiles{'default'});
 9840:                         if ($error eq '') {
 9841:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 9842:                             my $putresult =
 9843:                                 &Apache::lonnet::put_dom('configuration',
 9844:                                                          \%confhash,$dom);
 9845:                             if ($putresult ne 'ok') {
 9846:                                 $error{'default'} =
 9847:                                     '<span class="LC_error">'.
 9848:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 9849:                             }
 9850:                         } else {
 9851:                             $error{'default'} = $error;
 9852:                         }
 9853:                     }
 9854:                 }
 9855:             }
 9856:         } else {
 9857:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 9858:         }
 9859:     }
 9860:     if (ref($settings) eq 'HASH') {
 9861:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 9862:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 9863:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 9864:                 $scantronurl = '';
 9865:             } else {
 9866:                 $scantronurl = $settings->{'scantronformat'};
 9867:             }
 9868:             $is_custom = 1;
 9869:         } else {
 9870:             $scantronurl = $scantronurls{'default'};
 9871:         }
 9872:     } else {
 9873:         if ($is_custom) {
 9874:             $scantronurl = $scantronurls{'custom'};
 9875:         } else {
 9876:             $scantronurl = $scantronurls{'default'};
 9877:         }
 9878:     }
 9879:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9880:     $datatable .= '<tr'.$css_class.'>';
 9881:     if (!$is_custom) {
 9882:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 9883:                       '<span class="LC_nobreak">';
 9884:         if ($scantronurl) {
 9885:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 9886:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 9887:         } else {
 9888:             $datatable = &mt('File unavailable for display');
 9889:         }
 9890:         $datatable .= '</span></td>';
 9891:         if (keys(%error) == 0) { 
 9892:             $datatable .= '<td style="vertical-align: bottom">';
 9893:             if (!$switchserver) {
 9894:                 $datatable .= &mt('Upload:').'<br />';
 9895:             }
 9896:         } else {
 9897:             my $errorstr;
 9898:             foreach my $key (sort(keys(%error))) {
 9899:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 9900:             }
 9901:             $datatable .= '<td>'.$errorstr;
 9902:         }
 9903:     } else {
 9904:         if (keys(%error) > 0) {
 9905:             my $errorstr;
 9906:             foreach my $key (sort(keys(%error))) {
 9907:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 9908:             } 
 9909:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 9910:         } elsif ($scantronurl) {
 9911:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 9912:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 9913:             $datatable .= '<td><span class="LC_nobreak">'.
 9914:                           $link.
 9915:                           '<label><input type="checkbox" name="scantronformat_del"'.
 9916:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 9917:                           '<td><span class="LC_nobreak">&nbsp;'.
 9918:                           &mt('Replace:').'</span><br />';
 9919:         }
 9920:     }
 9921:     if (keys(%error) == 0) {
 9922:         if ($switchserver) {
 9923:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 9924:         } else {
 9925:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 9926:                          '<input type="file" name="scantronformat" /></span>';
 9927:         }
 9928:     }
 9929:     $datatable .= '</td></tr>';
 9930:     $$rowtotal ++;
 9931:     return $datatable;
 9932: }
 9933: 
 9934: sub legacy_scantronformat {
 9935:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 9936:     my ($url,$error);
 9937:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 9938:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 9939:         (my $result,$url) =
 9940:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 9941:                          '','',$newfile);
 9942:         if ($result ne 'ok') {
 9943:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 9944:         }
 9945:     }
 9946:     return ($url,$error);
 9947: }
 9948: 
 9949: sub print_scantronconfig {
 9950:     my ($dom,$settings,$rowtotal) = @_;
 9951:     my $itemcount = 2;
 9952:     my $is_checked = ' checked="checked"';
 9953:     my %optionson = (
 9954:                      hdr => ' checked="checked"',
 9955:                      pad => ' checked="checked"',
 9956:                      rem => ' checked="checked"',
 9957:                     );
 9958:     my %optionsoff = (
 9959:                       hdr => '',
 9960:                       pad => '',
 9961:                       rem => '',
 9962:                      );
 9963:     my $currcsvsty = 'none';
 9964:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 9965:     my @fields = &scantroncsv_fields();
 9966:     my %titles = &scantronconfig_titles();
 9967:     if (ref($settings) eq 'HASH') {
 9968:         if (ref($settings->{config}) eq 'HASH') {
 9969:             if ($settings->{config}->{dat}) {
 9970:                 $checked{'dat'} = $is_checked;
 9971:             }
 9972:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 9973:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 9974:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 9975:                     if (keys(%csvfields) > 0) {
 9976:                         $checked{'csv'} = $is_checked;
 9977:                         $currcsvsty = 'block';
 9978:                     }
 9979:                 }
 9980:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 9981:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 9982:                     foreach my $option (keys(%optionson)) {
 9983:                         unless ($csvoptions{$option}) {
 9984:                             $optionsoff{$option} = $optionson{$option};
 9985:                             $optionson{$option} = '';
 9986:                         }
 9987:                     }
 9988:                 }
 9989:             }
 9990:         } else {
 9991:             $checked{'dat'} = $is_checked;
 9992:         }
 9993:     } else {
 9994:         $checked{'dat'} = $is_checked;
 9995:     }
 9996:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 9997:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 9998:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 9999:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
10000:     foreach my $item ('dat','csv') {
10001:         my $id;
10002:         if ($item eq 'csv') {
10003:             $id = 'id="scantronconfcsv" ';
10004:         }
10005:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
10006:                       $titles{$item}.'</label>'.('&nbsp;'x3);
10007:         if ($item eq 'csv') {
10008:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
10009:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
10010:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
10011:             foreach my $col (@fields) {
10012:                 my $selnone;
10013:                 if ($csvfields{$col} eq '') {
10014:                     $selnone = ' selected="selected"';
10015:                 }
10016:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
10017:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
10018:                               '<option value=""'.$selnone.'></option>';
10019:                 for (my $i=0; $i<20; $i++) {
10020:                     my $shown = $i+1;
10021:                     my $sel;
10022:                     unless ($selnone) {
10023:                         if (exists($csvfields{$col})) {
10024:                             if ($csvfields{$col} == $i) {
10025:                                 $sel = ' selected="selected"';
10026:                             }
10027:                         }
10028:                     }
10029:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
10030:                 }
10031:                 $datatable .= '</select></td></tr>';
10032:            }
10033:            $datatable .= '</table></fieldset>'.
10034:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
10035:                          '<legend>'.&mt('CSV Options').'</legend>';
10036:            foreach my $option ('hdr','pad','rem') {
10037:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
10038:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
10039:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
10040:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
10041:            }
10042:            $datatable .= '</fieldset>';
10043:            $itemcount ++;
10044:         }
10045:     }
10046:     $datatable .= '</td></tr>';
10047:     $$rowtotal ++;
10048:     return $datatable;
10049: }
10050: 
10051: sub scantronconfig_titles {
10052:     return &Apache::lonlocal::texthash(
10053:                                           dat => 'Standard format (.dat)',
10054:                                           csv => 'Comma separated values (.csv)',
10055:                                           hdr => 'Remove first line in file (contains column titles)',
10056:                                           pad => 'Prepend 0s to PaperID',
10057:                                           rem => 'Remove leading spaces (except Question Response columns)',
10058:                                           CODE => 'CODE',
10059:                                           ID   => 'Student ID',
10060:                                           PaperID => 'Paper ID',
10061:                                           FirstName => 'First Name',
10062:                                           LastName => 'Last Name',
10063:                                           FirstQuestion => 'First Question Response',
10064:                                           Section => 'Section',
10065:     );
10066: }
10067: 
10068: sub scantroncsv_fields {
10069:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
10070: }
10071: 
10072: sub print_coursecategories {
10073:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
10074:     my $datatable;
10075:     if ($position eq 'top') {
10076:         my (%checked);
10077:         my @catitems = ('unauth','auth');
10078:         my @cattypes = ('std','domonly','codesrch','none');
10079:         $checked{'unauth'} = 'std';
10080:         $checked{'auth'} = 'std';
10081:         if (ref($settings) eq 'HASH') {
10082:             foreach my $type (@cattypes) {
10083:                 if ($type eq $settings->{'unauth'}) {
10084:                     $checked{'unauth'} = $type;
10085:                 }
10086:                 if ($type eq $settings->{'auth'}) {
10087:                     $checked{'auth'} = $type;
10088:                 }
10089:             }
10090:         }
10091:         my %lt = &Apache::lonlocal::texthash (
10092:                                                unauth   => 'Catalog type for unauthenticated users',
10093:                                                auth     => 'Catalog type for authenticated users',
10094:                                                none     => 'No catalog',
10095:                                                std      => 'Standard catalog',
10096:                                                domonly  => 'Domain-only catalog',
10097:                                                codesrch => "Code search form",
10098:                                              );
10099:        my $itemcount = 0;
10100:        foreach my $item (@catitems) {
10101:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10102:            $datatable .= '<tr '.$css_class.'>'.
10103:                          '<td>'.$lt{$item}.'</td>'.
10104:                          '<td class="LC_right_item"><span class="LC_nobreak">';
10105:            foreach my $type (@cattypes) {
10106:                my $ischecked;
10107:                if ($checked{$item} eq $type) {
10108:                    $ischecked=' checked="checked"';
10109:                }
10110:                $datatable .= '<label>'.
10111:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
10112:                              ' />'.$lt{$type}.'</label>&nbsp;';
10113:            }
10114:            $datatable .= '</span></td></tr>';
10115:            $itemcount ++;
10116:         }
10117:         $$rowtotal += $itemcount;
10118:     } elsif ($position eq 'middle') {
10119:         my $toggle_cats_crs = ' ';
10120:         my $toggle_cats_dom = ' checked="checked" ';
10121:         my $can_cat_crs = ' ';
10122:         my $can_cat_dom = ' checked="checked" ';
10123:         my $toggle_catscomm_comm = ' ';
10124:         my $toggle_catscomm_dom = ' checked="checked" ';
10125:         my $can_catcomm_comm = ' ';
10126:         my $can_catcomm_dom = ' checked="checked" ';
10127:         my $toggle_catsplace_place = ' ';
10128:         my $toggle_catsplace_dom = ' checked="checked" ';
10129:         my $can_catplace_place = ' ';
10130:         my $can_catplace_dom = ' checked="checked" ';
10131: 
10132:         if (ref($settings) eq 'HASH') {
10133:             if ($settings->{'togglecats'} eq 'crs') {
10134:                 $toggle_cats_crs = $toggle_cats_dom;
10135:                 $toggle_cats_dom = ' ';
10136:             }
10137:             if ($settings->{'categorize'} eq 'crs') {
10138:                 $can_cat_crs = $can_cat_dom;
10139:                 $can_cat_dom = ' ';
10140:             }
10141:             if ($settings->{'togglecatscomm'} eq 'comm') {
10142:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
10143:                 $toggle_catscomm_dom = ' ';
10144:             }
10145:             if ($settings->{'categorizecomm'} eq 'comm') {
10146:                 $can_catcomm_comm = $can_catcomm_dom;
10147:                 $can_catcomm_dom = ' ';
10148:             }
10149:             if ($settings->{'togglecatsplace'} eq 'place') {
10150:                 $toggle_catsplace_place = $toggle_catsplace_dom;
10151:                 $toggle_catsplace_dom = ' ';
10152:             }
10153:             if ($settings->{'categorizeplace'} eq 'place') {
10154:                 $can_catplace_place = $can_catplace_dom;
10155:                 $can_catplace_dom = ' ';
10156:             }
10157:         }
10158:         my %title = &Apache::lonlocal::texthash (
10159:                      togglecats      => 'Show/Hide a course in catalog',
10160:                      togglecatscomm  => 'Show/Hide a community in catalog',
10161:                      togglecatsplace => 'Show/Hide a placement test in catalog',
10162:                      categorize      => 'Assign a category to a course',
10163:                      categorizecomm  => 'Assign a category to a community',
10164:                      categorizeplace => 'Assign a category to a placement test',
10165:                     );
10166:         my %level = &Apache::lonlocal::texthash (
10167:                      dom   => 'Set in Domain',
10168:                      crs   => 'Set in Course',
10169:                      comm  => 'Set in Community',
10170:                      place => 'Set in Placement Test',
10171:                     );
10172:         $datatable = '<tr class="LC_odd_row">'.
10173:                   '<td>'.$title{'togglecats'}.'</td>'.
10174:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10175:                   '<input type="radio" name="togglecats"'.
10176:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10177:                   '<label><input type="radio" name="togglecats"'.
10178:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
10179:                   '</tr><tr>'.
10180:                   '<td>'.$title{'categorize'}.'</td>'.
10181:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10182:                   '<label><input type="radio" name="categorize"'.
10183:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10184:                   '<label><input type="radio" name="categorize"'.
10185:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
10186:                   '</tr><tr class="LC_odd_row">'.
10187:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
10188:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10189:                   '<input type="radio" name="togglecatscomm"'.
10190:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10191:                   '<label><input type="radio" name="togglecatscomm"'.
10192:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
10193:                   '</tr><tr>'.
10194:                   '<td>'.$title{'categorizecomm'}.'</td>'.
10195:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10196:                   '<label><input type="radio" name="categorizecomm"'.
10197:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10198:                   '<label><input type="radio" name="categorizecomm"'.
10199:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
10200:                   '</tr><tr class="LC_odd_row">'.
10201:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
10202:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10203:                   '<input type="radio" name="togglecatsplace"'.
10204:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10205:                   '<label><input type="radio" name="togglecatscomm"'.
10206:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
10207:                   '</tr><tr>'.
10208:                   '<td>'.$title{'categorizeplace'}.'</td>'.
10209:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10210:                   '<label><input type="radio" name="categorizeplace"'.
10211:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10212:                   '<label><input type="radio" name="categorizeplace"'.
10213:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
10214:                   '</tr>';
10215:         $$rowtotal += 6;
10216:     } else {
10217:         my $css_class;
10218:         my $itemcount = 1;
10219:         my $cathash; 
10220:         if (ref($settings) eq 'HASH') {
10221:             $cathash = $settings->{'cats'};
10222:         }
10223:         if (ref($cathash) eq 'HASH') {
10224:             my (@cats,@trails,%allitems,%idx,@jsarray);
10225:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
10226:                                                    \%allitems,\%idx,\@jsarray);
10227:             my $maxdepth = scalar(@cats);
10228:             my $colattrib = '';
10229:             if ($maxdepth > 2) {
10230:                 $colattrib = ' colspan="2" ';
10231:             }
10232:             my @path;
10233:             if (@cats > 0) {
10234:                 if (ref($cats[0]) eq 'ARRAY') {
10235:                     my $numtop = @{$cats[0]};
10236:                     my $maxnum = $numtop;
10237:                     my %default_names = (
10238:                           instcode    => &mt('Official courses'),
10239:                           communities => &mt('Communities'),
10240:                           placement   => &mt('Placement Tests'),
10241:                     );
10242: 
10243:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
10244:                         ($cathash->{'instcode::0'} eq '') ||
10245:                         (!grep(/^communities$/,@{$cats[0]})) || 
10246:                         ($cathash->{'communities::0'} eq '') ||
10247:                         (!grep(/^placement$/,@{$cats[0]})) ||
10248:                         ($cathash->{'placement::0'} eq '')) {
10249:                         $maxnum ++;
10250:                     }
10251:                     my $lastidx;
10252:                     for (my $i=0; $i<$numtop; $i++) {
10253:                         my $parent = $cats[0][$i];
10254:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10255:                         my $item = &escape($parent).'::0';
10256:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
10257:                         $lastidx = $idx{$item};
10258:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10259:                                       .'<select name="'.$item.'"'.$chgstr.'>';
10260:                         for (my $k=0; $k<=$maxnum; $k++) {
10261:                             my $vpos = $k+1;
10262:                             my $selstr;
10263:                             if ($k == $i) {
10264:                                 $selstr = ' selected="selected" ';
10265:                             }
10266:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10267:                         }
10268:                         $datatable .= '</select></span></td><td>';
10269:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
10270:                             $datatable .=  '<span class="LC_nobreak">'
10271:                                            .$default_names{$parent}.'</span>';
10272:                             if ($parent eq 'instcode') {
10273:                                 $datatable .= '<br /><span class="LC_nobreak">('
10274:                                               .&mt('with institutional codes')
10275:                                               .')</span></td><td'.$colattrib.'>';
10276:                             } else {
10277:                                 $datatable .= '<table><tr><td>';
10278:                             }
10279:                             $datatable .= '<span class="LC_nobreak">'
10280:                                           .'<label><input type="radio" name="'
10281:                                           .$parent.'" value="1" checked="checked" />'
10282:                                           .&mt('Display').'</label>';
10283:                             if ($parent eq 'instcode') {
10284:                                 $datatable .= '&nbsp;';
10285:                             } else {
10286:                                 $datatable .= '</span></td></tr><tr><td>'
10287:                                               .'<span class="LC_nobreak">';
10288:                             }
10289:                             $datatable .= '<label><input type="radio" name="'
10290:                                           .$parent.'" value="0" />'
10291:                                           .&mt('Do not display').'</label></span>';
10292:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
10293:                                 $datatable .= '</td></tr></table>';
10294:                             }
10295:                             $datatable .= '</td>';
10296:                         } else {
10297:                             $datatable .= $parent
10298:                                           .'&nbsp;<span class="LC_nobreak"><label>'
10299:                                           .'<input type="checkbox" name="deletecategory" '
10300:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
10301:                         }
10302:                         my $depth = 1;
10303:                         push(@path,$parent);
10304:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
10305:                         pop(@path);
10306:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10307:                         $itemcount ++;
10308:                     }
10309:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10310:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
10311:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
10312:                     for (my $k=0; $k<=$maxnum; $k++) {
10313:                         my $vpos = $k+1;
10314:                         my $selstr;
10315:                         if ($k == $numtop) {
10316:                             $selstr = ' selected="selected" ';
10317:                         }
10318:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10319:                     }
10320:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
10321:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
10322:                                   .'</tr>'."\n";
10323:                     $itemcount ++;
10324:                     foreach my $default ('instcode','communities','placement') {
10325:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
10326:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
10327:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
10328:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
10329:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
10330:                             for (my $k=0; $k<=$maxnum; $k++) {
10331:                                 my $vpos = $k+1;
10332:                                 my $selstr;
10333:                                 if ($k == $maxnum) {
10334:                                     $selstr = ' selected="selected" ';
10335:                                 }
10336:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10337:                             }
10338:                             $datatable .= '</select></span></td>'.
10339:                                           '<td><span class="LC_nobreak">'.
10340:                                           $default_names{$default}.'</span>';
10341:                             if ($default eq 'instcode') {
10342:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
10343:                                               .&mt('with institutional codes').')</span>';
10344:                             }
10345:                             $datatable .= '</td>'
10346:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
10347:                                           .&mt('Display').'</label>&nbsp;'
10348:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
10349:                                           .&mt('Do not display').'</label></span></td></tr>';
10350:                         }
10351:                     }
10352:                 }
10353:             } else {
10354:                 $datatable .= &initialize_categories($itemcount);
10355:             }
10356:         } else {
10357:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
10358:                           .&initialize_categories($itemcount);
10359:         }
10360:         $$rowtotal += $itemcount;
10361:     }
10362:     return $datatable;
10363: }
10364: 
10365: sub print_serverstatuses {
10366:     my ($dom,$settings,$rowtotal) = @_;
10367:     my $datatable;
10368:     my @pages = &serverstatus_pages();
10369:     my (%namedaccess,%machineaccess);
10370:     foreach my $type (@pages) {
10371:         $namedaccess{$type} = '';
10372:         $machineaccess{$type}= '';
10373:     }
10374:     if (ref($settings) eq 'HASH') {
10375:         foreach my $type (@pages) {
10376:             if (exists($settings->{$type})) {
10377:                 if (ref($settings->{$type}) eq 'HASH') {
10378:                     foreach my $key (keys(%{$settings->{$type}})) {
10379:                         if ($key eq 'namedusers') {
10380:                             $namedaccess{$type} = $settings->{$type}->{$key};
10381:                         } elsif ($key eq 'machines') {
10382:                             $machineaccess{$type} = $settings->{$type}->{$key};
10383:                         }
10384:                     }
10385:                 }
10386:             }
10387:         }
10388:     }
10389:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
10390:     my $rownum = 0;
10391:     my $css_class;
10392:     foreach my $type (@pages) {
10393:         $rownum ++;
10394:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10395:         $datatable .= '<tr'.$css_class.'>'.
10396:                       '<td><span class="LC_nobreak">'.
10397:                       $titles->{$type}.'</span></td>'.
10398:                       '<td class="LC_left_item">'.
10399:                       '<input type="text" name="'.$type.'_namedusers" '.
10400:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
10401:                       '<td class="LC_right_item">'.
10402:                       '<span class="LC_nobreak">'.
10403:                       '<input type="text" name="'.$type.'_machines" '.
10404:                       'value="'.$machineaccess{$type}.'" size="10" />'.
10405:                       '</span></td></tr>'."\n";
10406:     }
10407:     $$rowtotal += $rownum;
10408:     return $datatable;
10409: }
10410: 
10411: sub serverstatus_pages {
10412:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
10413:             'checksums','clusterstatus','certstatus','metadata_keywords',
10414:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
10415:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
10416: }
10417: 
10418: sub defaults_javascript {
10419:     my ($settings) = @_;
10420:     return unless (ref($settings) eq 'HASH');
10421:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10422:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
10423:         if ($maxnum eq '') {
10424:             $maxnum = 0;
10425:         }
10426:         $maxnum ++;
10427:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
10428:         return <<"ENDSCRIPT";
10429: <script type="text/javascript">
10430: // <![CDATA[
10431: function reorderTypes(form,caller) {
10432:     var changedVal;
10433: $jstext 
10434:     var newpos = 'addinststatus_pos';
10435:     var current = new Array;
10436:     var maxh = $maxnum;
10437:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10438:     var oldVal;
10439:     if (caller == newpos) {
10440:         changedVal = newitemVal;
10441:     } else {
10442:         var curritem = 'inststatus_pos_'+caller;
10443:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
10444:         current[newitemVal] = newpos;
10445:     }
10446:     for (var i=0; i<inststatuses.length; i++) {
10447:         if (inststatuses[i] != caller) {
10448:             var elementName = 'inststatus_pos_'+inststatuses[i];
10449:             if (form.elements[elementName]) {
10450:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10451:                 current[currVal] = elementName;
10452:             }
10453:         }
10454:     }
10455:     for (var j=0; j<maxh; j++) {
10456:         if (current[j] == undefined) {
10457:             oldVal = j;
10458:         }
10459:     }
10460:     if (oldVal < changedVal) {
10461:         for (var k=oldVal+1; k<=changedVal ; k++) {
10462:            var elementName = current[k];
10463:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10464:         }
10465:     } else {
10466:         for (var k=changedVal; k<oldVal; k++) {
10467:             var elementName = current[k];
10468:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10469:         }
10470:     }
10471:     return;
10472: }
10473: 
10474: // ]]>
10475: </script>
10476: 
10477: ENDSCRIPT
10478:     }
10479:     return;
10480: }
10481: 
10482: sub passwords_javascript {
10483:     my %intalert = &Apache::lonlocal::texthash (
10484:         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.',
10485:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
10486:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
10487:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
10488:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
10489:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
10490:     );
10491:     &js_escape(\%intalert);
10492:     my $defmin = $Apache::lonnet::passwdmin;
10493:     my $intauthjs = <<"ENDSCRIPT";
10494: 
10495: function warnIntAuth(field) {
10496:     if (field.name == 'intauth_check') {
10497:         if (field.value == '2') {
10498:             alert('$intalert{authcheck}');
10499:         }
10500:     }
10501:     if (field.name == 'intauth_cost') {
10502:         field.value.replace(/\s/g,'');
10503:         if (field.value != '') {
10504:             var regexdigit=/^\\d+\$/;
10505:             if (!regexdigit.test(field.value)) {
10506:                 alert('$intalert{authcost}');
10507:             }
10508:         }
10509:     }
10510:     return;
10511: }
10512: 
10513: function warnIntPass(field) {
10514:     field.value.replace(/^\s+/,'');
10515:     field.value.replace(/\s+\$/,'');
10516:     var regexdigit=/^\\d+\$/;
10517:     if (field.name == 'passwords_min') {
10518:         if (field.value == '') {
10519:             alert('$intalert{passmin}');
10520:             field.value = '$defmin';
10521:         } else {
10522:             if (!regexdigit.test(field.value)) {
10523:                 alert('$intalert{passmin}');
10524:                 field.value = '$defmin';
10525:             }
10526:             var minval = parseInt(field.value,10);
10527:             if (minval < $defmin) {
10528:                 alert('$intalert{passmin}');
10529:                 field.value = '$defmin';
10530:             }
10531:         }
10532:     } else {
10533:         if (field.value == '0') {
10534:             field.value = '';
10535:         }
10536:         if (field.value != '') {
10537:             if (field.name == 'passwords_expire') {
10538:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
10539:                 if (!regexpposnum.test(field.value)) {
10540:                     alert('$intalert{passexp}');
10541:                     field.value = '';
10542:                 } else {
10543:                     var expval = parseFloat(field.value);
10544:                     if (expval == 0) {
10545:                         alert('$intalert{passexp}');
10546:                         field.value = '';
10547:                     }
10548:                 }
10549:             } else {
10550:                 if (!regexdigit.test(field.value)) {
10551:                     if (field.name == 'passwords_max') {
10552:                         alert('$intalert{passmax}');
10553:                     } else {
10554:                         if (field.name == 'passwords_numsaved') {
10555:                             alert('$intalert{passnum}');
10556:                         }
10557:                     }
10558:                     field.value = '';
10559:                 }
10560:             }
10561:         }
10562:     }
10563:     return;
10564: }
10565: 
10566: ENDSCRIPT
10567:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
10568: }
10569: 
10570: sub coursecategories_javascript {
10571:     my ($settings) = @_;
10572:     my ($output,$jstext,$cathash);
10573:     if (ref($settings) eq 'HASH') {
10574:         $cathash = $settings->{'cats'};
10575:     }
10576:     if (ref($cathash) eq 'HASH') {
10577:         my (@cats,@jsarray,%idx);
10578:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
10579:         if (@jsarray > 0) {
10580:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
10581:             for (my $i=0; $i<@jsarray; $i++) {
10582:                 if (ref($jsarray[$i]) eq 'ARRAY') {
10583:                     my $catstr = join('","',@{$jsarray[$i]});
10584:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
10585:                 }
10586:             }
10587:         }
10588:     } else {
10589:         $jstext  = '    var categories = Array(1);'."\n".
10590:                    '    categories[0] = Array("instcode_pos");'."\n"; 
10591:     }
10592:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
10593:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
10594:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
10595:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
10596:     &js_escape(\$instcode_reserved);
10597:     &js_escape(\$communities_reserved);
10598:     &js_escape(\$placement_reserved);
10599:     &js_escape(\$choose_again);
10600:     $output = <<"ENDSCRIPT";
10601: <script type="text/javascript">
10602: // <![CDATA[
10603: function reorderCats(form,parent,item,idx) {
10604:     var changedVal;
10605: $jstext
10606:     var newpos = 'addcategory_pos';
10607:     if (parent == '') {
10608:         var has_instcode = 0;
10609:         var maxtop = categories[idx].length;
10610:         for (var j=0; j<maxtop; j++) {
10611:             if (categories[idx][j] == 'instcode::0') {
10612:                 has_instcode == 1;
10613:             }
10614:         }
10615:         if (has_instcode == 0) {
10616:             categories[idx][maxtop] = 'instcode_pos';
10617:         }
10618:     } else {
10619:         newpos += '_'+parent;
10620:     }
10621:     var maxh = 1 + categories[idx].length;
10622:     var current = new Array;
10623:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10624:     if (item == newpos) {
10625:         changedVal = newitemVal;
10626:     } else {
10627:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
10628:         current[newitemVal] = newpos;
10629:     }
10630:     for (var i=0; i<categories[idx].length; i++) {
10631:         var elementName = categories[idx][i];
10632:         if (elementName != item) {
10633:             if (form.elements[elementName]) {
10634:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10635:                 current[currVal] = elementName;
10636:             }
10637:         }
10638:     }
10639:     var oldVal;
10640:     for (var j=0; j<maxh; j++) {
10641:         if (current[j] == undefined) {
10642:             oldVal = j;
10643:         }
10644:     }
10645:     if (oldVal < changedVal) {
10646:         for (var k=oldVal+1; k<=changedVal ; k++) {
10647:            var elementName = current[k];
10648:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10649:         }
10650:     } else {
10651:         for (var k=changedVal; k<oldVal; k++) {
10652:             var elementName = current[k];
10653:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10654:         }
10655:     }
10656:     return;
10657: }
10658: 
10659: function categoryCheck(form) {
10660:     if (form.elements['addcategory_name'].value == 'instcode') {
10661:         alert('$instcode_reserved\\n$choose_again');
10662:         return false;
10663:     }
10664:     if (form.elements['addcategory_name'].value == 'communities') {
10665:         alert('$communities_reserved\\n$choose_again');
10666:         return false;
10667:     }
10668:     if (form.elements['addcategory_name'].value == 'placement') {
10669:         alert('$placement_reserved\\n$choose_again');
10670:         return false;
10671:     }
10672:     return true;
10673: }
10674: 
10675: // ]]>
10676: </script>
10677: 
10678: ENDSCRIPT
10679:     return $output;
10680: }
10681: 
10682: sub initialize_categories {
10683:     my ($itemcount) = @_;
10684:     my ($datatable,$css_class,$chgstr);
10685:     my %default_names = &Apache::lonlocal::texthash (
10686:                       instcode    => 'Official courses (with institutional codes)',
10687:                       communities => 'Communities',
10688:                       placement   => 'Placement Tests',
10689:                         );
10690:     my %selnum = (
10691:                    instcode    => '0',
10692:                    communities => '1',
10693:                    placement   => '2',
10694:                  );
10695:     my %selected;
10696:     foreach my $default ('instcode','communities','placement') {
10697:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10698:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
10699:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
10700:         $selected{$selnum{$default}} = ' selected="selected"';
10701:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10702:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
10703:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
10704:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
10705:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
10706:                      .'<option value="3">4</option></select>&nbsp;'
10707:                      .$default_names{$default}
10708:                      .'</span></td><td><span class="LC_nobreak">'
10709:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
10710:                      .&mt('Display').'</label>&nbsp;<label>'
10711:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
10712:                  .'</label></span></td></tr>';
10713:         $itemcount ++;
10714:     }
10715:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10716:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
10717:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10718:                   .'<select name="addcategory_pos"'.$chgstr.'>'
10719:                   .'<option value="0">1</option>'
10720:                   .'<option value="1">2</option>'
10721:                   .'<option value="2">3</option>'
10722:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
10723:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
10724:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
10725:                   .'</td></tr>';
10726:     return $datatable;
10727: }
10728: 
10729: sub build_category_rows {
10730:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
10731:     my ($text,$name,$item,$chgstr);
10732:     if (ref($cats) eq 'ARRAY') {
10733:         my $maxdepth = scalar(@{$cats});
10734:         if (ref($cats->[$depth]) eq 'HASH') {
10735:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10736:                 my $numchildren = @{$cats->[$depth]{$parent}};
10737:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10738:                 $text .= '<td><table class="LC_data_table">';
10739:                 my ($idxnum,$parent_name,$parent_item);
10740:                 my $higher = $depth - 1;
10741:                 if ($higher == 0) {
10742:                     $parent_name = &escape($parent).'::'.$higher;
10743:                 } else {
10744:                     if (ref($path) eq 'ARRAY') {
10745:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10746:                     }
10747:                 }
10748:                 $parent_item = 'addcategory_pos_'.$parent_name;
10749:                 for (my $j=0; $j<=$numchildren; $j++) {
10750:                     if ($j < $numchildren) {
10751:                         $name = $cats->[$depth]{$parent}[$j];
10752:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
10753:                         $idxnum = $idx->{$item};
10754:                     } else {
10755:                         $name = $parent_name;
10756:                         $item = $parent_item;
10757:                     }
10758:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
10759:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
10760:                     for (my $i=0; $i<=$numchildren; $i++) {
10761:                         my $vpos = $i+1;
10762:                         my $selstr;
10763:                         if ($j == $i) {
10764:                             $selstr = ' selected="selected" ';
10765:                         }
10766:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
10767:                     }
10768:                     $text .= '</select>&nbsp;';
10769:                     if ($j < $numchildren) {
10770:                         my $deeper = $depth+1;
10771:                         $text .= $name.'&nbsp;'
10772:                                  .'<label><input type="checkbox" name="deletecategory" value="'
10773:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
10774:                         if(ref($path) eq 'ARRAY') {
10775:                             push(@{$path},$name);
10776:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
10777:                             pop(@{$path});
10778:                         }
10779:                     } else {
10780:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
10781:                         if ($j == $numchildren) {
10782:                             $text .= $name;
10783:                         } else {
10784:                             $text .= $item;
10785:                         }
10786:                         $text .= '" value="" />';
10787:                     }
10788:                     $text .= '</td></tr>';
10789:                 }
10790:                 $text .= '</table></td>';
10791:             } else {
10792:                 my $higher = $depth-1;
10793:                 if ($higher == 0) {
10794:                     $name = &escape($parent).'::'.$higher;
10795:                 } else {
10796:                     if (ref($path) eq 'ARRAY') {
10797:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10798:                     }
10799:                 }
10800:                 my $colspan;
10801:                 if ($parent ne 'instcode') {
10802:                     $colspan = $maxdepth - $depth - 1;
10803:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
10804:                 }
10805:             }
10806:         }
10807:     }
10808:     return $text;
10809: }
10810: 
10811: sub modifiable_userdata_row {
10812:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
10813:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
10814:     my ($role,$rolename,$statustype);
10815:     $role = $item;
10816:     if ($context eq 'cancreate') {
10817:         if ($item =~ /^(emailusername)_(.+)$/) {
10818:             $role = $1;
10819:             $statustype = $2;
10820:             if (ref($usertypes) eq 'HASH') {
10821:                 if ($usertypes->{$statustype}) {
10822:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
10823:                 } else {
10824:                     $rolename = &mt('Data provided by user');
10825:                 }
10826:             }
10827:         }
10828:     } elsif ($context eq 'selfcreate') {
10829:         if (ref($usertypes) eq 'HASH') {
10830:             $rolename = $usertypes->{$role};
10831:         } else {
10832:             $rolename = $role;
10833:         }
10834:     } elsif ($context eq 'lti') {
10835:         $rolename = &mt('Institutional data used (if available)');
10836:     } elsif ($context eq 'privacy') {
10837:         $rolename = $itemdesc;
10838:     } else {
10839:         if ($role eq 'cr') {
10840:             $rolename = &mt('Custom role');
10841:         } else {
10842:             $rolename = &Apache::lonnet::plaintext($role);
10843:         }
10844:     }
10845:     my (@fields,%fieldtitles);
10846:     if (ref($fieldsref) eq 'ARRAY') {
10847:         @fields = @{$fieldsref};
10848:     } else {
10849:         @fields = ('lastname','firstname','middlename','generation',
10850:                    'permanentemail','id');
10851:     }
10852:     if ((ref($titlesref) eq 'HASH')) {
10853:         %fieldtitles = %{$titlesref};
10854:     } else {
10855:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10856:     }
10857:     my $output;
10858:     my $css_class;
10859:     if ($rowcount%2) {
10860:         $css_class = 'LC_odd_row';
10861:     }
10862:     if ($customcss) {
10863:         $css_class .= " $customcss";
10864:     }
10865:     $css_class =~ s/^\s+//;
10866:     if ($css_class) {
10867:         $css_class = ' class="'.$css_class.'"';
10868:     }
10869:     if ($rowstyle) {
10870:         $css_class .= ' style="'.$rowstyle.'"';
10871:     }
10872:     if ($rowid) {
10873:         $rowid = ' id="'.$rowid.'"';
10874:     }
10875:     $output = '<tr '.$css_class.$rowid.'>'.
10876:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
10877:               '<td class="LC_left_item" colspan="2"><table>';
10878:     my $rem;
10879:     my %checks;
10880:     my %current;
10881:     if (ref($settings) eq 'HASH') {
10882:         my $hashref;
10883:         if ($context eq 'lti') {
10884:             if (ref($settings) eq 'HASH') {
10885:                 $hashref = $settings->{'instdata'};
10886:             }
10887:         } elsif ($context eq 'privacy') {
10888:             my ($key,$inner) = split(/_/,$role);
10889:             if (ref($settings) eq 'HASH') {
10890:                 if (ref($settings->{$key}) eq 'HASH') {
10891:                     $hashref = $settings->{$key}->{$inner};
10892:                 }
10893:             }
10894:         } elsif (ref($settings->{$context}) eq 'HASH') {
10895:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
10896:                 $hashref = $settings->{'lti_instdata'};
10897:             }
10898:             if ($role eq 'emailusername') {
10899:                 if ($statustype) {
10900:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
10901:                         $hashref = $settings->{$context}->{$role}->{$statustype};
10902:                     }
10903:                 }
10904:             }
10905:         }
10906:         if (ref($hashref) eq 'HASH') { 
10907:             foreach my $field (@fields) {
10908:                 if ($hashref->{$field}) {
10909:                     if ($role eq 'emailusername') {
10910:                         $checks{$field} = $hashref->{$field};
10911:                     } else {
10912:                         $checks{$field} = ' checked="checked" ';
10913:                     }
10914:                 }
10915:             }
10916:         }
10917:     }
10918:  
10919:     my $total = scalar(@fields);
10920:     for (my $i=0; $i<$total; $i++) {
10921:         $rem = $i%($numinrow);
10922:         if ($rem == 0) {
10923:             if ($i > 0) {
10924:                 $output .= '</tr>';
10925:             }
10926:             $output .= '<tr>';
10927:         }
10928:         my $check = ' ';
10929:         unless ($role eq 'emailusername') {
10930:             if (exists($checks{$fields[$i]})) {
10931:                 $check = $checks{$fields[$i]};
10932:             } elsif ($context eq 'privacy') {
10933:                 if ($role =~ /^priv_(domain|course)$/) {
10934:                     if (ref($settings) ne 'HASH') {
10935:                         $check = ' checked="checked" ';
10936:                     }
10937:                 } elsif ($role =~ /^priv_(author|community)$/) {
10938:                     if (ref($settings) ne 'HASH') {
10939:                         unless ($fields[$i] eq 'id') {
10940:                             $check = ' checked="checked" ';
10941:                         }
10942:                     }
10943:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
10944:                     if (ref($settings) ne 'HASH') {
10945:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
10946:                             $check = ' checked="checked" ';
10947:                         }
10948:                     }
10949:                 }
10950:             } elsif ($context ne 'lti') {
10951:                 if ($role eq 'st') {
10952:                     if (ref($settings) ne 'HASH') {
10953:                         $check = ' checked="checked" '; 
10954:                     }
10955:                 }
10956:             }
10957:         }
10958:         $output .= '<td class="LC_left_item">'.
10959:                    '<span class="LC_nobreak">';
10960:         my $prefix = 'canmodify';
10961:         if ($role eq 'emailusername') {
10962:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
10963:                 $checks{$fields[$i]} = 'omit';
10964:             }
10965:             foreach my $option ('required','optional','omit') {
10966:                 my $checked='';
10967:                 if ($checks{$fields[$i]} eq $option) {
10968:                     $checked='checked="checked" ';
10969:                 }
10970:                 $output .= '<label>'.
10971:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
10972:                            &mt($option).'</label>'.('&nbsp;' x2);
10973:             }
10974:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
10975:         } else {
10976:             if ($context eq 'lti') {
10977:                 $prefix = 'lti';
10978:             } elsif ($context eq 'privacy') {
10979:                 $prefix = 'privacy';
10980:             }
10981:             $output .= '<label>'.
10982:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
10983:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
10984:                        '</label>';
10985:         }
10986:         $output .= '</span></td>';
10987:     }
10988:     $rem = $total%$numinrow;
10989:     my $colsleft;
10990:     if ($rem) {
10991:         $colsleft = $numinrow - $rem;
10992:     }
10993:     if ($colsleft > 1) {
10994:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10995:                    '&nbsp;</td>';
10996:     } elsif ($colsleft == 1) {
10997:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10998:     }
10999:     $output .= '</tr></table></td></tr>';
11000:     return $output;
11001: }
11002: 
11003: sub insttypes_row {
11004:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
11005:         $customcss,$rowstyle) = @_;
11006:     my %lt = &Apache::lonlocal::texthash (
11007:                       cansearch => 'Users allowed to search',
11008:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
11009:                       lockablenames => 'User preference to lock name',
11010:                       selfassign    => 'Self-reportable affiliations',
11011:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
11012:              );
11013:     my $showdom;
11014:     if ($context eq 'cansearch') {
11015:         $showdom = ' ('.$dom.')';
11016:     }
11017:     my $class = 'LC_left_item';
11018:     if ($context eq 'statustocreate') {
11019:         $class = 'LC_right_item';
11020:     }
11021:     my $css_class;
11022:     if ($$rowtotal%2) {
11023:         $css_class = 'LC_odd_row';
11024:     }
11025:     if ($customcss) {
11026:         $css_class .= ' '.$customcss;
11027:     }
11028:     $css_class =~ s/^\s+//;
11029:     if ($css_class) {
11030:         $css_class = ' class="'.$css_class.'"';
11031:     }
11032:     if ($rowstyle) {
11033:         $css_class .= ' style="'.$rowstyle.'"';
11034:     }
11035:     if ($onclick) {
11036:         $onclick = 'onclick="'.$onclick.'" ';
11037:     }
11038:     my $output = '<tr'.$css_class.'>'.
11039:                  '<td>'.$lt{$context}.$showdom.
11040:                  '</td><td class="'.$class.'" colspan="2"><table>';
11041:     my $rem;
11042:     if (ref($types) eq 'ARRAY') {
11043:         for (my $i=0; $i<@{$types}; $i++) {
11044:             if (defined($usertypes->{$types->[$i]})) {
11045:                 my $rem = $i%($numinrow);
11046:                 if ($rem == 0) {
11047:                     if ($i > 0) {
11048:                         $output .= '</tr>';
11049:                     }
11050:                     $output .= '<tr>';
11051:                 }
11052:                 my $check = ' ';
11053:                 if (ref($settings) eq 'HASH') {
11054:                     if (ref($settings->{$context}) eq 'ARRAY') {
11055:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
11056:                             $check = ' checked="checked" ';
11057:                         }
11058:                     } elsif (ref($settings->{$context}) eq 'HASH') {
11059:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
11060:                             $check = ' checked="checked" ';
11061:                         }
11062:                     } elsif ($context eq 'statustocreate') {
11063:                         $check = ' checked="checked" ';
11064:                     }
11065:                 }
11066:                 $output .= '<td class="LC_left_item">'.
11067:                            '<span class="LC_nobreak"><label>'.
11068:                            '<input type="checkbox" name="'.$context.'" '.
11069:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
11070:                            $usertypes->{$types->[$i]}.'</label></span></td>';
11071:             }
11072:         }
11073:         $rem = @{$types}%($numinrow);
11074:     }
11075:     my $colsleft = $numinrow - $rem;
11076:     if ($context eq 'overrides') {
11077:         if ($colsleft > 1) {
11078:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11079:         } else {
11080:             $output .= '<td class="LC_left_item">';
11081:         }
11082:         $output .= '&nbsp;';  
11083:     } else {
11084:         if ($rem == 0) {
11085:             $output .= '<tr>';
11086:         }
11087:         if ($colsleft > 1) {
11088:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11089:         } else {
11090:             $output .= '<td class="LC_left_item">';
11091:         }
11092:         my $defcheck = ' ';
11093:         if (ref($settings) eq 'HASH') {  
11094:             if (ref($settings->{$context}) eq 'ARRAY') {
11095:                 if (grep(/^default$/,@{$settings->{$context}})) {
11096:                     $defcheck = ' checked="checked" ';
11097:                 }
11098:             } elsif ($context eq 'statustocreate') {
11099:                 $defcheck = ' checked="checked" ';
11100:             }
11101:         }
11102:         $output .= '<span class="LC_nobreak"><label>'.
11103:                    '<input type="checkbox" name="'.$context.'" '.
11104:                    'value="default"'.$defcheck.$onclick.' />'.
11105:                    $othertitle.'</label></span>';
11106:     }
11107:     $output .= '</td></tr></table></td></tr>';
11108:     return $output;
11109: }
11110: 
11111: sub sorted_searchtitles {
11112:     my %searchtitles = &Apache::lonlocal::texthash(
11113:                          'uname' => 'username',
11114:                          'lastname' => 'last name',
11115:                          'lastfirst' => 'last name, first name',
11116:                      );
11117:     my @titleorder = ('uname','lastname','lastfirst');
11118:     return (\%searchtitles,\@titleorder);
11119: }
11120: 
11121: sub sorted_searchtypes {
11122:     my %srchtypes_desc = (
11123:                            exact    => 'is exact match',
11124:                            contains => 'contains ..',
11125:                            begins   => 'begins with ..',
11126:                          );
11127:     my @srchtypeorder = ('exact','begins','contains');
11128:     return (\%srchtypes_desc,\@srchtypeorder);
11129: }
11130: 
11131: sub usertype_update_row {
11132:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
11133:     my $datatable;
11134:     my $numinrow = 4;
11135:     foreach my $type (@{$types}) {
11136:         if (defined($usertypes->{$type})) {
11137:             $$rownums ++;
11138:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
11139:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
11140:                           '</td><td class="LC_left_item"><table>';
11141:             for (my $i=0; $i<@{$fields}; $i++) {
11142:                 my $rem = $i%($numinrow);
11143:                 if ($rem == 0) {
11144:                     if ($i > 0) {
11145:                         $datatable .= '</tr>';
11146:                     }
11147:                     $datatable .= '<tr>';
11148:                 }
11149:                 my $check = ' ';
11150:                 if (ref($settings) eq 'HASH') {
11151:                     if (ref($settings->{'fields'}) eq 'HASH') {
11152:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
11153:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
11154:                                 $check = ' checked="checked" ';
11155:                             }
11156:                         }
11157:                     }
11158:                 }
11159: 
11160:                 if ($i == @{$fields}-1) {
11161:                     my $colsleft = $numinrow - $rem;
11162:                     if ($colsleft > 1) {
11163:                         $datatable .= '<td colspan="'.$colsleft.'">';
11164:                     } else {
11165:                         $datatable .= '<td>';
11166:                     }
11167:                 } else {
11168:                     $datatable .= '<td>';
11169:                 }
11170:                 $datatable .= '<span class="LC_nobreak"><label>'.
11171:                               '<input type="checkbox" name="updateable_'.$type.
11172:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
11173:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
11174:             }
11175:             $datatable .= '</tr></table></td></tr>';
11176:         }
11177:     }
11178:     return $datatable;
11179: }
11180: 
11181: sub modify_login {
11182:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
11183:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
11184:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
11185:     %title = ( coursecatalog => 'Display course catalog',
11186:                adminmail => 'Display administrator E-mail address',
11187:                helpdesk  => 'Display "Contact Helpdesk" link',
11188:                newuser => 'Link for visitors to create a user account',
11189:                loginheader => 'Log-in box header');
11190:     @offon = ('off','on');
11191:     if (ref($domconfig{login}) eq 'HASH') {
11192:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
11193:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
11194:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
11195:             }
11196:         }
11197:     }
11198:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
11199:                                            \%domconfig,\%loginhash);
11200:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11201:     foreach my $item (@toggles) {
11202:         $loginhash{login}{$item} = $env{'form.'.$item};
11203:     }
11204:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
11205:     if (ref($colchanges{'login'}) eq 'HASH') {  
11206:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
11207:                                          \%loginhash);
11208:     }
11209: 
11210:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
11211:     my %domservers = &Apache::lonnet::get_servers($dom);
11212:     my @loginvia_attribs = ('serverpath','custompath','exempt');
11213:     if (keys(%servers) > 1) {
11214:         foreach my $lonhost (keys(%servers)) {
11215:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
11216:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
11217:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
11218:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
11219:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
11220:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11221:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11222:                         $changes{'loginvia'}{$lonhost} = 1;
11223:                     } else {
11224:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
11225:                         $changes{'loginvia'}{$lonhost} = 1;
11226:                     }
11227:                 } else {
11228:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11229:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11230:                         $changes{'loginvia'}{$lonhost} = 1;
11231:                     }
11232:                 }
11233:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
11234:                     foreach my $item (@loginvia_attribs) {
11235:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
11236:                     }
11237:                 } else {
11238:                     foreach my $item (@loginvia_attribs) {
11239:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11240:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11241:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
11242:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11243:                                 $new = '/';
11244:                             }
11245:                         }
11246:                         if (($item eq 'custompath') && 
11247:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11248:                             $new = '';
11249:                         }
11250:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
11251:                             $changes{'loginvia'}{$lonhost} = 1;
11252:                         }
11253:                         if ($item eq 'exempt') {
11254:                             $new = &check_exempt_addresses($new);
11255:                         }
11256:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11257:                     }
11258:                 }
11259:             } else {
11260:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11261:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11262:                     $changes{'loginvia'}{$lonhost} = 1;
11263:                     foreach my $item (@loginvia_attribs) {
11264:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11265:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11266:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11267:                                 $new = '/';
11268:                             }
11269:                         }
11270:                         if (($item eq 'custompath') && 
11271:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11272:                             $new = '';
11273:                         }
11274:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11275:                     }
11276:                 }
11277:             }
11278:         }
11279:     }
11280: 
11281:     my $servadm = $r->dir_config('lonAdmEMail');
11282:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
11283:     if (ref($domconfig{'login'}) eq 'HASH') {
11284:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
11285:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
11286:                 if ($lang eq 'nolang') {
11287:                     push(@currlangs,$lang);
11288:                 } elsif (defined($langchoices{$lang})) {
11289:                     push(@currlangs,$lang);
11290:                 } else {
11291:                     next;
11292:                 }
11293:             }
11294:         }
11295:     }
11296:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
11297:     if (@currlangs > 0) {
11298:         foreach my $lang (@currlangs) {
11299:             if (grep(/^\Q$lang\E$/,@delurls)) {
11300:                 $changes{'helpurl'}{$lang} = 1;
11301:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
11302:                 $changes{'helpurl'}{$lang} = 1;
11303:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
11304:                 push(@newlangs,$lang);
11305:             } else {
11306:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11307:             }
11308:         }
11309:     }
11310:     unless (grep(/^nolang$/,@currlangs)) {
11311:         if ($env{'form.loginhelpurl_nolang.filename'}) {
11312:             $changes{'helpurl'}{'nolang'} = 1;
11313:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
11314:             push(@newlangs,'nolang');
11315:         }
11316:     }
11317:     if ($env{'form.loginhelpurl_add_lang'}) {
11318:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
11319:             ($env{'form.loginhelpurl_add_file.filename'})) {
11320:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
11321:             $addedfile = $env{'form.loginhelpurl_add_lang'};
11322:         }
11323:     }
11324:     if ((@newlangs > 0) || ($addedfile)) {
11325:         my $error;
11326:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11327:         if ($configuserok eq 'ok') {
11328:             if ($switchserver) {
11329:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
11330:             } elsif ($author_ok eq 'ok') {
11331:                 my @allnew = @newlangs;
11332:                 if ($addedfile ne '') {
11333:                     push(@allnew,$addedfile);
11334:                 }
11335:                 foreach my $lang (@allnew) {
11336:                     my $formelem = 'loginhelpurl_'.$lang;
11337:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
11338:                         $formelem = 'loginhelpurl_add_file';
11339:                     }
11340:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11341:                                                                "help/$lang",'','',$newfile{$lang});
11342:                     if ($result eq 'ok') {
11343:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
11344:                         $changes{'helpurl'}{$lang} = 1;
11345:                     } else {
11346:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
11347:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11348:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
11349:                             (!grep(/^\Q$lang\E$/,@delurls))) {
11350:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11351:                         }
11352:                     }
11353:                 }
11354:             } else {
11355:                 $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);
11356:             }
11357:         } else {
11358:             $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);
11359:         }
11360:         if ($error) {
11361:             &Apache::lonnet::logthis($error);
11362:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11363:         }
11364:     }
11365: 
11366:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
11367:     if (ref($domconfig{'login'}) eq 'HASH') {
11368:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
11369:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
11370:                 if ($domservers{$lonhost}) {
11371:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11372:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
11373:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
11374:                     }
11375:                 }
11376:             }
11377:         }
11378:     }
11379:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
11380:     foreach my $lonhost (sort(keys(%domservers))) {
11381:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11382:             $changes{'headtag'}{$lonhost} = 1;
11383:         } else {
11384:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
11385:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
11386:             }
11387:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
11388:                 push(@newhosts,$lonhost);
11389:             } elsif ($currheadtagurls{$lonhost}) {
11390:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
11391:                 if ($currexempt{$lonhost}) {
11392:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
11393:                         $changes{'headtag'}{$lonhost} = 1;
11394:                     }
11395:                 } elsif ($possexempt{$lonhost}) {
11396:                     $changes{'headtag'}{$lonhost} = 1;
11397:                 }
11398:                 if ($possexempt{$lonhost}) {
11399:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11400:                 }
11401:             }
11402:         }
11403:     }
11404:     if (@newhosts) {
11405:         my $error;
11406:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11407:         if ($configuserok eq 'ok') {
11408:             if ($switchserver) {
11409:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
11410:             } elsif ($author_ok eq 'ok') {
11411:                 foreach my $lonhost (@newhosts) {
11412:                     my $formelem = 'loginheadtag_'.$lonhost;
11413:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11414:                                                                           "login/headtag/$lonhost",'','',
11415:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
11416:                     if ($result eq 'ok') {
11417:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
11418:                         $changes{'headtag'}{$lonhost} = 1;
11419:                         if ($possexempt{$lonhost}) {
11420:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11421:                         }
11422:                     } else {
11423:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
11424:                                            $newheadtagurls{$lonhost},$result);
11425:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11426:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
11427:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
11428:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
11429:                         }
11430:                     }
11431:                 }
11432:             } else {
11433:                 $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);
11434:             }
11435:         } else {
11436:             $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);
11437:         }
11438:         if ($error) {
11439:             &Apache::lonnet::logthis($error);
11440:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11441:         }
11442:     }
11443:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
11444: 
11445:     my $defaulthelpfile = '/adm/loginproblems.html';
11446:     my $defaulttext = &mt('Default in use');
11447: 
11448:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
11449:                                              $dom);
11450:     if ($putresult eq 'ok') {
11451:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11452:         my %defaultchecked = (
11453:                     'coursecatalog' => 'on',
11454:                     'helpdesk'      => 'on',
11455:                     'adminmail'     => 'off',
11456:                     'newuser'       => 'off',
11457:         );
11458:         if (ref($domconfig{'login'}) eq 'HASH') {
11459:             foreach my $item (@toggles) {
11460:                 if ($defaultchecked{$item} eq 'on') { 
11461:                     if (($domconfig{'login'}{$item} eq '0') &&
11462:                         ($env{'form.'.$item} eq '1')) {
11463:                         $changes{$item} = 1;
11464:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11465:                               $domconfig{'login'}{$item} eq '1') &&
11466:                              ($env{'form.'.$item} eq '0')) {
11467:                         $changes{$item} = 1;
11468:                     }
11469:                 } elsif ($defaultchecked{$item} eq 'off') {
11470:                     if (($domconfig{'login'}{$item} eq '1') &&
11471:                         ($env{'form.'.$item} eq '0')) {
11472:                         $changes{$item} = 1;
11473:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11474:                               $domconfig{'login'}{$item} eq '0') &&
11475:                              ($env{'form.'.$item} eq '1')) {
11476:                         $changes{$item} = 1;
11477:                     }
11478:                 }
11479:             }
11480:         }
11481:         if (keys(%changes) > 0 || $colchgtext) {
11482:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11483:             if (ref($lastactref) eq 'HASH') {
11484:                 $lastactref->{'domainconfig'} = 1;
11485:             }
11486:             $resulttext = &mt('Changes made:').'<ul>';
11487:             foreach my $item (sort(keys(%changes))) {
11488:                 if ($item eq 'loginvia') {
11489:                     if (ref($changes{$item}) eq 'HASH') {
11490:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
11491:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11492:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
11493:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
11494:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
11495:                                     $protocol = 'http' if ($protocol ne 'https');
11496:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
11497: 
11498:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
11499:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
11500:                                     } else {
11501:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
11502:                                     }
11503:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
11504:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
11505:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
11506:                                     }
11507:                                     $resulttext .= '</li>';
11508:                                 } else {
11509:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
11510:                                 }
11511:                             } else {
11512:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
11513:                             }
11514:                         }
11515:                         $resulttext .= '</ul></li>';
11516:                     }
11517:                 } elsif ($item eq 'helpurl') {
11518:                     if (ref($changes{$item}) eq 'HASH') {
11519:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
11520:                             if (grep(/^\Q$lang\E$/,@delurls)) {
11521:                                 my ($chg,$link);
11522:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
11523:                                 if ($lang eq 'nolang') {
11524:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
11525:                                 } else {
11526:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
11527:                                 }
11528:                                 $resulttext .= '<li>'.$chg.'</li>';
11529:                             } else {
11530:                                 my $chg;
11531:                                 if ($lang eq 'nolang') {
11532:                                     $chg = &mt('custom log-in help file for no preferred language');
11533:                                 } else {
11534:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
11535:                                 }
11536:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
11537:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
11538:                                                       '?inhibitmenu=yes',$chg,600,500).
11539:                                                '</li>';
11540:                             }
11541:                         }
11542:                     }
11543:                 } elsif ($item eq 'headtag') {
11544:                     if (ref($changes{$item}) eq 'HASH') {
11545:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11546:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11547:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
11548:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11549:                                 $resulttext .= '<li><a href="'.
11550:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
11551:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
11552:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
11553:                                 if ($possexempt{$lonhost}) {
11554:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
11555:                                 } else {
11556:                                     $resulttext .= &mt('included for any client IP');
11557:                                 }
11558:                                 $resulttext .= '</li>';
11559:                             }
11560:                         }
11561:                     }
11562:                 } elsif ($item eq 'captcha') {
11563:                     if (ref($loginhash{'login'}) eq 'HASH') {
11564:                         my $chgtxt;
11565:                         if ($loginhash{'login'}{$item} eq 'notused') {
11566:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
11567:                         } else {
11568:                             my %captchas = &captcha_phrases();
11569:                             if ($captchas{$loginhash{'login'}{$item}}) {
11570:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
11571:                             } else {
11572:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
11573:                             }
11574:                         }
11575:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11576:                     }
11577:                 } elsif ($item eq 'recaptchakeys') {
11578:                     if (ref($loginhash{'login'}) eq 'HASH') {
11579:                         my ($privkey,$pubkey);
11580:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
11581:                             $pubkey = $loginhash{'login'}{$item}{'public'};
11582:                             $privkey = $loginhash{'login'}{$item}{'private'};
11583:                         }
11584:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
11585:                         if (!$pubkey) {
11586:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
11587:                         } else {
11588:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
11589:                         }
11590:                         if (!$privkey) {
11591:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
11592:                         } else {
11593:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
11594:                         }
11595:                         $chgtxt .= '</ul>';
11596:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11597:                     }
11598:                 } elsif ($item eq 'recaptchaversion') {
11599:                     if (ref($loginhash{'login'}) eq 'HASH') {
11600:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
11601:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
11602:                                            '</li>';
11603:                         }
11604:                     }
11605:                 } else {
11606:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
11607:                 }
11608:             }
11609:             $resulttext .= $colchgtext.'</ul>';
11610:         } else {
11611:             $resulttext = &mt('No changes made to log-in page settings');
11612:         }
11613:     } else {
11614:         $resulttext = '<span class="LC_error">'.
11615: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11616:     }
11617:     if ($errors) {
11618:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
11619:                        $errors.'</ul>';
11620:     }
11621:     return $resulttext;
11622: }
11623: 
11624: sub check_exempt_addresses {
11625:     my ($iplist) = @_;
11626:     $iplist =~ s/^\s+//;
11627:     $iplist =~ s/\s+$//;
11628:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
11629:     my (@okips,$new);
11630:     foreach my $ip (@poss_ips) {
11631:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
11632:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
11633:                 push(@okips,$ip);
11634:             }
11635:         }
11636:     }
11637:     if (@okips > 0) {
11638:         $new = join(',',@okips);
11639:     } else {
11640:         $new = '';
11641:     }
11642:     return $new;
11643: }
11644: 
11645: sub color_font_choices {
11646:     my %choices =
11647:         &Apache::lonlocal::texthash (
11648:             img => "Header",
11649:             bgs => "Background colors",
11650:             links => "Link colors",
11651:             images => "Images",
11652:             font => "Font color",
11653:             fontmenu => "Font menu",
11654:             pgbg => "Page",
11655:             tabbg => "Header",
11656:             sidebg => "Border",
11657:             link => "Link",
11658:             alink => "Active link",
11659:             vlink => "Visited link",
11660:         );
11661:     return %choices;
11662: }
11663: 
11664: sub modify_rolecolors {
11665:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
11666:     my ($resulttext,%rolehash);
11667:     $rolehash{'rolecolors'} = {};
11668:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
11669:         if ($domconfig{'rolecolors'} eq '') {
11670:             $domconfig{'rolecolors'} = {};
11671:         }
11672:     }
11673:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
11674:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
11675:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
11676:                                              $dom);
11677:     if ($putresult eq 'ok') {
11678:         if (keys(%changes) > 0) {
11679:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11680:             if (ref($lastactref) eq 'HASH') {
11681:                 $lastactref->{'domainconfig'} = 1;
11682:             }
11683:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
11684:                                              $rolehash{'rolecolors'});
11685:         } else {
11686:             $resulttext = &mt('No changes made to default color schemes');
11687:         }
11688:     } else {
11689:         $resulttext = '<span class="LC_error">'.
11690: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11691:     }
11692:     if ($errors) {
11693:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
11694:                        $errors.'</ul>';
11695:     }
11696:     return $resulttext;
11697: }
11698: 
11699: sub modify_colors {
11700:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
11701:     my (%changes,%choices);
11702:     my @bgs;
11703:     my @links = ('link','alink','vlink');
11704:     my @logintext;
11705:     my @images;
11706:     my $servadm = $r->dir_config('lonAdmEMail');
11707:     my $errors;
11708:     my %defaults;
11709:     foreach my $role (@{$roles}) {
11710:         if ($role eq 'login') {
11711:             %choices = &login_choices();
11712:             @logintext = ('textcol','bgcol');
11713:         } else {
11714:             %choices = &color_font_choices();
11715:         }
11716:         if ($role eq 'login') {
11717:             @images = ('img','logo','domlogo','login');
11718:             @bgs = ('pgbg','mainbg','sidebg');
11719:         } else {
11720:             @images = ('img');
11721:             @bgs = ('pgbg','tabbg','sidebg');
11722:         }
11723:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
11724:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
11725:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
11726:         }
11727:         if ($role eq 'login') {
11728:             foreach my $item (@logintext) {
11729:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11730:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11731:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11732:                 }
11733:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
11734:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11735:                 }
11736:             }
11737:         } else {
11738:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
11739:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
11740:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
11741:             }
11742:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
11743:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
11744:             }
11745:         }
11746:         foreach my $item (@bgs) {
11747:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11748:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11749:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11750:             }
11751:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
11752:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11753:             }
11754:         }
11755:         foreach my $item (@links) {
11756:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11757:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11758:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11759:             }
11760:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
11761:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11762:             }
11763:         }
11764:         my ($configuserok,$author_ok,$switchserver) = 
11765:             &config_check($dom,$confname,$servadm);
11766:         my ($width,$height) = &thumb_dimensions();
11767:         if (ref($domconfig->{$role}) ne 'HASH') {
11768:             $domconfig->{$role} = {};
11769:         }
11770:         foreach my $img (@images) {
11771:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
11772:                 if (defined($env{'form.login_showlogo_'.$img})) {
11773:                     $confhash->{$role}{'showlogo'}{$img} = 1;
11774:                 } else { 
11775:                     $confhash->{$role}{'showlogo'}{$img} = 0;
11776:                 }
11777:             } 
11778: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
11779: 		 && !defined($domconfig->{$role}{$img})
11780: 		 && !$env{'form.'.$role.'_del_'.$img}
11781: 		 && $env{'form.'.$role.'_import_'.$img}) {
11782: 		# import the old configured image from the .tab setting
11783: 		# if they haven't provided a new one 
11784: 		$domconfig->{$role}{$img} = 
11785: 		    $env{'form.'.$role.'_import_'.$img};
11786: 	    }
11787:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
11788:                 my $error;
11789:                 if ($configuserok eq 'ok') {
11790:                     if ($switchserver) {
11791:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
11792:                     } else {
11793:                         if ($author_ok eq 'ok') {
11794:                             my ($result,$logourl) = 
11795:                                 &publishlogo($r,'upload',$role.'_'.$img,
11796:                                            $dom,$confname,$img,$width,$height);
11797:                             if ($result eq 'ok') {
11798:                                 $confhash->{$role}{$img} = $logourl;
11799:                                 $changes{$role}{'images'}{$img} = 1;
11800:                             } else {
11801:                                 $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);
11802:                             }
11803:                         } else {
11804:                             $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);
11805:                         }
11806:                     }
11807:                 } else {
11808:                     $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);
11809:                 }
11810:                 if ($error) {
11811:                     &Apache::lonnet::logthis($error);
11812:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11813:                 }
11814:             } elsif ($domconfig->{$role}{$img} ne '') {
11815:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
11816:                     my $error;
11817:                     if ($configuserok eq 'ok') {
11818: # is confname an author?
11819:                         if ($switchserver eq '') {
11820:                             if ($author_ok eq 'ok') {
11821:                                 my ($result,$logourl) = 
11822:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
11823:                                             $dom,$confname,$img,$width,$height);
11824:                                 if ($result eq 'ok') {
11825:                                     $confhash->{$role}{$img} = $logourl;
11826: 				    $changes{$role}{'images'}{$img} = 1;
11827:                                 }
11828:                             }
11829:                         }
11830:                     }
11831:                 }
11832:             }
11833:         }
11834:         if (ref($domconfig) eq 'HASH') {
11835:             if (ref($domconfig->{$role}) eq 'HASH') {
11836:                 foreach my $img (@images) {
11837:                     if ($domconfig->{$role}{$img} ne '') {
11838:                         if ($env{'form.'.$role.'_del_'.$img}) {
11839:                             $confhash->{$role}{$img} = '';
11840:                             $changes{$role}{'images'}{$img} = 1;
11841:                         } else {
11842:                             if ($confhash->{$role}{$img} eq '') {
11843:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
11844:                             }
11845:                         }
11846:                     } else {
11847:                         if ($env{'form.'.$role.'_del_'.$img}) {
11848:                             $confhash->{$role}{$img} = '';
11849:                             $changes{$role}{'images'}{$img} = 1;
11850:                         } 
11851:                     }
11852:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
11853:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
11854:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
11855:                                 $domconfig->{$role}{'showlogo'}{$img}) {
11856:                                 $changes{$role}{'showlogo'}{$img} = 1; 
11857:                             }
11858:                         } else {
11859:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11860:                                 $changes{$role}{'showlogo'}{$img} = 1;
11861:                             }
11862:                         }
11863:                     }
11864:                 }
11865:                 if ($domconfig->{$role}{'font'} ne '') {
11866:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
11867:                         $changes{$role}{'font'} = 1;
11868:                     }
11869:                 } else {
11870:                     if ($confhash->{$role}{'font'}) {
11871:                         $changes{$role}{'font'} = 1;
11872:                     }
11873:                 }
11874:                 if ($role ne 'login') {
11875:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
11876:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
11877:                             $changes{$role}{'fontmenu'} = 1;
11878:                         }
11879:                     } else {
11880:                         if ($confhash->{$role}{'fontmenu'}) {
11881:                             $changes{$role}{'fontmenu'} = 1;
11882:                         }
11883:                     }
11884:                 }
11885:                 foreach my $item (@bgs) {
11886:                     if ($domconfig->{$role}{$item} ne '') {
11887:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11888:                             $changes{$role}{'bgs'}{$item} = 1;
11889:                         } 
11890:                     } else {
11891:                         if ($confhash->{$role}{$item}) {
11892:                             $changes{$role}{'bgs'}{$item} = 1;
11893:                         }
11894:                     }
11895:                 }
11896:                 foreach my $item (@links) {
11897:                     if ($domconfig->{$role}{$item} ne '') {
11898:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11899:                             $changes{$role}{'links'}{$item} = 1;
11900:                         }
11901:                     } else {
11902:                         if ($confhash->{$role}{$item}) {
11903:                             $changes{$role}{'links'}{$item} = 1;
11904:                         }
11905:                     }
11906:                 }
11907:                 foreach my $item (@logintext) {
11908:                     if ($domconfig->{$role}{$item} ne '') {
11909:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11910:                             $changes{$role}{'logintext'}{$item} = 1;
11911:                         }
11912:                     } else {
11913:                         if ($confhash->{$role}{$item}) {
11914:                             $changes{$role}{'logintext'}{$item} = 1;
11915:                         }
11916:                     }
11917:                 }
11918:             } else {
11919:                 &default_change_checker($role,\@images,\@links,\@bgs,
11920:                                         \@logintext,$confhash,\%changes); 
11921:             }
11922:         } else {
11923:             &default_change_checker($role,\@images,\@links,\@bgs,
11924:                                     \@logintext,$confhash,\%changes); 
11925:         }
11926:     }
11927:     return ($errors,%changes);
11928: }
11929: 
11930: sub config_check {
11931:     my ($dom,$confname,$servadm) = @_;
11932:     my ($configuserok,$author_ok,$switchserver,%currroles);
11933:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
11934:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
11935:                                                    $confname,$servadm);
11936:     if ($configuserok eq 'ok') {
11937:         $switchserver = &check_switchserver($dom,$confname);
11938:         if ($switchserver eq '') {
11939:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
11940:         }
11941:     }
11942:     return ($configuserok,$author_ok,$switchserver);
11943: }
11944: 
11945: sub default_change_checker {
11946:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
11947:     foreach my $item (@{$links}) {
11948:         if ($confhash->{$role}{$item}) {
11949:             $changes->{$role}{'links'}{$item} = 1;
11950:         }
11951:     }
11952:     foreach my $item (@{$bgs}) {
11953:         if ($confhash->{$role}{$item}) {
11954:             $changes->{$role}{'bgs'}{$item} = 1;
11955:         }
11956:     }
11957:     foreach my $item (@{$logintext}) {
11958:         if ($confhash->{$role}{$item}) {
11959:             $changes->{$role}{'logintext'}{$item} = 1;
11960:         }
11961:     }
11962:     foreach my $img (@{$images}) {
11963:         if ($env{'form.'.$role.'_del_'.$img}) {
11964:             $confhash->{$role}{$img} = '';
11965:             $changes->{$role}{'images'}{$img} = 1;
11966:         }
11967:         if ($role eq 'login') {
11968:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11969:                 $changes->{$role}{'showlogo'}{$img} = 1;
11970:             }
11971:         }
11972:     }
11973:     if ($confhash->{$role}{'font'}) {
11974:         $changes->{$role}{'font'} = 1;
11975:     }
11976: }
11977: 
11978: sub display_colorchgs {
11979:     my ($dom,$changes,$roles,$confhash) = @_;
11980:     my (%choices,$resulttext);
11981:     if (!grep(/^login$/,@{$roles})) {
11982:         $resulttext = &mt('Changes made:').'<br />';
11983:     }
11984:     foreach my $role (@{$roles}) {
11985:         if ($role eq 'login') {
11986:             %choices = &login_choices();
11987:         } else {
11988:             %choices = &color_font_choices();
11989:         }
11990:         if (ref($changes->{$role}) eq 'HASH') {
11991:             if ($role ne 'login') {
11992:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
11993:             }
11994:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
11995:                 if ($role ne 'login') {
11996:                     $resulttext .= '<ul>';
11997:                 }
11998:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
11999:                     if ($role ne 'login') {
12000:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
12001:                     }
12002:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
12003:                         if (($role eq 'login') && ($key eq 'showlogo')) {
12004:                             if ($confhash->{$role}{$key}{$item}) {
12005:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
12006:                             } else {
12007:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
12008:                             }
12009:                         } elsif ($confhash->{$role}{$item} eq '') {
12010:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
12011:                         } else {
12012:                             my $newitem = $confhash->{$role}{$item};
12013:                             if ($key eq 'images') {
12014:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
12015:                             }
12016:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
12017:                         }
12018:                     }
12019:                     if ($role ne 'login') {
12020:                         $resulttext .= '</ul></li>';
12021:                     }
12022:                 } else {
12023:                     if ($confhash->{$role}{$key} eq '') {
12024:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
12025:                     } else {
12026:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
12027:                     }
12028:                 }
12029:                 if ($role ne 'login') {
12030:                     $resulttext .= '</ul>';
12031:                 }
12032:             }
12033:         }
12034:     }
12035:     return $resulttext;
12036: }
12037: 
12038: sub thumb_dimensions {
12039:     return ('200','50');
12040: }
12041: 
12042: sub check_dimensions {
12043:     my ($inputfile) = @_;
12044:     my ($fullwidth,$fullheight);
12045:     if ($inputfile =~ m|^[/\w.\-]+$|) {
12046:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
12047:             my $imageinfo = <PIPE>;
12048:             if (!close(PIPE)) {
12049:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
12050:             }
12051:             chomp($imageinfo);
12052:             my ($fullsize) = 
12053:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
12054:             if ($fullsize) {
12055:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
12056:             }
12057:         }
12058:     }
12059:     return ($fullwidth,$fullheight);
12060: }
12061: 
12062: sub check_configuser {
12063:     my ($uhome,$dom,$confname,$servadm) = @_;
12064:     my ($configuserok,%currroles);
12065:     if ($uhome eq 'no_host') {
12066:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
12067:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
12068:         $configuserok = 
12069:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
12070:                              $configpass,'','','','','',undef,$servadm);
12071:     } else {
12072:         $configuserok = 'ok';
12073:         %currroles = 
12074:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
12075:     }
12076:     return ($configuserok,%currroles);
12077: }
12078: 
12079: sub check_authorstatus {
12080:     my ($dom,$confname,%currroles) = @_;
12081:     my $author_ok;
12082:     if (!$currroles{':'.$dom.':au'}) {
12083:         my $start = time;
12084:         my $end = 0;
12085:         $author_ok = 
12086:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
12087:                                         'au',$end,$start,'','','domconfig');
12088:     } else {
12089:         $author_ok = 'ok';
12090:     }
12091:     return $author_ok;
12092: }
12093: 
12094: sub publishlogo {
12095:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
12096:     my ($output,$fname,$logourl,$madethumb);
12097:     if ($action eq 'upload') {
12098:         $fname=$env{'form.'.$formname.'.filename'};
12099:         chop($env{'form.'.$formname});
12100:     } else {
12101:         ($fname) = ($formname =~ /([^\/]+)$/);
12102:     }
12103:     if ($savefileas ne '') {
12104:         $fname = $savefileas;
12105:     }
12106:     $fname=&Apache::lonnet::clean_filename($fname);
12107: # See if there is anything left
12108:     unless ($fname) { return ('error: no uploaded file'); }
12109:     $fname="$subdir/$fname";
12110:     my $docroot=$r->dir_config('lonDocRoot');
12111:     my $filepath="$docroot/priv";
12112:     my $relpath = "$dom/$confname";
12113:     my ($fnamepath,$file,$fetchthumb);
12114:     $file=$fname;
12115:     if ($fname=~m|/|) {
12116:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
12117:     }
12118:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
12119:     my $count;
12120:     for ($count=5;$count<=$#parts;$count++) {
12121:         $filepath.="/$parts[$count]";
12122:         if ((-e $filepath)!=1) {
12123:             mkdir($filepath,02770);
12124:         }
12125:     }
12126:     # Check for bad extension and disallow upload
12127:     if ($file=~/\.(\w+)$/ &&
12128:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12129:         $output = 
12130:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
12131:     } elsif ($file=~/\.(\w+)$/ &&
12132:         !defined(&Apache::loncommon::fileembstyle($1))) {
12133:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
12134:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
12135:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
12136:     } elsif (-d "$filepath/$file") {
12137:         $output = &mt('Filename is a directory name - rename the file and re-upload');
12138:     } else {
12139:         my $source = $filepath.'/'.$file;
12140:         my $logfile;
12141:         if (!open($logfile,">>",$source.'.log')) {
12142:             return (&mt('No write permission to Authoring Space'));
12143:         }
12144:         print $logfile
12145: "\n================= Publish ".localtime()." ================\n".
12146: $env{'user.name'}.':'.$env{'user.domain'}."\n";
12147: # Save the file
12148:         if (!open(FH,">",$source)) {
12149:             &Apache::lonnet::logthis('Failed to create '.$source);
12150:             return (&mt('Failed to create file'));
12151:         }
12152:         if ($action eq 'upload') {
12153:             if (!print FH ($env{'form.'.$formname})) {
12154:                 &Apache::lonnet::logthis('Failed to write to '.$source);
12155:                 return (&mt('Failed to write file'));
12156:             }
12157:         } else {
12158:             my $original = &Apache::lonnet::filelocation('',$formname);
12159:             if(!copy($original,$source)) {
12160:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
12161:                 return (&mt('Failed to write file'));
12162:             }
12163:         }
12164:         close(FH);
12165:         chmod(0660, $source); # Permissions to rw-rw---.
12166: 
12167:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
12168:         my $copyfile=$targetdir.'/'.$file;
12169: 
12170:         my @parts=split(/\//,$targetdir);
12171:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
12172:         for (my $count=5;$count<=$#parts;$count++) {
12173:             $path.="/$parts[$count]";
12174:             if (!-e $path) {
12175:                 print $logfile "\nCreating directory ".$path;
12176:                 mkdir($path,02770);
12177:             }
12178:         }
12179:         my $versionresult;
12180:         if (-e $copyfile) {
12181:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
12182:         } else {
12183:             $versionresult = 'ok';
12184:         }
12185:         if ($versionresult eq 'ok') {
12186:             if (copy($source,$copyfile)) {
12187:                 print $logfile "\nCopied original source to ".$copyfile."\n";
12188:                 $output = 'ok';
12189:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
12190:                 push(@{$modified_urls},[$copyfile,$source]);
12191:                 my $metaoutput = 
12192:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
12193:                 unless ($registered_cleanup) {
12194:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12195:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12196:                     $registered_cleanup=1;
12197:                 }
12198:             } else {
12199:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
12200:                 $output = &mt('Failed to copy file to RES space').", $!";
12201:             }
12202:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
12203:                 my $inputfile = $filepath.'/'.$file;
12204:                 my $outfile = $filepath.'/'.'tn-'.$file;
12205:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
12206:                 if ($fullwidth ne '' && $fullheight ne '') { 
12207:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
12208:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
12209:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
12210:                         system({$args[0]} @args);
12211:                         chmod(0660, $filepath.'/tn-'.$file);
12212:                         if (-e $outfile) {
12213:                             my $copyfile=$targetdir.'/tn-'.$file;
12214:                             if (copy($outfile,$copyfile)) {
12215:                                 print $logfile "\nCopied source to ".$copyfile."\n";
12216:                                 my $thumb_metaoutput = 
12217:                                     &write_metadata($dom,$confname,$formname,
12218:                                                     $targetdir,'tn-'.$file,$logfile);
12219:                                 push(@{$modified_urls},[$copyfile,$outfile]);
12220:                                 unless ($registered_cleanup) {
12221:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12222:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12223:                                     $registered_cleanup=1;
12224:                                 }
12225:                                 $madethumb = 1;
12226:                             } else {
12227:                                 print $logfile "\nUnable to write ".$copyfile.
12228:                                                ':'.$!."\n";
12229:                             }
12230:                         }
12231:                     }
12232:                 }
12233:             }
12234:         } else {
12235:             $output = $versionresult;
12236:         }
12237:     }
12238:     return ($output,$logourl,$madethumb);
12239: }
12240: 
12241: sub logo_versioning {
12242:     my ($targetdir,$file,$logfile) = @_;
12243:     my $target = $targetdir.'/'.$file;
12244:     my ($maxversion,$fn,$extn,$output);
12245:     $maxversion = 0;
12246:     if ($file =~ /^(.+)\.(\w+)$/) {
12247:         $fn=$1;
12248:         $extn=$2;
12249:     }
12250:     opendir(DIR,$targetdir);
12251:     while (my $filename=readdir(DIR)) {
12252:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
12253:             $maxversion=($1>$maxversion)?$1:$maxversion;
12254:         }
12255:     }
12256:     $maxversion++;
12257:     print $logfile "\nCreating old version ".$maxversion."\n";
12258:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
12259:     if (copy($target,$copyfile)) {
12260:         print $logfile "Copied old target to ".$copyfile."\n";
12261:         $copyfile=$copyfile.'.meta';
12262:         if (copy($target.'.meta',$copyfile)) {
12263:             print $logfile "Copied old target metadata to ".$copyfile."\n";
12264:             $output = 'ok';
12265:         } else {
12266:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
12267:             $output = &mt('Failed to copy old meta').", $!, ";
12268:         }
12269:     } else {
12270:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
12271:         $output = &mt('Failed to copy old target').", $!, ";
12272:     }
12273:     return $output;
12274: }
12275: 
12276: sub write_metadata {
12277:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
12278:     my (%metadatafields,%metadatakeys,$output);
12279:     $metadatafields{'title'}=$formname;
12280:     $metadatafields{'creationdate'}=time;
12281:     $metadatafields{'lastrevisiondate'}=time;
12282:     $metadatafields{'copyright'}='public';
12283:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
12284:                                          $env{'user.domain'};
12285:     $metadatafields{'authorspace'}=$confname.':'.$dom;
12286:     $metadatafields{'domain'}=$dom;
12287:     {
12288:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
12289:         my $mfh;
12290:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
12291:             foreach (sort(keys(%metadatafields))) {
12292:                 unless ($_=~/\./) {
12293:                     my $unikey=$_;
12294:                     $unikey=~/^([A-Za-z]+)/;
12295:                     my $tag=$1;
12296:                     $tag=~tr/A-Z/a-z/;
12297:                     print $mfh "\n\<$tag";
12298:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
12299:                         my $value=$metadatafields{$unikey.'.'.$_};
12300:                         $value=~s/\"/\'\'/g;
12301:                         print $mfh ' '.$_.'="'.$value.'"';
12302:                     }
12303:                     print $mfh '>'.
12304:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
12305:                             .'</'.$tag.'>';
12306:                 }
12307:             }
12308:             $output = 'ok';
12309:             print $logfile "\nWrote metadata";
12310:             close($mfh);
12311:         } else {
12312:             print $logfile "\nFailed to open metadata file";
12313:             $output = &mt('Could not write metadata');
12314:         }
12315:     }
12316:     return $output;
12317: }
12318: 
12319: sub notifysubscribed {
12320:     foreach my $targetsource (@{$modified_urls}){
12321:         next unless (ref($targetsource) eq 'ARRAY');
12322:         my ($target,$source)=@{$targetsource};
12323:         if ($source ne '') {
12324:             if (open(my $logfh,">>",$source.'.log')) {
12325:                 print $logfh "\nCleanup phase: Notifications\n";
12326:                 my @subscribed=&subscribed_hosts($target);
12327:                 foreach my $subhost (@subscribed) {
12328:                     print $logfh "\nNotifying host ".$subhost.':';
12329:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
12330:                     print $logfh $reply;
12331:                 }
12332:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
12333:                 foreach my $subhost (@subscribedmeta) {
12334:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
12335:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
12336:                                                         $subhost);
12337:                     print $logfh $reply;
12338:                 }
12339:                 print $logfh "\n============ Done ============\n";
12340:                 close($logfh);
12341:             }
12342:         }
12343:     }
12344:     return OK;
12345: }
12346: 
12347: sub subscribed_hosts {
12348:     my ($target) = @_;
12349:     my @subscribed;
12350:     if (open(my $fh,"<","$target.subscription")) {
12351:         while (my $subline=<$fh>) {
12352:             if ($subline =~ /^($match_lonid):/) {
12353:                 my $host = $1;
12354:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
12355:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
12356:                         push(@subscribed,$host);
12357:                     }
12358:                 }
12359:             }
12360:         }
12361:     }
12362:     return @subscribed;
12363: }
12364: 
12365: sub check_switchserver {
12366:     my ($dom,$confname) = @_;
12367:     my ($allowed,$switchserver);
12368:     my $home = &Apache::lonnet::homeserver($confname,$dom);
12369:     if ($home eq 'no_host') {
12370:         $home = &Apache::lonnet::domain($dom,'primary');
12371:     }
12372:     my @ids=&Apache::lonnet::current_machine_ids();
12373:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
12374:     if (!$allowed) {
12375: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
12376:     }
12377:     return $switchserver;
12378: }
12379: 
12380: sub modify_quotas {
12381:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12382:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
12383:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
12384:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
12385:         $validationfieldsref);
12386:     if ($action eq 'quotas') {
12387:         $context = 'tools'; 
12388:     } else {
12389:         $context = $action;
12390:     }
12391:     if ($context eq 'requestcourses') {
12392:         @usertools = ('official','unofficial','community','textbook','placement','lti');
12393:         @options =('norequest','approval','validate','autolimit');
12394:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
12395:         %titles = &courserequest_titles();
12396:         $toolregexp = join('|',@usertools);
12397:         %conditions = &courserequest_conditions();
12398:         $confname = $dom.'-domainconfig';
12399:         my $servadm = $r->dir_config('lonAdmEMail');
12400:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12401:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
12402:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
12403:     } elsif ($context eq 'requestauthor') {
12404:         @usertools = ('author');
12405:         %titles = &authorrequest_titles();
12406:     } else {
12407:         @usertools = ('aboutme','blog','webdav','portfolio');
12408:         %titles = &tool_titles();
12409:     }
12410:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12411:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12412:     foreach my $key (keys(%env)) {
12413:         if ($context eq 'requestcourses') {
12414:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
12415:                 my $item = $1;
12416:                 my $type = $2;
12417:                 if ($type =~ /^limit_(.+)/) {
12418:                     $limithash{$item}{$1} = $env{$key};
12419:                 } else {
12420:                     $confhash{$item}{$type} = $env{$key};
12421:                 }
12422:             }
12423:         } elsif ($context eq 'requestauthor') {
12424:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
12425:                 $confhash{$1} = $env{$key};
12426:             }
12427:         } else {
12428:             if ($key =~ /^form\.quota_(.+)$/) {
12429:                 $confhash{'defaultquota'}{$1} = $env{$key};
12430:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
12431:                 $confhash{'authorquota'}{$1} = $env{$key};
12432:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
12433:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
12434:             }
12435:         }
12436:     }
12437:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12438:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
12439:         @approvalnotify = sort(@approvalnotify);
12440:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
12441:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
12442:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
12443:         foreach my $type (@hasuniquecode) {
12444:             if (grep(/^\Q$type\E$/,@crstypes)) {
12445:                 $confhash{'uniquecode'}{$type} = 1;
12446:             }
12447:         }
12448:         my (%newbook,%allpos);
12449:         if ($context eq 'requestcourses') {
12450:             foreach my $type ('textbooks','templates') {
12451:                 @{$allpos{$type}} = (); 
12452:                 my $invalid;
12453:                 if ($type eq 'textbooks') {
12454:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
12455:                 } else {
12456:                     $invalid = &mt('Invalid LON-CAPA course for template');
12457:                 }
12458:                 if ($env{'form.'.$type.'_addbook'}) {
12459:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
12460:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
12461:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
12462:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
12463:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12464:                         } else {
12465:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
12466:                             my $position = $env{'form.'.$type.'_addbook_pos'};
12467:                             $position =~ s/\D+//g;
12468:                             if ($position ne '') {
12469:                                 $allpos{$type}[$position] = $newbook{$type};
12470:                             }
12471:                         }
12472:                     } else {
12473:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12474:                     }
12475:                 }
12476:             } 
12477:         }
12478:         if (ref($domconfig{$action}) eq 'HASH') {
12479:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
12480:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
12481:                     $changes{'notify'}{'approval'} = 1;
12482:                 }
12483:             } else {
12484:                 if ($confhash{'notify'}{'approval'}) {
12485:                     $changes{'notify'}{'approval'} = 1;
12486:                 }
12487:             }
12488:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
12489:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
12490:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
12491:                         unless ($confhash{'uniquecode'}{$crstype}) {
12492:                             $changes{'uniquecode'} = 1;
12493:                         }
12494:                     }
12495:                     unless ($changes{'uniquecode'}) {
12496:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
12497:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
12498:                                 $changes{'uniquecode'} = 1;
12499:                             }
12500:                         }
12501:                     }
12502:                } else {
12503:                    $changes{'uniquecode'} = 1;
12504:                }
12505:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
12506:                 $changes{'uniquecode'} = 1;
12507:             }
12508:             if ($context eq 'requestcourses') {
12509:                 foreach my $type ('textbooks','templates') {
12510:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
12511:                         my %deletions;
12512:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
12513:                         if (@todelete) {
12514:                             map { $deletions{$_} = 1; } @todelete;
12515:                         }
12516:                         my %imgdeletions;
12517:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
12518:                         if (@todeleteimages) {
12519:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
12520:                         }
12521:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
12522:                         for (my $i=0; $i<=$maxnum; $i++) {
12523:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
12524:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
12525:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
12526:                                 if ($deletions{$key}) {
12527:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
12528:                                         #FIXME need to obsolete item in RES space
12529:                                     }
12530:                                     next;
12531:                                 } else {
12532:                                     my $newpos = $env{'form.'.$itemid};
12533:                                     $newpos =~ s/\D+//g;
12534:                                     foreach my $item ('subject','title','publisher','author') {
12535:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12536:                                                  ($type eq 'templates'));
12537:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
12538:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
12539:                                             $changes{$type}{$key} = 1;
12540:                                         }
12541:                                     }
12542:                                     $allpos{$type}[$newpos] = $key;
12543:                                 }
12544:                                 if ($imgdeletions{$key}) {
12545:                                     $changes{$type}{$key} = 1;
12546:                                     #FIXME need to obsolete item in RES space
12547:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
12548:                                     my ($cdom,$cnum) = split(/_/,$key);
12549:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12550:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12551:                                     } else {
12552:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
12553:                                                                                       $cdom,$cnum,$type,$configuserok,
12554:                                                                                       $switchserver,$author_ok);
12555:                                         if ($imgurl) {
12556:                                             $confhash{$type}{$key}{'image'} = $imgurl;
12557:                                             $changes{$type}{$key} = 1; 
12558:                                         }
12559:                                         if ($error) {
12560:                                             &Apache::lonnet::logthis($error);
12561:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12562:                                         }
12563:                                     }
12564:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
12565:                                     $confhash{$type}{$key}{'image'} = 
12566:                                         $domconfig{$action}{$type}{$key}{'image'};
12567:                                 }
12568:                             }
12569:                         }
12570:                     }
12571:                 }
12572:             }
12573:         } else {
12574:             if ($confhash{'notify'}{'approval'}) {
12575:                 $changes{'notify'}{'approval'} = 1;
12576:             }
12577:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
12578:                 $changes{'uniquecode'} = 1;
12579:             }
12580:         }
12581:         if ($context eq 'requestcourses') {
12582:             foreach my $type ('textbooks','templates') {
12583:                 if ($newbook{$type}) {
12584:                     $changes{$type}{$newbook{$type}} = 1;
12585:                     foreach my $item ('subject','title','publisher','author') {
12586:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12587:                                  ($type eq 'template'));
12588:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
12589:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
12590:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
12591:                         }
12592:                     }
12593:                     if ($type eq 'textbooks') {
12594:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
12595:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
12596:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12597:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12598:                             } else {
12599:                                 my ($imageurl,$error) =
12600:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
12601:                                                             $configuserok,$switchserver,$author_ok);
12602:                                 if ($imageurl) {
12603:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
12604:                                 }
12605:                                 if ($error) {
12606:                                     &Apache::lonnet::logthis($error);
12607:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12608:                                 }
12609:                             }
12610:                         }
12611:                     }
12612:                 }
12613:                 if (@{$allpos{$type}} > 0) {
12614:                     my $idx = 0;
12615:                     foreach my $item (@{$allpos{$type}}) {
12616:                         if ($item ne '') {
12617:                             $confhash{$type}{$item}{'order'} = $idx;
12618:                             if (ref($domconfig{$action}) eq 'HASH') {
12619:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
12620:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
12621:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
12622:                                             $changes{$type}{$item} = 1;
12623:                                         }
12624:                                     }
12625:                                 }
12626:                             }
12627:                             $idx ++;
12628:                         }
12629:                     }
12630:                 }
12631:             }
12632:             if (ref($validationitemsref) eq 'ARRAY') {
12633:                 foreach my $item (@{$validationitemsref}) {
12634:                     if ($item eq 'fields') {
12635:                         my @changed;
12636:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
12637:                         if (@{$confhash{'validation'}{$item}} > 0) {
12638:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
12639:                         }
12640:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12641:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12642:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
12643:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
12644:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
12645:                                 } else {
12646:                                     @changed = @{$confhash{'validation'}{$item}};
12647:                                 }
12648:                             } else {
12649:                                 @changed = @{$confhash{'validation'}{$item}};
12650:                             }
12651:                         } else {
12652:                             @changed = @{$confhash{'validation'}{$item}};
12653:                         }
12654:                         if (@changed) {
12655:                             if ($confhash{'validation'}{$item}) {
12656:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
12657:                             } else {
12658:                                 $changes{'validation'}{$item} = &mt('None');
12659:                             }
12660:                         }
12661:                     } else {
12662:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
12663:                         if ($item eq 'markup') {
12664:                             if ($env{'form.requestcourses_validation_'.$item}) {
12665:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
12666:                             }
12667:                         }
12668:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12669:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12670:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
12671:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12672:                                 }
12673:                             } else {
12674:                                 if ($confhash{'validation'}{$item} ne '') {
12675:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12676:                                 }
12677:                             }
12678:                         } else {
12679:                             if ($confhash{'validation'}{$item} ne '') {
12680:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12681:                             }
12682:                         }
12683:                     }
12684:                 }
12685:             }
12686:             if ($env{'form.validationdc'}) {
12687:                 my $newval = $env{'form.validationdc'};
12688:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
12689:                 if (exists($domcoords{$newval})) {
12690:                     $confhash{'validation'}{'dc'} = $newval;
12691:                 }
12692:             }
12693:             if (ref($confhash{'validation'}) eq 'HASH') {
12694:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12695:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12696:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
12697:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
12698:                                 if ($confhash{'validation'}{'dc'} eq '') {
12699:                                     $changes{'validation'}{'dc'} = &mt('None');
12700:                                 } else {
12701:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12702:                                 }
12703:                             }
12704:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
12705:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12706:                         }
12707:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
12708:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12709:                     }
12710:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
12711:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12712:                 }
12713:             } else {
12714:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12715:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12716:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
12717:                             $changes{'validation'}{'dc'} = &mt('None');
12718:                         }
12719:                     }
12720:                 }
12721:             }
12722:         }
12723:     } else {
12724:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
12725:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
12726:     }
12727:     foreach my $item (@usertools) {
12728:         foreach my $type (@{$types},'default','_LC_adv') {
12729:             my $unset; 
12730:             if ($context eq 'requestcourses') {
12731:                 $unset = '0';
12732:                 if ($type eq '_LC_adv') {
12733:                     $unset = '';
12734:                 }
12735:                 if ($confhash{$item}{$type} eq 'autolimit') {
12736:                     $confhash{$item}{$type} .= '=';
12737:                     unless ($limithash{$item}{$type} =~ /\D/) {
12738:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
12739:                     }
12740:                 }
12741:             } elsif ($context eq 'requestauthor') {
12742:                 $unset = '0';
12743:                 if ($type eq '_LC_adv') {
12744:                     $unset = '';
12745:                 }
12746:             } else {
12747:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
12748:                     $confhash{$item}{$type} = 1;
12749:                 } else {
12750:                     $confhash{$item}{$type} = 0;
12751:                 }
12752:             }
12753:             if (ref($domconfig{$action}) eq 'HASH') {
12754:                 if ($action eq 'requestauthor') {
12755:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
12756:                         $changes{$type} = 1;
12757:                     }
12758:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
12759:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
12760:                         $changes{$item}{$type} = 1;
12761:                     }
12762:                 } else {
12763:                     if ($context eq 'requestcourses') {
12764:                         if ($confhash{$item}{$type} ne $unset) {
12765:                             $changes{$item}{$type} = 1;
12766:                         }
12767:                     } else {
12768:                         if (!$confhash{$item}{$type}) {
12769:                             $changes{$item}{$type} = 1;
12770:                         }
12771:                     }
12772:                 }
12773:             } else {
12774:                 if ($context eq 'requestcourses') {
12775:                     if ($confhash{$item}{$type} ne $unset) {
12776:                         $changes{$item}{$type} = 1;
12777:                     }
12778:                 } elsif ($context eq 'requestauthor') {
12779:                     if ($confhash{$type} ne $unset) {
12780:                         $changes{$type} = 1;
12781:                     }
12782:                 } else {
12783:                     if (!$confhash{$item}{$type}) {
12784:                         $changes{$item}{$type} = 1;
12785:                     }
12786:                 }
12787:             }
12788:         }
12789:     }
12790:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12791:         if (ref($domconfig{'quotas'}) eq 'HASH') {
12792:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12793:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
12794:                     if (exists($confhash{'defaultquota'}{$key})) {
12795:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
12796:                             $changes{'defaultquota'}{$key} = 1;
12797:                         }
12798:                     } else {
12799:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
12800:                     }
12801:                 }
12802:             } else {
12803:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
12804:                     if (exists($confhash{'defaultquota'}{$key})) {
12805:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
12806:                             $changes{'defaultquota'}{$key} = 1;
12807:                         }
12808:                     } else {
12809:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
12810:                     }
12811:                 }
12812:             }
12813:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12814:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
12815:                     if (exists($confhash{'authorquota'}{$key})) {
12816:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
12817:                             $changes{'authorquota'}{$key} = 1;
12818:                         }
12819:                     } else {
12820:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
12821:                     }
12822:                 }
12823:             }
12824:         }
12825:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
12826:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
12827:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12828:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12829:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
12830:                             $changes{'defaultquota'}{$key} = 1;
12831:                         }
12832:                     } else {
12833:                         if (!exists($domconfig{'quotas'}{$key})) {
12834:                             $changes{'defaultquota'}{$key} = 1;
12835:                         }
12836:                     }
12837:                 } else {
12838:                     $changes{'defaultquota'}{$key} = 1;
12839:                 }
12840:             }
12841:         }
12842:         if (ref($confhash{'authorquota'}) eq 'HASH') {
12843:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
12844:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12845:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12846:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
12847:                             $changes{'authorquota'}{$key} = 1;
12848:                         }
12849:                     } else {
12850:                         $changes{'authorquota'}{$key} = 1;
12851:                     }
12852:                 } else {
12853:                     $changes{'authorquota'}{$key} = 1;
12854:                 }
12855:             }
12856:         }
12857:     }
12858: 
12859:     if ($context eq 'requestauthor') {
12860:         $domdefaults{'requestauthor'} = \%confhash;
12861:     } else {
12862:         foreach my $key (keys(%confhash)) {
12863:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
12864:                 $domdefaults{$key} = $confhash{$key};
12865:             }
12866:         }
12867:     }
12868: 
12869:     my %quotahash = (
12870:                       $action => { %confhash }
12871:                     );
12872:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
12873:                                              $dom);
12874:     if ($putresult eq 'ok') {
12875:         if (keys(%changes) > 0) {
12876:             my $cachetime = 24*60*60;
12877:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12878:             if (ref($lastactref) eq 'HASH') {
12879:                 $lastactref->{'domdefaults'} = 1;
12880:             }
12881:             $resulttext = &mt('Changes made:').'<ul>';
12882:             unless (($context eq 'requestcourses') ||
12883:                     ($context eq 'requestauthor')) {
12884:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
12885:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
12886:                     foreach my $type (@{$types},'default') {
12887:                         if (defined($changes{'defaultquota'}{$type})) {
12888:                             my $typetitle = $usertypes->{$type};
12889:                             if ($type eq 'default') {
12890:                                 $typetitle = $othertitle;
12891:                             }
12892:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
12893:                         }
12894:                     }
12895:                     $resulttext .= '</ul></li>';
12896:                 }
12897:                 if (ref($changes{'authorquota'}) eq 'HASH') {
12898:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
12899:                     foreach my $type (@{$types},'default') {
12900:                         if (defined($changes{'authorquota'}{$type})) {
12901:                             my $typetitle = $usertypes->{$type};
12902:                             if ($type eq 'default') {
12903:                                 $typetitle = $othertitle;
12904:                             }
12905:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
12906:                         }
12907:                     }
12908:                     $resulttext .= '</ul></li>';
12909:                 }
12910:             }
12911:             my %newenv;
12912:             foreach my $item (@usertools) {
12913:                 my (%haschgs,%inconf);
12914:                 if ($context eq 'requestauthor') {
12915:                     %haschgs = %changes;
12916:                     %inconf = %confhash;
12917:                 } else {
12918:                     if (ref($changes{$item}) eq 'HASH') {
12919:                         %haschgs = %{$changes{$item}};
12920:                     }
12921:                     if (ref($confhash{$item}) eq 'HASH') {
12922:                         %inconf = %{$confhash{$item}};
12923:                     }
12924:                 }
12925:                 if (keys(%haschgs) > 0) {
12926:                     my $newacc = 
12927:                         &Apache::lonnet::usertools_access($env{'user.name'},
12928:                                                           $env{'user.domain'},
12929:                                                           $item,'reload',$context);
12930:                     if (($context eq 'requestcourses') ||
12931:                         ($context eq 'requestauthor')) {
12932:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
12933:                             $newenv{'environment.canrequest.'.$item} = $newacc;
12934:                         }
12935:                     } else {
12936:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
12937:                             $newenv{'environment.availabletools.'.$item} = $newacc;
12938:                         }
12939:                     }
12940:                     unless ($context eq 'requestauthor') {
12941:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
12942:                     }
12943:                     foreach my $type (@{$types},'default','_LC_adv') {
12944:                         if ($haschgs{$type}) {
12945:                             my $typetitle = $usertypes->{$type};
12946:                             if ($type eq 'default') {
12947:                                 $typetitle = $othertitle;
12948:                             } elsif ($type eq '_LC_adv') {
12949:                                 $typetitle = 'LON-CAPA Advanced Users'; 
12950:                             }
12951:                             if ($inconf{$type}) {
12952:                                 if ($context eq 'requestcourses') {
12953:                                     my $cond;
12954:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
12955:                                         if ($1 eq '') {
12956:                                             $cond = &mt('(Automatic processing of any request).');
12957:                                         } else {
12958:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
12959:                                         }
12960:                                     } else { 
12961:                                         $cond = $conditions{$inconf{$type}};
12962:                                     }
12963:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
12964:                                 } elsif ($context eq 'requestauthor') {
12965:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
12966:                                                              $titles{$inconf{$type}},$typetitle);
12967: 
12968:                                 } else {
12969:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
12970:                                 }
12971:                             } else {
12972:                                 if ($type eq '_LC_adv') {
12973:                                     if ($inconf{$type} eq '0') {
12974:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12975:                                     } else { 
12976:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
12977:                                     }
12978:                                 } else {
12979:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12980:                                 }
12981:                             }
12982:                         }
12983:                     }
12984:                     unless ($context eq 'requestauthor') {
12985:                         $resulttext .= '</ul></li>';
12986:                     }
12987:                 }
12988:             }
12989:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
12990:                 if (ref($changes{'notify'}) eq 'HASH') {
12991:                     if ($changes{'notify'}{'approval'}) {
12992:                         if (ref($confhash{'notify'}) eq 'HASH') {
12993:                             if ($confhash{'notify'}{'approval'}) {
12994:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
12995:                             } else {
12996:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
12997:                             }
12998:                         }
12999:                     }
13000:                 }
13001:             }
13002:             if ($action eq 'requestcourses') {
13003:                 my @offon = ('off','on');
13004:                 if ($changes{'uniquecode'}) {
13005:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
13006:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
13007:                         $resulttext .= '<li>'.
13008:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
13009:                                        '</li>';
13010:                     } else {
13011:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
13012:                                        '</li>';
13013:                     }
13014:                 }
13015:                 foreach my $type ('textbooks','templates') {
13016:                     if (ref($changes{$type}) eq 'HASH') {
13017:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
13018:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
13019:                             my %coursehash = &Apache::lonnet::coursedescription($key);
13020:                             my $coursetitle = $coursehash{'description'};
13021:                             my $position = $confhash{$type}{$key}{'order'} + 1;
13022:                             $resulttext .= '<li>';
13023:                             foreach my $item ('subject','title','publisher','author') {
13024:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
13025:                                          ($type eq 'templates'));
13026:                                 my $name = $item.':';
13027:                                 $name =~ s/^(\w)/\U$1/;
13028:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
13029:                             }
13030:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
13031:                             if ($type eq 'textbooks') {
13032:                                 if ($confhash{$type}{$key}{'image'}) {
13033:                                     $resulttext .= ' '.&mt('Image: [_1]',
13034:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
13035:                                                    ' alt="Textbook cover" />').'<br />';
13036:                                 }
13037:                             }
13038:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
13039:                         }
13040:                         $resulttext .= '</ul></li>';
13041:                     }
13042:                 }
13043:                 if (ref($changes{'validation'}) eq 'HASH') {
13044:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
13045:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
13046:                         foreach my $item (@{$validationitemsref}) {
13047:                             if (exists($changes{'validation'}{$item})) {
13048:                                 if ($item eq 'markup') {
13049:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13050:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
13051:                                 } else {
13052:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13053:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
13054:                                 }
13055:                             }
13056:                         }
13057:                         if (exists($changes{'validation'}{'dc'})) {
13058:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
13059:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
13060:                         }
13061:                     }
13062:                 }
13063:             }
13064:             $resulttext .= '</ul>';
13065:             if (keys(%newenv)) {
13066:                 &Apache::lonnet::appenv(\%newenv);
13067:             }
13068:         } else {
13069:             if ($context eq 'requestcourses') {
13070:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
13071:             } elsif ($context eq 'requestauthor') {
13072:                 $resulttext = &mt('No changes made to rights to request author space.');
13073:             } else {
13074:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
13075:             }
13076:         }
13077:     } else {
13078:         $resulttext = '<span class="LC_error">'.
13079: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13080:     }
13081:     if ($errors) {
13082:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
13083:                        '<ul>'.$errors.'</ul></p>';
13084:     }
13085:     return $resulttext;
13086: }
13087: 
13088: sub process_textbook_image {
13089:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
13090:     my $filename = $env{'form.'.$caller.'.filename'};
13091:     my ($error,$url);
13092:     my ($width,$height) = (50,50);
13093:     if ($configuserok eq 'ok') {
13094:         if ($switchserver) {
13095:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
13096:                          $switchserver);
13097:         } elsif ($author_ok eq 'ok') {
13098:             my ($result,$imageurl) =
13099:                 &publishlogo($r,'upload',$caller,$dom,$confname,
13100:                              "$type/$cdom/$cnum/cover",$width,$height);
13101:             if ($result eq 'ok') {
13102:                 $url = $imageurl;
13103:             } else {
13104:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
13105:             }
13106:         } else {
13107:             $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);
13108:         }
13109:     } else {
13110:         $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);
13111:     }
13112:     return ($url,$error);
13113: }
13114: 
13115: sub modify_ltitools {
13116:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13117:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13118:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
13119:     my $confname = $dom.'-domainconfig';
13120:     my $servadm = $r->dir_config('lonAdmEMail');
13121:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13122:     my (%posslti,%possfield);
13123:     my @courseroles = ('cc','in','ta','ep','st');
13124:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
13125:     map { $posslti{$_} = 1; } @ltiroles;
13126:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
13127:     map { $possfield{$_} = 1; } @allfields;
13128:     my %lt = &ltitools_names(); 
13129:     if ($env{'form.ltitools_add'}) {
13130:         my $title = $env{'form.ltitools_add_title'};
13131:         $title =~ s/(`)/'/g;
13132:         ($newid,my $error) = &get_ltitools_id($dom,$title);
13133:         if ($newid) {
13134:             my $position = $env{'form.ltitools_add_pos'};
13135:             $position =~ s/\D+//g;
13136:             if ($position ne '') {
13137:                 $allpos[$position] = $newid;
13138:             }
13139:             $changes{$newid} = 1;
13140:             foreach my $item ('title','url','key','secret','lifetime') {
13141:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
13142:                 if ($item eq 'lifetime') {
13143:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
13144:                 }
13145:                 if ($env{'form.ltitools_add_'.$item}) {
13146:                     if (($item eq 'key') || ($item eq 'secret')) {
13147:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13148:                     } else {
13149:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13150:                     }
13151:                 }
13152:             }
13153:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
13154:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
13155:             }
13156:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
13157:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
13158:             }
13159:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
13160:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
13161:             } else {
13162:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
13163:             }
13164:             foreach my $item ('width','height','linktext','explanation') {
13165:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
13166:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
13167:                 if (($item eq 'width') || ($item eq 'height')) {
13168:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
13169:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
13170:                     }
13171:                 } else {
13172:                     if ($env{'form.ltitools_add_'.$item} ne '') {
13173:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
13174:                     }
13175:                 }
13176:             }
13177:             if ($env{'form.ltitools_add_target'} eq 'window') {
13178:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13179:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
13180:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13181:             } else {
13182:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
13183:             }
13184:             foreach my $item ('passback','roster') {
13185:                 if ($env{'form.ltitools_'.$item.'_add'}) {
13186:                     $confhash{$newid}{$item} = 1;
13187:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
13188:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
13189:                         $lifetime =~ s/^\s+|\s+$//g;
13190:                         if ($lifetime =~ /^\d+\.?\d*$/) {
13191:                             $confhash{$newid}{$item.'valid'} = $lifetime;
13192:                         }
13193:                     }
13194:                 }
13195:             }
13196:             if ($env{'form.ltitools_add_image.filename'} ne '') {
13197:                 my ($imageurl,$error) =
13198:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
13199:                                             $configuserok,$switchserver,$author_ok);
13200:                 if ($imageurl) {
13201:                     $confhash{$newid}{'image'} = $imageurl;
13202:                 }
13203:                 if ($error) {
13204:                     &Apache::lonnet::logthis($error);
13205:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13206:                 }
13207:             }
13208:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
13209:             foreach my $field (@fields) {
13210:                 if ($possfield{$field}) {
13211:                     if ($field eq 'roles') {
13212:                         foreach my $role (@courseroles) {
13213:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
13214:                             if (($choice ne '') && ($posslti{$choice})) {
13215:                                 $confhash{$newid}{'roles'}{$role} = $choice;
13216:                                 if ($role eq 'cc') {
13217:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
13218:                                 }
13219:                             }
13220:                         }
13221:                     } else {
13222:                         $confhash{$newid}{'fields'}{$field} = 1;
13223:                     }
13224:                 }
13225:             }
13226:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
13227:                 if ($confhash{$newid}{'fields'}{'user'}) {
13228:                     if ($env{'form.ltitools_userincdom_add'}) {
13229:                         $confhash{$newid}{'incdom'} = 1;
13230:                     }
13231:                 }
13232:             }
13233:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
13234:             foreach my $item (@courseconfig) {
13235:                 $confhash{$newid}{'crsconf'}{$item} = 1;
13236:             }
13237:             if ($env{'form.ltitools_add_custom'}) {
13238:                 my $name = $env{'form.ltitools_add_custom_name'};
13239:                 my $value = $env{'form.ltitools_add_custom_value'};
13240:                 $value =~ s/(`)/'/g;
13241:                 $name =~ s/(`)/'/g;
13242:                 $confhash{$newid}{'custom'}{$name} = $value;
13243:             }
13244:         } else {
13245:             my $error = &mt('Failed to acquire unique ID for new external tool');   
13246:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13247:         }
13248:     }
13249:     if (ref($domconfig{$action}) eq 'HASH') {
13250:         my %deletions;
13251:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
13252:         if (@todelete) {
13253:             map { $deletions{$_} = 1; } @todelete;
13254:         }
13255:         my %customadds;
13256:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
13257:         if (@newcustom) {
13258:             map { $customadds{$_} = 1; } @newcustom;
13259:         } 
13260:         my %imgdeletions;
13261:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
13262:         if (@todeleteimages) {
13263:             map { $imgdeletions{$_} = 1; } @todeleteimages;
13264:         }
13265:         my $maxnum = $env{'form.ltitools_maxnum'};
13266:         for (my $i=0; $i<=$maxnum; $i++) {
13267:             my $itemid = $env{'form.ltitools_id_'.$i};
13268:             $itemid =~ s/\D+//g;
13269:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13270:                 if ($deletions{$itemid}) {
13271:                     if ($domconfig{$action}{$itemid}{'image'}) {
13272:                         #FIXME need to obsolete item in RES space
13273:                     }
13274:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
13275:                     next;
13276:                 } else {
13277:                     my $newpos = $env{'form.ltitools_'.$itemid};
13278:                     $newpos =~ s/\D+//g;
13279:                     foreach my $item ('title','url','lifetime') {
13280:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13281:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
13282:                             $changes{$itemid} = 1;
13283:                         }
13284:                     }
13285:                     foreach my $item ('key','secret') {
13286:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13287:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
13288:                             $changes{$itemid} = 1;
13289:                         }
13290:                     }
13291:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
13292:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
13293:                     }
13294:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
13295:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
13296:                     }
13297:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
13298:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
13299:                     } else {
13300:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
13301:                     }
13302:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
13303:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
13304:                             $changes{$itemid} = 1;
13305:                         }
13306:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
13307:                         $changes{$itemid} = 1;
13308:                     }
13309:                     foreach my $size ('width','height') {
13310:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
13311:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
13312:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
13313:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
13314:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13315:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
13316:                                     $changes{$itemid} = 1;
13317:                                 }
13318:                             } else {
13319:                                 $changes{$itemid} = 1;
13320:                             }
13321:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13322:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
13323:                                 $changes{$itemid} = 1;
13324:                             }
13325:                         }
13326:                     }
13327:                     foreach my $item ('linktext','explanation') {
13328:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
13329:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
13330:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
13331:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13332:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13333:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
13334:                                     $changes{$itemid} = 1;
13335:                                 }
13336:                             } else {
13337:                                 $changes{$itemid} = 1;
13338:                             }
13339:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13340:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
13341:                                 $changes{$itemid} = 1;
13342:                             }
13343:                         }
13344:                     }
13345:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
13346:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13347:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
13348:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13349:                     } else {
13350:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
13351:                     }
13352:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13353:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
13354:                             $changes{$itemid} = 1;
13355:                         }
13356:                     } else {
13357:                         $changes{$itemid} = 1;
13358:                     }
13359:                     foreach my $extra ('passback','roster') {
13360:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
13361:                             $confhash{$itemid}{$extra} = 1;
13362:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
13363:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
13364:                                 $lifetime =~ s/^\s+|\s+$//g;
13365:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
13366:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
13367:                                 }
13368:                             }
13369:                         }
13370:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
13371:                             $changes{$itemid} = 1;
13372:                         }
13373:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
13374:                             $changes{$itemid} = 1;
13375:                         }
13376:                     }
13377:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
13378:                     foreach my $item ('label','title','target','linktext','explanation','append') {
13379:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
13380:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
13381:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
13382:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
13383:                                     $changes{$itemid} = 1;
13384:                                 }
13385:                             } else {
13386:                                 $changes{$itemid} = 1;
13387:                             }
13388:                         }
13389:                     }
13390:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
13391:                     foreach my $field (@fields) {
13392:                         if ($possfield{$field}) {
13393:                             if ($field eq 'roles') {
13394:                                 foreach my $role (@courseroles) {
13395:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
13396:                                     if (($choice ne '') && ($posslti{$choice})) {
13397:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
13398:                                         if ($role eq 'cc') {
13399:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
13400:                                         }
13401:                                     }
13402:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
13403:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
13404:                                             $changes{$itemid} = 1;
13405:                                         }
13406:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
13407:                                         $changes{$itemid} = 1;
13408:                                     }
13409:                                 }
13410:                             } else {
13411:                                 $confhash{$itemid}{'fields'}{$field} = 1;
13412:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
13413:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
13414:                                         $changes{$itemid} = 1;
13415:                                     }
13416:                                 } else {
13417:                                     $changes{$itemid} = 1;
13418:                                 }
13419:                             }
13420:                         }
13421:                     }
13422:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
13423:                         if ($confhash{$itemid}{'fields'}{'user'}) {
13424:                             if ($env{'form.ltitools_userincdom_'.$i}) {
13425:                                 $confhash{$itemid}{'incdom'} = 1;
13426:                             }
13427:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
13428:                                 $changes{$itemid} = 1;
13429:                             }
13430:                         }
13431:                     }
13432:                     $allpos[$newpos] = $itemid;
13433:                 }
13434:                 if ($imgdeletions{$itemid}) {
13435:                     $changes{$itemid} = 1;
13436:                     #FIXME need to obsolete item in RES space
13437:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
13438:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
13439:                                                                  $itemid,$configuserok,$switchserver,
13440:                                                                  $author_ok);
13441:                     if ($imgurl) {
13442:                         $confhash{$itemid}{'image'} = $imgurl;
13443:                         $changes{$itemid} = 1;
13444:                     }
13445:                     if ($error) {
13446:                         &Apache::lonnet::logthis($error);
13447:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13448:                     }
13449:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
13450:                     $confhash{$itemid}{'image'} =
13451:                        $domconfig{$action}{$itemid}{'image'};
13452:                 }
13453:                 if ($customadds{$i}) {
13454:                     my $name = $env{'form.ltitools_custom_name_'.$i};
13455:                     $name =~ s/(`)/'/g;
13456:                     $name =~ s/^\s+//;
13457:                     $name =~ s/\s+$//;
13458:                     my $value = $env{'form.ltitools_custom_value_'.$i};
13459:                     $value =~ s/(`)/'/g;
13460:                     $value =~ s/^\s+//;
13461:                     $value =~ s/\s+$//;
13462:                     if ($name ne '') {
13463:                         $confhash{$itemid}{'custom'}{$name} = $value;
13464:                         $changes{$itemid} = 1;
13465:                     }
13466:                 }
13467:                 my %customdels;
13468:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
13469:                 if (@customdeletions) {
13470:                     $changes{$itemid} = 1;
13471:                 }
13472:                 map { $customdels{$_} = 1; } @customdeletions;
13473:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
13474:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
13475:                         unless ($customdels{$key}) {
13476:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
13477:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
13478:                             }
13479:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
13480:                                 $changes{$itemid} = 1;
13481:                             }
13482:                         }
13483:                     }
13484:                 }
13485:                 unless ($changes{$itemid}) {
13486:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
13487:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
13488:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
13489:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
13490:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
13491:                                         $changes{$itemid} = 1;
13492:                                         last;
13493:                                     }
13494:                                 }
13495:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
13496:                                 $changes{$itemid} = 1;
13497:                             }
13498:                         }
13499:                         last if ($changes{$itemid});
13500:                     }
13501:                 }
13502:             }
13503:         }
13504:     }
13505:     if (@allpos > 0) {
13506:         my $idx = 0;
13507:         foreach my $itemid (@allpos) {
13508:             if ($itemid ne '') {
13509:                 $confhash{$itemid}{'order'} = $idx;
13510:                 if (ref($domconfig{$action}) eq 'HASH') {
13511:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13512:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
13513:                             $changes{$itemid} = 1;
13514:                         }
13515:                     }
13516:                 }
13517:                 $idx ++;
13518:             }
13519:         }
13520:     }
13521:     my %ltitoolshash = (
13522:                           $action => { %confhash }
13523:                        );
13524:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
13525:                                              $dom);
13526:     if ($putresult eq 'ok') {
13527:         my %ltienchash = (
13528:                              $action => { %encconfig }
13529:                          );
13530:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
13531:         if (keys(%changes) > 0) {
13532:             my $cachetime = 24*60*60;
13533:             my %ltiall = %confhash;
13534:             foreach my $id (keys(%ltiall)) {
13535:                 if (ref($encconfig{$id}) eq 'HASH') {
13536:                     foreach my $item ('key','secret') {
13537:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
13538:                     }
13539:                 }
13540:             }
13541:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
13542:             if (ref($lastactref) eq 'HASH') {
13543:                 $lastactref->{'ltitools'} = 1;
13544:             }
13545:             $resulttext = &mt('Changes made:').'<ul>';
13546:             my %bynum;
13547:             foreach my $itemid (sort(keys(%changes))) {
13548:                 my $position = $confhash{$itemid}{'order'};
13549:                 $bynum{$position} = $itemid;
13550:             }
13551:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13552:                 my $itemid = $bynum{$pos}; 
13553:                 if (ref($confhash{$itemid}) ne 'HASH') {
13554:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13555:                 } else {
13556:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
13557:                     if ($confhash{$itemid}{'image'}) {
13558:                         $resulttext .= '&nbsp;'.
13559:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
13560:                                        ' alt="'.&mt('Tool Provider icon').'" />';
13561:                     }
13562:                     $resulttext .= '</li><ul>';
13563:                     my $position = $pos + 1;
13564:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13565:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
13566:                         if ($confhash{$itemid}{$item} ne '') {
13567:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
13568:                         }
13569:                     }
13570:                     if ($encconfig{$itemid}{'key'} ne '') {
13571:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
13572:                     }
13573:                     if ($encconfig{$itemid}{'secret'} ne '') {
13574:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
13575:                         my $num = length($encconfig{$itemid}{'secret'});
13576:                         $resulttext .= ('*'x$num).'</li>';
13577:                     }
13578:                     $resulttext .= '<li>'.&mt('Configurable in course:');
13579:                     my @possconfig = ('label','title','target','linktext','explanation','append');
13580:                     my $numconfig = 0; 
13581:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
13582:                         foreach my $item (@possconfig) {
13583:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
13584:                                 $numconfig ++;
13585:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
13586:                             }
13587:                         }
13588:                     }
13589:                     if (!$numconfig) {
13590:                         $resulttext .= '&nbsp;'.&mt('None');
13591:                     }
13592:                     $resulttext .= '</li>';
13593:                     foreach my $item ('passback','roster') {
13594:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
13595:                         if ($confhash{$itemid}{$item}) {
13596:                             $resulttext .= &mt('Yes');
13597:                             if ($confhash{$itemid}{$item.'valid'}) {
13598:                                 if ($item eq 'passback') {
13599:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
13600:                                                            $confhash{$itemid}{$item.'valid'});
13601:                                 } else {
13602:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
13603:                                                            $confhash{$itemid}{$item.'valid'});
13604:                                 }
13605:                             }
13606:                         } else {
13607:                             $resulttext .= &mt('No');
13608:                         }
13609:                         $resulttext .= '</li>';
13610:                     }
13611:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
13612:                         my $displaylist;
13613:                         if ($confhash{$itemid}{'display'}{'target'}) {
13614:                             $displaylist = &mt('Display target').':&nbsp;'.
13615:                                            $confhash{$itemid}{'display'}{'target'}.',';
13616:                         }
13617:                         foreach my $size ('width','height') { 
13618:                             if ($confhash{$itemid}{'display'}{$size}) {
13619:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
13620:                                                 $confhash{$itemid}{'display'}{$size}.',';
13621:                             }
13622:                         }
13623:                         if ($displaylist) {
13624:                             $displaylist =~ s/,$//;
13625:                             $resulttext .= '<li>'.$displaylist.'</li>';
13626:                         }
13627:                         foreach my $item ('linktext','explanation') {
13628:                             if ($confhash{$itemid}{'display'}{$item}) {
13629:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
13630:                             }
13631:                         }
13632:                     }
13633:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
13634:                         my $fieldlist;
13635:                         foreach my $field (@allfields) {
13636:                             if ($confhash{$itemid}{'fields'}{$field}) {
13637:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
13638:                             }
13639:                         }
13640:                         if ($fieldlist) {
13641:                             $fieldlist =~ s/,$//;
13642:                             if ($confhash{$itemid}{'fields'}{'user'}) {
13643:                                 if ($confhash{$itemid}{'incdom'}) {
13644:                                     $fieldlist .= ' ('.&mt('username:domain').')';
13645:                                 } else {
13646:                                     $fieldlist .= ' ('.&mt('username').')';
13647:                                 }
13648:                             }
13649:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
13650:                         }
13651:                     }
13652:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
13653:                         my $rolemaps;
13654:                         foreach my $role (@courseroles) {
13655:                             if ($confhash{$itemid}{'roles'}{$role}) {
13656:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
13657:                                              $confhash{$itemid}{'roles'}{$role}.',';
13658:                             }
13659:                         }
13660:                         if ($rolemaps) {
13661:                             $rolemaps =~ s/,$//; 
13662:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
13663:                         }
13664:                     }
13665:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
13666:                         my $customlist;
13667:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
13668:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
13669:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
13670:                             } 
13671:                         }
13672:                         if ($customlist) {
13673:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
13674:                         }
13675:                     } 
13676:                     $resulttext .= '</ul></li>';
13677:                 }
13678:             }
13679:             $resulttext .= '</ul>';
13680:         } else {
13681:             $resulttext = &mt('No changes made.');
13682:         }
13683:     } else {
13684:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13685:     }
13686:     if ($errors) {
13687:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13688:                        $errors.'</ul>';
13689:     }
13690:     return $resulttext;
13691: }
13692: 
13693: sub process_ltitools_image {
13694:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
13695:     my $filename = $env{'form.'.$caller.'.filename'};
13696:     my ($error,$url);
13697:     my ($width,$height) = (21,21);
13698:     if ($configuserok eq 'ok') {
13699:         if ($switchserver) {
13700:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
13701:                          $switchserver);
13702:         } elsif ($author_ok eq 'ok') {
13703:             my ($result,$imageurl,$madethumb) =
13704:                 &publishlogo($r,'upload',$caller,$dom,$confname,
13705:                              "ltitools/$itemid/icon",$width,$height);
13706:             if ($result eq 'ok') {
13707:                 if ($madethumb) {
13708:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
13709:                     my $imagethumb = "$path/tn-".$imagefile;
13710:                     $url = $imagethumb;
13711:                 } else {
13712:                     $url = $imageurl;
13713:                 }
13714:             } else {
13715:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
13716:             }
13717:         } else {
13718:             $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);
13719:         }
13720:     } else {
13721:         $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);
13722:     }
13723:     return ($url,$error);
13724: }
13725: 
13726: sub get_ltitools_id {
13727:     my ($cdom,$title) = @_;
13728:     # get lock on ltitools db
13729:     my $lockhash = {
13730:                       lock => $env{'user.name'}.
13731:                               ':'.$env{'user.domain'},
13732:                    };
13733:     my $tries = 0;
13734:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
13735:     my ($id,$error);
13736:  
13737:     while (($gotlock ne 'ok') && ($tries<10)) {
13738:         $tries ++;
13739:         sleep (0.1);
13740:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
13741:     }
13742:     if ($gotlock eq 'ok') {
13743:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
13744:         if ($currids{'lock'}) {
13745:             delete($currids{'lock'});
13746:             if (keys(%currids)) {
13747:                 my @curr = sort { $a <=> $b } keys(%currids);
13748:                 if ($curr[-1] =~ /^\d+$/) {
13749:                     $id = 1 + $curr[-1];
13750:                 }
13751:             } else {
13752:                 $id = 1;
13753:             }
13754:             if ($id) {
13755:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13756:                     $error = 'nostore';
13757:                 }
13758:             } else {
13759:                 $error = 'nonumber';
13760:             }
13761:         }
13762:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
13763:     } else {
13764:         $error = 'nolock';
13765:     }
13766:     return ($id,$error);
13767: }
13768: 
13769: sub modify_proctoring {
13770:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13771:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13772:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
13773:     my $confname = $dom.'-domainconfig';
13774:     my $servadm = $r->dir_config('lonAdmEMail');
13775:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13776:     my %providernames = &proctoring_providernames();
13777:     my $maxnum = scalar(keys(%providernames));
13778: 
13779:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
13780:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
13781:     if (ref($requref) eq 'HASH') {
13782:         %requserfields = %{$requref};
13783:     }
13784:     if (ref($opturef) eq 'HASH') {
13785:         %optuserfields = %{$opturef};
13786:     }
13787:     if (ref($defref) eq 'HASH') {
13788:         %defaults = %{$defref};
13789:     }
13790:     if (ref($extref) eq 'HASH') {
13791:         %extended = %{$extref};
13792:     }
13793:     if (ref($crsref) eq 'HASH') {
13794:         %crsconf = %{$crsref};
13795:     }
13796:     if (ref($rolesref) eq 'ARRAY') {
13797:         @courseroles = @{$rolesref};
13798:     }
13799:     if (ref($ltiref) eq 'ARRAY') {
13800:         @ltiroles = @{$ltiref};
13801:     }
13802: 
13803:     if (ref($domconfig{$action}) eq 'HASH') {
13804:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
13805:         if (@todeleteimages) {
13806:             map { $imgdeletions{$_} = 1; } @todeleteimages;
13807:         }
13808:     }
13809:     my %customadds;
13810:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
13811:     if (@newcustom) {
13812:         map { $customadds{$_} = 1; } @newcustom;
13813:     }
13814:     foreach my $provider (sort(keys(%providernames))) {
13815:         $confhash{$provider} = {};
13816:         my $pos = $env{'form.proctoring_pos_'.$provider};
13817:         $pos =~ s/\D+//g;
13818:         $allpos[$pos] = $provider;
13819:         my (%current,%currentenc);
13820:         my $showroles = 0;
13821:         if (ref($domconfig{$action}) eq 'HASH') {
13822:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
13823:                 %current = %{$domconfig{$action}{$provider}};
13824:                 foreach my $item ('key','secret') { 
13825:                     $currentenc{$item} = $current{$item};
13826:                     delete($current{$item});
13827:                 }
13828:             }
13829:         }
13830:         if ($env{'form.proctoring_available_'.$provider}) {
13831:             $confhash{$provider}{'available'} = 1;
13832:             unless ($current{'available'}) {
13833:                 $changes{$provider} = 1;
13834:             }
13835:         } else {
13836:             %{$confhash{$provider}} = %current;
13837:             %{$encconfhash{$provider}} = %currentenc;
13838:             $confhash{$provider}{'available'} = 0;
13839:             if ($current{'available'}) {
13840:                 $changes{$provider} = 1;
13841:             }
13842:         }
13843:         if ($confhash{$provider}{'available'}) {
13844:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
13845:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
13846:                 if ($field eq 'lifetime') {
13847:                     if ($possval =~ /^\d+$/) {
13848:                         $confhash{$provider}{$field} = $possval;
13849:                     }
13850:                 } elsif ($field eq 'version') {
13851:                     if ($possval =~ /^\d+\.\d+$/) {
13852:                         $confhash{$provider}{$field} = $possval;
13853:                     }
13854:                 } elsif ($field eq 'sigmethod') {
13855:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
13856:                         $confhash{$provider}{$field} = $possval;
13857:                     }
13858:                 } elsif ($field eq 'url') {
13859:                     $confhash{$provider}{$field} = $possval;
13860:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
13861:                     $encconfhash{$provider}{$field} = $possval;
13862:                     unless ($currentenc{$field} eq $possval) {
13863:                         $changes{$provider} = 1;
13864:                     }
13865:                 }
13866:                 unless (($field eq 'key') || ($field eq 'secret')) {
13867:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
13868:                         $changes{$provider} = 1;
13869:                     }
13870:                 }
13871:             }
13872:             if ($imgdeletions{$provider}) {
13873:                 $changes{$provider} = 1;
13874:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
13875:                 my ($imageurl,$error) =
13876:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
13877:                                               $configuserok,$switchserver,$author_ok);
13878:                 if ($imageurl) {
13879:                     $confhash{$provider}{'image'} = $imageurl;
13880:                     $changes{$provider} = 1; 
13881:                 }
13882:                 if ($error) {
13883:                     &Apache::lonnet::logthis($error);
13884:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13885:                 }
13886:             } elsif (exists($current{'image'})) {
13887:                 $confhash{$provider}{'image'} = $current{'image'};
13888:             }
13889:             if (ref($requserfields{$provider}) eq 'ARRAY') {
13890:                 if (@{$requserfields{$provider}} > 0) {
13891:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
13892:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
13893:                             $confhash{$provider}{'incdom'} = 1;
13894:                         }
13895:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
13896:                             $changes{$provider} = 1;
13897:                         }
13898:                     }
13899:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
13900:                         $showroles = 1;
13901:                     }
13902:                 }
13903:             }
13904:             $confhash{$provider}{'fields'} = [];
13905:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
13906:                 if (@{$optuserfields{$provider}} > 0) {
13907:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
13908:                     foreach my $field (@{$optuserfields{$provider}}) {
13909:                         if (grep(/^\Q$field\E$/,@optfields)) {
13910:                             push(@{$confhash{$provider}{'fields'}},$field);
13911:                         }
13912:                     }
13913:                 }
13914:                 if (ref($current{'fields'}) eq 'ARRAY') {
13915:                     unless ($changes{$provider}) {
13916:                         my @new = sort(@{$confhash{$provider}{'fields'}});
13917:                         my @old = sort(@{$current{'fields'}}); 
13918:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
13919:                         if (@diffs) {
13920:                             $changes{$provider} = 1;
13921:                         }
13922:                     }
13923:                 } elsif (@{$confhash{$provider}{'fields'}}) {
13924:                     $changes{$provider} = 1;
13925:                 }
13926:             }
13927:             if (ref($defaults{$provider}) eq 'ARRAY') {  
13928:                 if (@{$defaults{$provider}} > 0) {
13929:                     my %options;
13930:                     if (ref($extended{$provider}) eq 'HASH') {
13931:                         %options = %{$extended{$provider}};
13932:                     }
13933:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
13934:                     foreach my $field (@{$defaults{$provider}}) {
13935:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
13936:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
13937:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
13938:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
13939:                             }
13940:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
13941:                             foreach my $inner (keys(%{$options{$field}})) {
13942:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
13943:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
13944:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
13945:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
13946:                                     }
13947:                                 } else {
13948:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
13949:                                 }
13950:                             }
13951:                         } else {
13952:                             if (grep(/^\Q$field\E$/,@checked)) {
13953:                                 push(@{$confhash{$provider}{'defaults'}},$field);
13954:                             }
13955:                         }
13956:                     }
13957:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
13958:                         if (ref($current{'defaults'}) eq 'ARRAY') {
13959:                             unless ($changes{$provider}) {
13960:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
13961:                                 my @old = sort(@{$current{'defaults'}});
13962:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
13963:                                 if (@diffs) {
13964:                                     $changes{$provider} = 1; 
13965:                                 }
13966:                             }
13967:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
13968:                             if (@{$current{'defaults'}}) {
13969:                                 $changes{$provider} = 1;
13970:                             }
13971:                         }
13972:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
13973:                         if (ref($current{'defaults'}) eq 'HASH') {
13974:                             unless ($changes{$provider}) {
13975:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
13976:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
13977:                                         $changes{$provider} = 1;
13978:                                         last;
13979:                                     }
13980:                                 }
13981:                             }
13982:                             unless ($changes{$provider}) {
13983:                                 foreach my $key (keys(%{$current{'defaults'}})) {
13984:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
13985:                                         $changes{$provider} = 1;
13986:                                         last;
13987:                                     }
13988:                                 }
13989:                             }
13990:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
13991:                             $changes{$provider} = 1;
13992:                         }
13993:                     }
13994:                 }
13995:             }
13996:             if (ref($crsconf{$provider}) eq 'ARRAY') {
13997:                 if (@{$crsconf{$provider}} > 0) {
13998:                     $confhash{$provider}{'crsconf'} = [];
13999:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
14000:                     foreach my $crsfield (@{$crsconf{$provider}}) {
14001:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
14002:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
14003:                         }
14004:                     }
14005:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
14006:                         unless ($changes{$provider}) {  
14007:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
14008:                             my @old = sort(@{$current{'crsconf'}});
14009:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
14010:                             if (@diffs) {
14011:                                 $changes{$provider} = 1;
14012:                             }
14013:                         }
14014:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
14015:                         $changes{$provider} = 1;
14016:                     }
14017:                 }
14018:             }
14019:             if ($showroles) {
14020:                 $confhash{$provider}{'roles'} = {};
14021:                 foreach my $role (@courseroles) {
14022:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
14023:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
14024:                         $confhash{$provider}{'roles'}{$role} = $poss;
14025:                     }
14026:                 }
14027:                 unless ($changes{$provider}) {
14028:                     if (ref($current{'roles'}) eq 'HASH') {
14029:                         foreach my $role (keys(%{$current{'roles'}})) {
14030:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
14031:                                 $changes{$provider} = 1;
14032:                                 last
14033:                             }
14034:                         }
14035:                         unless ($changes{$provider}) {
14036:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
14037:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
14038:                                     $changes{$provider} = 1;
14039:                                     last;
14040:                                 }
14041:                             }
14042:                         }
14043:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
14044:                         $changes{$provider} = 1;
14045:                     }
14046:                 }
14047:             }
14048:             if (ref($current{'custom'}) eq 'HASH') {
14049:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
14050:                 foreach my $key (keys(%{$current{'custom'}})) {
14051:                     if (grep(/^\Q$key\E$/,@customdels)) {
14052:                         $changes{$provider} = 1;
14053:                     } else {
14054:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
14055:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
14056:                             $changes{$provider} = 1;
14057:                         }
14058:                     }
14059:                 }
14060:             }
14061:             if ($customadds{$provider}) {
14062:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
14063:                 $name =~ s/(`)/'/g;
14064:                 $name =~ s/^\s+//;
14065:                 $name =~ s/\s+$//;
14066:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
14067:                 $value =~ s/(`)/'/g;
14068:                 $value =~ s/^\s+//;
14069:                 $value =~ s/\s+$//;
14070:                 if ($name ne '') {
14071:                     $confhash{$provider}{'custom'}{$name} = $value;
14072:                     $changes{$provider} = 1;
14073:                 }
14074:             }
14075:         }
14076:     }
14077:     if (@allpos > 0) {
14078:         my $idx = 0;
14079:         foreach my $provider (@allpos) {
14080:             if ($provider ne '') {
14081:                 $confhash{$provider}{'order'} = $idx;
14082:                 unless ($changes{$provider}) {
14083:                     if (ref($domconfig{$action}) eq 'HASH') {
14084:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14085:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
14086:                                 $changes{$provider} = 1;
14087:                             }
14088:                         }
14089:                     }
14090:                 }
14091:                 $idx ++;
14092:             }
14093:         }
14094:     }
14095:     my %proc_hash = (
14096:                           $action => { %confhash }
14097:                        );
14098:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
14099:                                              $dom);
14100:     if ($putresult eq 'ok') {
14101:         my %proc_enchash = (
14102:                              $action => { %encconfhash }
14103:                          );
14104:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom);
14105:         if (keys(%changes) > 0) {
14106:             my $cachetime = 24*60*60;
14107:             my %procall = %confhash;
14108:             foreach my $provider (keys(%procall)) {
14109:                 if (ref($encconfhash{$provider}) eq 'HASH') {
14110:                     foreach my $key ('key','secret') {
14111:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
14112:                     }
14113:                 }
14114:             }
14115:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
14116:             if (ref($lastactref) eq 'HASH') {
14117:                 $lastactref->{'proctoring'} = 1;
14118:             }
14119:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
14120:             my %bynum;
14121:             foreach my $provider (sort(keys(%changes))) {
14122:                 my $position = $confhash{$provider}{'order'};
14123:                 $bynum{$position} = $provider;
14124:             }
14125:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14126:                 my $provider = $bynum{$pos};
14127:                 my %lt = &proctoring_titles($provider);
14128:                 my %fieldtitles = &proctoring_fieldtitles($provider);
14129:                 if (!$confhash{$provider}{'available'}) {
14130:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
14131:                 } else {
14132:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
14133:                     if ($confhash{$provider}{'image'}) {
14134:                         $resulttext .= '&nbsp;'.
14135:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
14136:                                        ' alt="'.&mt('Proctoring icon').'" />';
14137:                     }
14138:                     $resulttext .= '<ul>';
14139:                     my $position = $pos + 1;
14140:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
14141:                     foreach my $key ('version','sigmethod','url','lifetime') {
14142:                         if ($confhash{$provider}{$key} ne '') {
14143:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
14144:                         }
14145:                     }
14146:                     if ($encconfhash{$provider}{'key'} ne '') {
14147:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
14148:                     }
14149:                     if ($encconfhash{$provider}{'secret'} ne '') {
14150:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
14151:                         my $num = length($encconfhash{$provider}{'secret'});
14152:                         $resulttext .= ('*'x$num).'</li>';
14153:                     }
14154:                     my (@fields,$showroles);
14155:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14156:                         push(@fields,@{$requserfields{$provider}});
14157:                     }
14158:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
14159:                         push(@fields,@{$confhash{$provider}{'fields'}});
14160:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
14161:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
14162:                     }
14163:                     if (@fields) {
14164:                         if (grep(/^roles$/,@fields)) {
14165:                             $showroles = 1;
14166:                         }
14167:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
14168:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
14169:                     }
14170:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14171:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
14172:                             if ($confhash{$provider}{'incdom'}) {
14173:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
14174:                             } else { 
14175:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
14176:                             }
14177:                         }
14178:                     }
14179:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
14180:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
14181:                             $resulttext .= '<li>'.$lt{'defa'};
14182:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
14183:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
14184:                             }
14185:                             $resulttext =~ s/,$//;
14186:                             $resulttext .= '</li>';
14187:                         }
14188:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
14189:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
14190:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
14191:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
14192:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
14193:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
14194:                                 }
14195:                             }
14196:                             $resulttext .= '</ul></li>';
14197:                         }
14198:                     }
14199:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
14200:                         if (@{$crsconf{$provider}} > 0) {
14201:                             $resulttext .= '<li>'.&mt('Configurable in course:');
14202:                             my $numconfig = 0;
14203:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
14204:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
14205:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
14206:                                         $numconfig ++;
14207:                                         if ($provider eq 'examity') {
14208:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
14209:                                         } else {
14210:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
14211:                                         }
14212:                                     }
14213:                                     $resulttext =~ s/,$//;
14214:                                 }
14215:                             }
14216:                             if (!$numconfig) {
14217:                                 $resulttext .= '&nbsp;'.&mt('None');
14218:                             }
14219:                             $resulttext .= '</li>';
14220:                         }
14221:                     }
14222:                     if ($showroles) {
14223:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
14224:                             my $rolemaps;
14225:                             foreach my $role (@courseroles) {
14226:                                 if ($confhash{$provider}{'roles'}{$role}) {
14227:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
14228:                                                  $confhash{$provider}{'roles'}{$role}.',';
14229:                                 }
14230:                             }
14231:                             if ($rolemaps) {
14232:                                 $rolemaps =~ s/,$//;
14233:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14234:                             }
14235:                         }
14236:                     }
14237:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
14238:                         my $customlist;
14239:                         if (keys(%{$confhash{$provider}{'custom'}})) {
14240:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
14241:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
14242:                             }
14243:                             $customlist =~ s/,$//;
14244:                         }
14245:                         if ($customlist) {
14246:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
14247:                         }
14248:                     } 
14249:                     $resulttext .= '</ul></li>';
14250:                 }
14251:             }
14252:             $resulttext .= '</ul>';
14253:         } else {
14254:             $resulttext = &mt('No changes made.');
14255:         }
14256:     } else {
14257:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14258:     }
14259:     if ($errors) {
14260:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14261:                        $errors.'</ul>';
14262:     }
14263:     return $resulttext;
14264: }
14265: 
14266: sub process_proctoring_image {
14267:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
14268:     my $filename = $env{'form.'.$caller.'.filename'};
14269:     my ($error,$url);
14270:     my ($width,$height) = (21,21);
14271:     if ($configuserok eq 'ok') {
14272:         if ($switchserver) {
14273:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
14274:                          $switchserver);
14275:         } elsif ($author_ok eq 'ok') {
14276:             my ($result,$imageurl,$madethumb) =
14277:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14278:                              "proctoring/$provider/icon",$width,$height);
14279:             if ($result eq 'ok') {
14280:                 if ($madethumb) {
14281:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
14282:                     my $imagethumb = "$path/tn-".$imagefile;
14283:                     $url = $imagethumb;
14284:                 } else {
14285:                     $url = $imageurl;
14286:                 }
14287:             } else {
14288:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14289:             }
14290:         } else {
14291:             $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);
14292:         }
14293:     } else {
14294:         $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);
14295:     }
14296:     return ($url,$error);
14297: }
14298: 
14299: sub modify_lti {
14300:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14301:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14302:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14303:     my (%posslti,%posslticrs,%posscrstype);
14304:     my @courseroles = ('cc','in','ta','ep','st');
14305:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
14306:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
14307:     my @coursetypes = ('official','unofficial','community','textbook','placement');
14308:     my %coursetypetitles = &Apache::lonlocal::texthash (
14309:                                official   => 'Official',
14310:                                unofficial => 'Unofficial',
14311:                                community  => 'Community',
14312:                                textbook   => 'Textbook',
14313:                                placement  => 'Placement Test',
14314:     );
14315:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14316:     my %lt = &lti_names();
14317:     map { $posslti{$_} = 1; } @ltiroles;
14318:     map { $posslticrs{$_} = 1; } @lticourseroles;
14319:     map { $posscrstype{$_} = 1; } @coursetypes;
14320: 
14321:     my %menutitles = &ltimenu_titles();
14322: 
14323:     my (@items,%deletions,%itemids);
14324:     if ($env{'form.lti_add'}) {
14325:         my $consumer = $env{'form.lti_consumer_add'};
14326:         $consumer =~ s/(`)/'/g;
14327:         ($newid,my $error) = &get_lti_id($dom,$consumer);
14328:         if ($newid) {
14329:             $itemids{'add'} = $newid;
14330:             push(@items,'add');
14331:             $changes{$newid} = 1;
14332:         } else {
14333:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
14334:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14335:         }
14336:     }
14337:     if (ref($domconfig{$action}) eq 'HASH') {
14338:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
14339:         if (@todelete) {
14340:             map { $deletions{$_} = 1; } @todelete;
14341:         }
14342:         my $maxnum = $env{'form.lti_maxnum'};
14343:         for (my $i=0; $i<=$maxnum; $i++) {
14344:             my $itemid = $env{'form.lti_id_'.$i};
14345:             $itemid =~ s/\D+//g;
14346:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14347:                 if ($deletions{$itemid}) {
14348:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
14349:                 } else {
14350:                    push(@items,$i);
14351:                    $itemids{$i} = $itemid;
14352:                 }
14353:             }
14354:         }
14355:     }
14356:     foreach my $idx (@items) {
14357:         my $itemid = $itemids{$idx};
14358:         next unless ($itemid);
14359:         my $position = $env{'form.lti_pos_'.$idx};
14360:         $position =~ s/\D+//g;
14361:         if ($position ne '') {
14362:             $allpos[$position] = $itemid;
14363:         }
14364:         foreach my $item ('consumer','key','secret','lifetime','requser') {
14365:             my $formitem = 'form.lti_'.$item.'_'.$idx;
14366:             $env{$formitem} =~ s/(`)/'/g;
14367:             if ($item eq 'lifetime') {
14368:                 $env{$formitem} =~ s/[^\d.]//g;
14369:             }
14370:             if ($env{$formitem} ne '') {
14371:                 if (($item eq 'key') || ($item eq 'secret')) {
14372:                     $encconfig{$itemid}{$item} = $env{$formitem};
14373:                 } else {
14374:                     $confhash{$itemid}{$item} = $env{$formitem};
14375:                     unless (($idx eq 'add') || ($changes{$itemid})) {
14376:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14377:                             $changes{$itemid} = 1;
14378:                         }
14379:                     }
14380:                 }
14381:             }
14382:         }
14383:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
14384:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
14385:         }
14386:         if ($confhash{$itemid}{'requser'}) {
14387:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
14388:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid'; 
14389:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
14390:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
14391:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
14392:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
14393:                 $mapuser =~ s/(`)/'/g;
14394:                 $mapuser =~ s/^\s+|\s+$//g; 
14395:                 $confhash{$itemid}{'mapuser'} = $mapuser; 
14396:             }
14397:             foreach my $ltirole (@lticourseroles) {
14398:                 my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
14399:                 if (grep(/^\Q$possrole\E$/,@courseroles)) {
14400:                     $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
14401:                 }
14402:             }
14403:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
14404:             my @makeuser;
14405:             foreach my $ltirole (sort(@possmakeuser)) {
14406:                 if ($posslti{$ltirole}) {
14407:                     push(@makeuser,$ltirole);
14408:                 }
14409:             }
14410:             $confhash{$itemid}{'makeuser'} = \@makeuser;
14411:             if (@makeuser) {
14412:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
14413:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
14414:                     $confhash{$itemid}{'lcauth'} = $lcauth;
14415:                     if ($lcauth ne 'internal') {
14416:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
14417:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
14418:                         $lcauthparm =~ s/`//g;
14419:                         if ($lcauthparm ne '') {
14420:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
14421:                         }
14422:                     }
14423:                 } else {
14424:                     $confhash{$itemid}{'lcauth'} = 'lti';
14425:                 }
14426:             }
14427:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
14428:             if (@possinstdata) {
14429:                 foreach my $field (@possinstdata) {
14430:                     if (exists($fieldtitles{$field})) {
14431:                         push(@{$confhash{$itemid}{'instdata'}});
14432:                     }
14433:                 }
14434:             }
14435:             if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
14436:                 ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
14437:                 $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
14438:             } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
14439:                 my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
14440:                 $mapcrs =~ s/(`)/'/g;
14441:                 $mapcrs =~ s/^\s+|\s+$//g;
14442:                 $confhash{$itemid}{'mapcrs'} = $mapcrs;
14443:             }
14444:             my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
14445:             my @crstypes;
14446:             foreach my $type (sort(@posstypes)) {
14447:                 if ($posscrstype{$type}) {
14448:                     push(@crstypes,$type);
14449:                 }
14450:             }
14451:             $confhash{$itemid}{'mapcrstype'} = \@crstypes;
14452:             if ($env{'form.lti_makecrs_'.$idx}) {
14453:                 $confhash{$itemid}{'makecrs'} = 1;
14454:             }
14455:             my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
14456:             my @selfenroll;
14457:             foreach my $type (sort(@possenroll)) {
14458:                 if ($posslticrs{$type}) {
14459:                     push(@selfenroll,$type);
14460:                 }
14461:             }
14462:             $confhash{$itemid}{'selfenroll'} = \@selfenroll;
14463:             if ($env{'form.lti_crssec_'.$idx}) {
14464:                 if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
14465:                     $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
14466:                 } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
14467:                     my $section = $env{'form.lti_customsection_'.$idx};
14468:                     $section =~ s/(`)/'/g;
14469:                     $section =~ s/^\s+|\s+$//g;
14470:                     if ($section ne '') {
14471:                         $confhash{$itemid}{'section'} = $section;
14472:                     }
14473:                 }
14474:             }
14475:             if ($env{'form.lti_callback_'.$idx}) {
14476:                 if ($env{'form.lti_callbackparam_'.$idx}) {
14477:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
14478:                     $callback =~ s/^\s+|\s+$//g;
14479:                     $confhash{$itemid}{'callback'} = $callback;
14480:                 }
14481:             }
14482:             foreach my $field ('passback','roster','topmenu','inlinemenu') {
14483:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
14484:                     $confhash{$itemid}{$field} = 1;
14485:                 }
14486:             }
14487:             if ($env{'form.lti_passback_'.$idx}) {
14488:                 if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
14489:                     $confhash{$itemid}{'passbackformat'} = '1.0';
14490:                 } else {
14491:                     $confhash{$itemid}{'passbackformat'} = '1.1';
14492:                 }
14493:             }
14494:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
14495:                 $confhash{$itemid}{lcmenu} = [];
14496:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
14497:                 foreach my $field (@possmenu) {
14498:                     if (exists($menutitles{$field})) {
14499:                         if ($field eq 'grades') {
14500:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
14501:                         }
14502:                         push(@{$confhash{$itemid}{lcmenu}},$field);
14503:                     }
14504:                 }
14505:             }
14506:             unless (($idx eq 'add') || ($changes{$itemid})) {
14507:                 foreach my $field ('mapuser','mapcrs','makecrs','section','passback','roster','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
14508:                     if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
14509:                         $changes{$itemid} = 1;
14510:                     }
14511:                 }
14512:                 unless ($changes{$itemid}) {
14513:                     if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
14514:                         if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
14515:                             $changes{$itemid} = 1;
14516:                         }
14517:                     }
14518:                 }
14519:                 foreach my $field ('makeuser','mapcrstype','selfenroll','instdata','lcmenu') {
14520:                     unless ($changes{$itemid}) {
14521:                         if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
14522:                             if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14523:                                 my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
14524:                                                                                $confhash{$itemid}{$field});
14525:                                 if (@diffs) {
14526:                                     $changes{$itemid} = 1;
14527:                                 }
14528:                             } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
14529:                                 $changes{$itemid} = 1;
14530:                             }
14531:                         } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14532:                             if (@{$confhash{$itemid}{$field}} > 0) {
14533:                                 $changes{$itemid} = 1;
14534:                             }
14535:                         }
14536:                     }
14537:                 }
14538:                 unless ($changes{$itemid}) {
14539:                     if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
14540:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14541:                             foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
14542:                                 if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
14543:                                     $confhash{$itemid}{'maproles'}{$ltirole}) {
14544:                                     $changes{$itemid} = 1;
14545:                                     last;
14546:                                 }
14547:                             }
14548:                             unless ($changes{$itemid}) {
14549:                                 foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
14550:                                     if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
14551:                                         $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
14552:                                         $changes{$itemid} = 1;
14553:                                         last;
14554:                                     }
14555:                                 }
14556:                             }
14557:                         } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
14558:                             $changes{$itemid} = 1;
14559:                         }
14560:                     } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14561:                         unless ($changes{$itemid}) {
14562:                             if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
14563:                                 $changes{$itemid} = 1;
14564:                             }
14565:                         }
14566:                     }
14567:                 }
14568:             }
14569:         }
14570:     }
14571:     if (@allpos > 0) {
14572:         my $idx = 0;
14573:         foreach my $itemid (@allpos) {
14574:             if ($itemid ne '') {
14575:                 $confhash{$itemid}{'order'} = $idx;
14576:                 if (ref($domconfig{$action}) eq 'HASH') {
14577:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14578:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
14579:                             $changes{$itemid} = 1;
14580:                         }
14581:                     }
14582:                 }
14583:                 $idx ++;
14584:             }
14585:         }
14586:     }
14587:     my %ltihash = (
14588:                           $action => { %confhash }
14589:                        );
14590:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,
14591:                                              $dom);
14592:     if ($putresult eq 'ok') {
14593:         my %ltienchash = (
14594:                              $action => { %encconfig }
14595:                          );
14596:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
14597:         if (keys(%changes) > 0) {
14598:             my $cachetime = 24*60*60;
14599:             my %ltiall = %confhash;
14600:             foreach my $id (keys(%ltiall)) {
14601:                 if (ref($encconfig{$id}) eq 'HASH') {
14602:                     foreach my $item ('key','secret') {
14603:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
14604:                     }
14605:                 }
14606:             }
14607:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
14608:             if (ref($lastactref) eq 'HASH') {
14609:                 $lastactref->{'lti'} = 1;
14610:             }
14611:             $resulttext = &mt('Changes made:').'<ul>';
14612:             my %bynum;
14613:             foreach my $itemid (sort(keys(%changes))) {
14614:                 my $position = $confhash{$itemid}{'order'};
14615:                 $bynum{$position} = $itemid;
14616:             }
14617:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14618:                 my $itemid = $bynum{$pos};
14619:                 if (ref($confhash{$itemid}) ne 'HASH') {
14620:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
14621:                 } else {
14622:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b></li><ul>';
14623:                     my $position = $pos + 1;
14624:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
14625:                     foreach my $item ('version','lifetime') {
14626:                         if ($confhash{$itemid}{$item} ne '') {
14627:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
14628:                         }
14629:                     }
14630:                     if ($encconfig{$itemid}{'key'} ne '') {
14631:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
14632:                     }
14633:                     if ($encconfig{$itemid}{'secret'} ne '') {
14634:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
14635:                         my $num = length($encconfig{$itemid}{'secret'});
14636:                         $resulttext .= ('*'x$num).'</li>';
14637:                     }
14638:                     if ($confhash{$itemid}{'requser'}) {
14639:                         if ($confhash{$itemid}{'mapuser'}) {
14640:                             my $shownmapuser;
14641:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
14642:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
14643:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
14644:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
14645:                             } else {
14646:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
14647:                             }
14648:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
14649:                         }
14650:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14651:                             my $rolemaps;
14652:                             foreach my $role (@ltiroles) {
14653:                                 if ($confhash{$itemid}{'maproles'}{$role}) {
14654:                                     $rolemaps .= ('&nbsp;'x2).$role.'='.
14655:                                                  &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
14656:                                                                             'Course').',';
14657:                                 }
14658:                             }
14659:                             if ($rolemaps) {
14660:                                 $rolemaps =~ s/,$//;
14661:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14662:                             }
14663:                         }
14664:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
14665:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
14666:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
14667:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
14668:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
14669:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
14670:                                 } else {
14671:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
14672:                                                        $confhash{$itemid}{'lcauth'});
14673:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
14674:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
14675:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
14676:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
14677:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
14678:                                         }
14679:                                     } else {
14680:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
14681:                                     }
14682:                                 }
14683:                                 $resulttext .= '</li>';
14684:                             } else {
14685:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
14686:                             }
14687:                         }
14688:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
14689:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
14690:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
14691:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
14692:                             } else {
14693:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
14694:                             }
14695:                         }
14696:                         if ($confhash{$itemid}{'mapcrs'}) {
14697:                             $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
14698:                         }
14699:                         if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
14700:                             if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
14701:                                 $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
14702:                                                join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
14703:                                                '</li>';
14704:                             } else {
14705:                                 $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
14706:                             }
14707:                         }
14708:                         if ($confhash{$itemid}{'makecrs'}) {
14709:                             $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
14710:                         } else {
14711:                             $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
14712:                         }
14713:                         if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
14714:                             if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
14715:                                 $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
14716:                                                           join(', ',@{$confhash{$itemid}{'selfenroll'}})).
14717:                                                '</li>';
14718:                             } else {
14719:                                 $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
14720:                             }
14721:                         }
14722:                         if ($confhash{$itemid}{'section'}) {
14723:                             if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
14724:                                 $resulttext .= '<li>'.&mt('User section from standard field:').
14725:                                                      ' (course_section_sourcedid)'.'</li>';  
14726:                             } else {
14727:                                 $resulttext .= '<li>'.&mt('User section from:').' '.
14728:                                                       $confhash{$itemid}{'section'}.'</li>';
14729:                             }
14730:                         } else {
14731:                             $resulttext .= '<li>'.&mt('No section assignment').'</li>';
14732:                         }
14733:                         if ($confhash{$itemid}{'callback'}) {
14734:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
14735:                         } else {
14736:                             $resulttext .= '<li>'.&mt('No callback to logout LON-CAPA session when user logs out of Comsumer');
14737:                         }
14738:                         foreach my $item ('passback','roster','topmenu','inlinemenu') {
14739:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
14740:                             if ($confhash{$itemid}{$item}) {
14741:                                 $resulttext .= &mt('Yes');
14742:                                 if ($item eq 'passback') {
14743:                                     if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
14744:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
14745:                                     } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
14746:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
14747:                                     }
14748:                                 }
14749:                             } else {
14750:                                 $resulttext .= &mt('No');
14751:                             }
14752:                             $resulttext .= '</li>';
14753:                         }
14754:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
14755:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
14756:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
14757:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
14758:                             } else {
14759:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
14760:                             }
14761:                         }
14762:                     }
14763:                     $resulttext .= '</ul></li>';
14764:                 }
14765:             }
14766:             $resulttext .= '</ul>';
14767:         } else {
14768:             $resulttext = &mt('No changes made.');
14769:         }
14770:     } else {
14771:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14772:     }
14773:     if ($errors) {
14774:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14775:                        $errors.'</ul>';
14776:     }
14777:     return $resulttext;
14778: }
14779: 
14780: sub get_lti_id {
14781:     my ($domain,$consumer) = @_;
14782:     # get lock on lti db
14783:     my $lockhash = {
14784:                       lock => $env{'user.name'}.
14785:                               ':'.$env{'user.domain'},
14786:                    };
14787:     my $tries = 0;
14788:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
14789:     my ($id,$error);
14790: 
14791:     while (($gotlock ne 'ok') && ($tries<10)) {
14792:         $tries ++;
14793:         sleep (0.1);
14794:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
14795:     }
14796:     if ($gotlock eq 'ok') {
14797:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
14798:         if ($currids{'lock'}) {
14799:             delete($currids{'lock'});
14800:             if (keys(%currids)) {
14801:                 my @curr = sort { $a <=> $b } keys(%currids);
14802:                 if ($curr[-1] =~ /^\d+$/) {
14803:                     $id = 1 + $curr[-1];
14804:                 }
14805:             } else {
14806:                 $id = 1;
14807:             }
14808:             if ($id) {
14809:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
14810:                     $error = 'nostore';
14811:                 }
14812:             } else {
14813:                 $error = 'nonumber';
14814:             }
14815:         }
14816:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
14817:     } else {
14818:         $error = 'nolock';
14819:     }
14820:     return ($id,$error);
14821: }
14822: 
14823: sub modify_autoenroll {
14824:     my ($dom,$lastactref,%domconfig) = @_;
14825:     my ($resulttext,%changes);
14826:     my %currautoenroll;
14827:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
14828:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
14829:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
14830:         }
14831:     }
14832:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
14833:     my %title = ( run => 'Auto-enrollment active',
14834:                   sender => 'Sender for notification messages',
14835:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
14836:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
14837:     my @offon = ('off','on');
14838:     my $sender_uname = $env{'form.sender_uname'};
14839:     my $sender_domain = $env{'form.sender_domain'};
14840:     if ($sender_domain eq '') {
14841:         $sender_uname = '';
14842:     } elsif ($sender_uname eq '') {
14843:         $sender_domain = '';
14844:     }
14845:     my $coowners = $env{'form.autoassign_coowners'};
14846:     my $failsafe = $env{'form.autoenroll_failsafe'};
14847:     $failsafe =~ s{^\s+|\s+$}{}g;
14848:     if ($failsafe =~ /\D/) {
14849:         undef($failsafe);
14850:     }
14851:     my %autoenrollhash =  (
14852:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
14853:                                        'sender_uname' => $sender_uname,
14854:                                        'sender_domain' => $sender_domain,
14855:                                        'co-owners' => $coowners,
14856:                                        'autofailsafe' => $failsafe,
14857:                                 }
14858:                      );
14859:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
14860:                                              $dom);
14861:     if ($putresult eq 'ok') {
14862:         if (exists($currautoenroll{'run'})) {
14863:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
14864:                  $changes{'run'} = 1;
14865:              }
14866:         } elsif ($autorun) {
14867:             if ($env{'form.autoenroll_run'} ne '1') {
14868:                  $changes{'run'} = 1;
14869:             }
14870:         }
14871:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
14872:             $changes{'sender'} = 1;
14873:         }
14874:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
14875:             $changes{'sender'} = 1;
14876:         }
14877:         if ($currautoenroll{'co-owners'} ne '') {
14878:             if ($currautoenroll{'co-owners'} ne $coowners) {
14879:                 $changes{'coowners'} = 1;
14880:             }
14881:         } elsif ($coowners) {
14882:             $changes{'coowners'} = 1;
14883:         }
14884:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
14885:             $changes{'autofailsafe'} = 1;
14886:         }
14887:         if (keys(%changes) > 0) {
14888:             $resulttext = &mt('Changes made:').'<ul>';
14889:             if ($changes{'run'}) {
14890:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
14891:             }
14892:             if ($changes{'sender'}) {
14893:                 if ($sender_uname eq '' || $sender_domain eq '') {
14894:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
14895:                 } else {
14896:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
14897:                 }
14898:             }
14899:             if ($changes{'coowners'}) {
14900:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
14901:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
14902:                 if (ref($lastactref) eq 'HASH') {
14903:                     $lastactref->{'domainconfig'} = 1;
14904:                 }
14905:             }
14906:             if ($changes{'autofailsafe'}) {
14907:                 if ($failsafe ne '') {
14908:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
14909:                 } else {
14910:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
14911:                 }
14912:                 &Apache::lonnet::get_domain_defaults($dom,1);
14913:                 if (ref($lastactref) eq 'HASH') {
14914:                     $lastactref->{'domdefaults'} = 1;
14915:                 }
14916:             }
14917:             $resulttext .= '</ul>';
14918:         } else {
14919:             $resulttext = &mt('No changes made to auto-enrollment settings');
14920:         }
14921:     } else {
14922:         $resulttext = '<span class="LC_error">'.
14923: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14924:     }
14925:     return $resulttext;
14926: }
14927: 
14928: sub modify_autoupdate {
14929:     my ($dom,%domconfig) = @_;
14930:     my ($resulttext,%currautoupdate,%fields,%changes);
14931:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
14932:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
14933:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
14934:         }
14935:     }
14936:     my @offon = ('off','on');
14937:     my %title = &Apache::lonlocal::texthash (
14938:                    run => 'Auto-update:',
14939:                    classlists => 'Updates to user information in classlists?'
14940:                 );
14941:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14942:     my %fieldtitles = &Apache::lonlocal::texthash (
14943:                         id => 'Student/Employee ID',
14944:                         permanentemail => 'E-mail address',
14945:                         lastname => 'Last Name',
14946:                         firstname => 'First Name',
14947:                         middlename => 'Middle Name',
14948:                         generation => 'Generation',
14949:                       );
14950:     $othertitle = &mt('All users');
14951:     if (keys(%{$usertypes}) >  0) {
14952:         $othertitle = &mt('Other users');
14953:     }
14954:     foreach my $key (keys(%env)) {
14955:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
14956:             my ($usertype,$item) = ($1,$2);
14957:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
14958:                 if ($usertype eq 'default') {   
14959:                     push(@{$fields{$1}},$2);
14960:                 } elsif (ref($types) eq 'ARRAY') {
14961:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
14962:                         push(@{$fields{$1}},$2);
14963:                     }
14964:                 }
14965:             }
14966:         }
14967:     }
14968:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
14969:     @lockablenames = sort(@lockablenames);
14970:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
14971:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
14972:         if (@changed) {
14973:             $changes{'lockablenames'} = 1;
14974:         }
14975:     } else {
14976:         if (@lockablenames) {
14977:             $changes{'lockablenames'} = 1;
14978:         }
14979:     }
14980:     my %updatehash = (
14981:                       autoupdate => { run => $env{'form.autoupdate_run'},
14982:                                       classlists => $env{'form.classlists'},
14983:                                       fields => {%fields},
14984:                                       lockablenames => \@lockablenames,
14985:                                     }
14986:                      );
14987:     foreach my $key (keys(%currautoupdate)) {
14988:         if (($key eq 'run') || ($key eq 'classlists')) {
14989:             if (exists($updatehash{autoupdate}{$key})) {
14990:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
14991:                     $changes{$key} = 1;
14992:                 }
14993:             }
14994:         } elsif ($key eq 'fields') {
14995:             if (ref($currautoupdate{$key}) eq 'HASH') {
14996:                 foreach my $item (@{$types},'default') {
14997:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
14998:                         my $change = 0;
14999:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
15000:                             if (!exists($fields{$item})) {
15001:                                 $change = 1;
15002:                                 last;
15003:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
15004:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
15005:                                     $change = 1;
15006:                                     last;
15007:                                 }
15008:                             }
15009:                         }
15010:                         if ($change) {
15011:                             push(@{$changes{$key}},$item);
15012:                         }
15013:                     } 
15014:                 }
15015:             }
15016:         } elsif ($key eq 'lockablenames') {
15017:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
15018:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
15019:                 if (@changed) {
15020:                     $changes{'lockablenames'} = 1;
15021:                 }
15022:             } else {
15023:                 if (@lockablenames) {
15024:                     $changes{'lockablenames'} = 1;
15025:                 }
15026:             }
15027:         }
15028:     }
15029:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
15030:         if (@lockablenames) {
15031:             $changes{'lockablenames'} = 1;
15032:         }
15033:     }
15034:     foreach my $item (@{$types},'default') {
15035:         if (defined($fields{$item})) {
15036:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
15037:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
15038:                     my $change = 0;
15039:                     if (ref($fields{$item}) eq 'ARRAY') {
15040:                         foreach my $type (@{$fields{$item}}) {
15041:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
15042:                                 $change = 1;
15043:                                 last;
15044:                             }
15045:                         }
15046:                     }
15047:                     if ($change) {
15048:                         push(@{$changes{'fields'}},$item);
15049:                     }
15050:                 } else {
15051:                     push(@{$changes{'fields'}},$item);
15052:                 }
15053:             } else {
15054:                 push(@{$changes{'fields'}},$item);
15055:             }
15056:         }
15057:     }
15058:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
15059:                                              $dom);
15060:     if ($putresult eq 'ok') {
15061:         if (keys(%changes) > 0) {
15062:             $resulttext = &mt('Changes made:').'<ul>';
15063:             foreach my $key (sort(keys(%changes))) {
15064:                 if ($key eq 'lockablenames') {
15065:                     $resulttext .= '<li>';
15066:                     if (@lockablenames) {
15067:                         $usertypes->{'default'} = $othertitle;
15068:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
15069:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
15070:                     } else {
15071:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
15072:                     }
15073:                     $resulttext .= '</li>';
15074:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
15075:                     foreach my $item (@{$changes{$key}}) {
15076:                         my @newvalues;
15077:                         foreach my $type (@{$fields{$item}}) {
15078:                             push(@newvalues,$fieldtitles{$type});
15079:                         }
15080:                         my $newvaluestr;
15081:                         if (@newvalues > 0) {
15082:                             $newvaluestr = join(', ',@newvalues);
15083:                         } else {
15084:                             $newvaluestr = &mt('none');
15085:                         }
15086:                         if ($item eq 'default') {
15087:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
15088:                         } else {
15089:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
15090:                         }
15091:                     }
15092:                 } else {
15093:                     my $newvalue;
15094:                     if ($key eq 'run') {
15095:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
15096:                     } else {
15097:                         $newvalue = $offon[$env{'form.'.$key}];
15098:                     }
15099:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
15100:                 }
15101:             }
15102:             $resulttext .= '</ul>';
15103:         } else {
15104:             $resulttext = &mt('No changes made to autoupdates');
15105:         }
15106:     } else {
15107:         $resulttext = '<span class="LC_error">'.
15108: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
15109:     }
15110:     return $resulttext;
15111: }
15112: 
15113: sub modify_autocreate {
15114:     my ($dom,%domconfig) = @_;
15115:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
15116:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
15117:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
15118:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
15119:         }
15120:     }
15121:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
15122:                  req => 'Auto-creation of validated requests for official courses',
15123:                  xmldc => 'Identity of course creator of courses from XML files',
15124:                );
15125:     my @types = ('xml','req');
15126:     foreach my $item (@types) {
15127:         $newvals{$item} = $env{'form.autocreate_'.$item};
15128:         $newvals{$item} =~ s/\D//g;
15129:         $newvals{$item} = 0 if ($newvals{$item} eq '');
15130:     }
15131:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
15132:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
15133:     unless (exists($domcoords{$newvals{'xmldc'}})) {
15134:         $newvals{'xmldc'} = '';
15135:     } 
15136:     %autocreatehash =  (
15137:                         autocreate => { xml => $newvals{'xml'},
15138:                                         req => $newvals{'req'},
15139:                                       }
15140:                        );
15141:     if ($newvals{'xmldc'} ne '') {
15142:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
15143:     }
15144:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
15145:                                              $dom);
15146:     if ($putresult eq 'ok') {
15147:         my @items = @types;
15148:         if ($newvals{'xml'}) {
15149:             push(@items,'xmldc');
15150:         }
15151:         foreach my $item (@items) {
15152:             if (exists($currautocreate{$item})) {
15153:                 if ($currautocreate{$item} ne $newvals{$item}) {
15154:                     $changes{$item} = 1;
15155:                 }
15156:             } elsif ($newvals{$item}) {
15157:                 $changes{$item} = 1;
15158:             }
15159:         }
15160:         if (keys(%changes) > 0) {
15161:             my @offon = ('off','on'); 
15162:             $resulttext = &mt('Changes made:').'<ul>';
15163:             foreach my $item (@types) {
15164:                 if ($changes{$item}) {
15165:                     my $newtxt = $offon[$newvals{$item}];
15166:                     $resulttext .= '<li>'.
15167:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
15168:                                        '<b>','</b>').
15169:                                    '</li>';
15170:                 }
15171:             }
15172:             if ($changes{'xmldc'}) {
15173:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
15174:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
15175:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
15176:             }
15177:             $resulttext .= '</ul>';
15178:         } else {
15179:             $resulttext = &mt('No changes made to auto-creation settings');
15180:         }
15181:     } else {
15182:         $resulttext = '<span class="LC_error">'.
15183:             &mt('An error occurred: [_1]',$putresult).'</span>';
15184:     }
15185:     return $resulttext;
15186: }
15187: 
15188: sub modify_directorysrch {
15189:     my ($dom,$lastactref,%domconfig) = @_;
15190:     my ($resulttext,%changes);
15191:     my %currdirsrch;
15192:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
15193:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
15194:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
15195:         }
15196:     }
15197:     my %title = ( available => 'Institutional directory search available',
15198:                   localonly => 'Other domains can search institution',
15199:                   lcavailable => 'LON-CAPA directory search available',
15200:                   lclocalonly => 'Other domains can search LON-CAPA domain',
15201:                   searchby => 'Search types',
15202:                   searchtypes => 'Search latitude');
15203:     my @offon = ('off','on');
15204:     my @otherdoms = ('Yes','No');
15205: 
15206:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
15207:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
15208:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
15209: 
15210:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15211:     if (keys(%{$usertypes}) == 0) {
15212:         @cansearch = ('default');
15213:     } else {
15214:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
15215:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
15216:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
15217:                     push(@{$changes{'cansearch'}},$type);
15218:                 }
15219:             }
15220:             foreach my $type (@cansearch) {
15221:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
15222:                     push(@{$changes{'cansearch'}},$type);
15223:                 }
15224:             }
15225:         } else {
15226:             push(@{$changes{'cansearch'}},@cansearch);
15227:         }
15228:     }
15229: 
15230:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
15231:         foreach my $by (@{$currdirsrch{'searchby'}}) {
15232:             if (!grep(/^\Q$by\E$/,@searchby)) {
15233:                 push(@{$changes{'searchby'}},$by);
15234:             }
15235:         }
15236:         foreach my $by (@searchby) {
15237:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
15238:                 push(@{$changes{'searchby'}},$by);
15239:             }
15240:         }
15241:     } else {
15242:         push(@{$changes{'searchby'}},@searchby);
15243:     }
15244: 
15245:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
15246:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
15247:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
15248:                 push(@{$changes{'searchtypes'}},$type);
15249:             }
15250:         }
15251:         foreach my $type (@searchtypes) {
15252:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
15253:                 push(@{$changes{'searchtypes'}},$type);
15254:             }
15255:         }
15256:     } else {
15257:         if (exists($currdirsrch{'searchtypes'})) {
15258:             foreach my $type (@searchtypes) {  
15259:                 if ($type ne $currdirsrch{'searchtypes'}) { 
15260:                     push(@{$changes{'searchtypes'}},$type);
15261:                 }
15262:             }
15263:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
15264:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
15265:             }   
15266:         } else {
15267:             push(@{$changes{'searchtypes'}},@searchtypes); 
15268:         }
15269:     }
15270: 
15271:     my %dirsrch_hash =  (
15272:             directorysrch => { available => $env{'form.dirsrch_available'},
15273:                                cansearch => \@cansearch,
15274:                                localonly => $env{'form.dirsrch_instlocalonly'},
15275:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
15276:                                lcavailable => $env{'form.dirsrch_domavailable'},
15277:                                searchby => \@searchby,
15278:                                searchtypes => \@searchtypes,
15279:                              }
15280:             );
15281:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
15282:                                              $dom);
15283:     if ($putresult eq 'ok') {
15284:         if (exists($currdirsrch{'available'})) {
15285:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
15286:                  $changes{'available'} = 1;
15287:              }
15288:         } else {
15289:             if ($env{'form.dirsrch_available'} eq '1') {
15290:                 $changes{'available'} = 1;
15291:             }
15292:         }
15293:         if (exists($currdirsrch{'lcavailable'})) {
15294:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
15295:                 $changes{'lcavailable'} = 1;
15296:             }
15297:         } else {
15298:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
15299:                 $changes{'lcavailable'} = 1;
15300:             }
15301:         }
15302:         if (exists($currdirsrch{'localonly'})) {
15303:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
15304:                 $changes{'localonly'} = 1;
15305:             }
15306:         } else {
15307:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
15308:                 $changes{'localonly'} = 1;
15309:             }
15310:         }
15311:         if (exists($currdirsrch{'lclocalonly'})) {
15312:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
15313:                 $changes{'lclocalonly'} = 1;
15314:             }
15315:         } else {
15316:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
15317:                 $changes{'lclocalonly'} = 1;
15318:             }
15319:         }
15320:         if (keys(%changes) > 0) {
15321:             $resulttext = &mt('Changes made:').'<ul>';
15322:             if ($changes{'available'}) {
15323:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
15324:             }
15325:             if ($changes{'lcavailable'}) {
15326:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
15327:             }
15328:             if ($changes{'localonly'}) {
15329:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
15330:             }
15331:             if ($changes{'lclocalonly'}) {
15332:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
15333:             }
15334:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
15335:                 my $chgtext;
15336:                 if (ref($usertypes) eq 'HASH') {
15337:                     if (keys(%{$usertypes}) > 0) {
15338:                         foreach my $type (@{$types}) {
15339:                             if (grep(/^\Q$type\E$/,@cansearch)) {
15340:                                 $chgtext .= $usertypes->{$type}.'; ';
15341:                             }
15342:                         }
15343:                         if (grep(/^default$/,@cansearch)) {
15344:                             $chgtext .= $othertitle;
15345:                         } else {
15346:                             $chgtext =~ s/\; $//;
15347:                         }
15348:                         $resulttext .=
15349:                             '<li>'.
15350:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
15351:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
15352:                             '</li>';
15353:                     }
15354:                 }
15355:             }
15356:             if (ref($changes{'searchby'}) eq 'ARRAY') {
15357:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
15358:                 my $chgtext;
15359:                 foreach my $type (@{$titleorder}) {
15360:                     if (grep(/^\Q$type\E$/,@searchby)) {
15361:                         if (defined($searchtitles->{$type})) {
15362:                             $chgtext .= $searchtitles->{$type}.'; ';
15363:                         }
15364:                     }
15365:                 }
15366:                 $chgtext =~ s/\; $//;
15367:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
15368:             }
15369:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
15370:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
15371:                 my $chgtext;
15372:                 foreach my $type (@{$srchtypeorder}) {
15373:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
15374:                         if (defined($srchtypes_desc->{$type})) {
15375:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
15376:                         }
15377:                     }
15378:                 }
15379:                 $chgtext =~ s/\; $//;
15380:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
15381:             }
15382:             $resulttext .= '</ul>';
15383:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
15384:             if (ref($lastactref) eq 'HASH') {
15385:                 $lastactref->{'directorysrch'} = 1;
15386:             }
15387:         } else {
15388:             $resulttext = &mt('No changes made to directory search settings');
15389:         }
15390:     } else {
15391:         $resulttext = '<span class="LC_error">'.
15392:                       &mt('An error occurred: [_1]',$putresult).'</span>';
15393:     }
15394:     return $resulttext;
15395: }
15396: 
15397: sub modify_contacts {
15398:     my ($dom,$lastactref,%domconfig) = @_;
15399:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
15400:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15401:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
15402:             $currsetting{$key} = $domconfig{'contacts'}{$key};
15403:         }
15404:     }
15405:     my (%others,%to,%bcc,%includestr,%includeloc);
15406:     my @contacts = ('supportemail','adminemail');
15407:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
15408:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
15409:     my @toggles = ('reporterrors','reportupdates','reportstatus');
15410:     my @lonstatus = ('threshold','sysmail','weights','excluded');
15411:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
15412:     foreach my $type (@mailings) {
15413:         @{$newsetting{$type}} = 
15414:             &Apache::loncommon::get_env_multiple('form.'.$type);
15415:         foreach my $item (@contacts) {
15416:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
15417:                 $contacts_hash{contacts}{$type}{$item} = 1;
15418:             } else {
15419:                 $contacts_hash{contacts}{$type}{$item} = 0;
15420:             }
15421:         }
15422:         $others{$type} = $env{'form.'.$type.'_others'};
15423:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
15424:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15425:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
15426:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
15427:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
15428:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
15429:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
15430:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15431:             }
15432:         }
15433:     }
15434:     foreach my $item (@contacts) {
15435:         $to{$item} = $env{'form.'.$item};
15436:         $contacts_hash{'contacts'}{$item} = $to{$item};
15437:     }
15438:     foreach my $item (@toggles) {
15439:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
15440:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
15441:         }
15442:     }
15443:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
15444:     foreach my $item (@lonstatus) {
15445:         if ($item eq 'excluded') {
15446:             my (%serverhomes,@excluded);
15447:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
15448:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
15449:             if (@possexcluded) {
15450:                 foreach my $id (sort(@possexcluded)) {
15451:                     if ($serverhomes{$id}) {
15452:                         push(@excluded,$id);
15453:                     }
15454:                 }
15455:             }
15456:             if (@excluded) {
15457:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
15458:             }
15459:         } elsif ($item eq 'weights') {
15460:             foreach my $type ('E','W','N','U') {
15461:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
15462:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
15463:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
15464:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
15465:                             $env{'form.error'.$item.'_'.$type};
15466:                     }
15467:                 }
15468:             }
15469:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
15470:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
15471:             if ($env{'form.error'.$item} =~ /^\d+$/) {
15472:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
15473:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
15474:                 }
15475:             }
15476:         }
15477:     }
15478:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
15479:         foreach my $field (@{$fields}) {
15480:             if (ref($possoptions->{$field}) eq 'ARRAY') {
15481:                 my $value = $env{'form.helpform_'.$field};
15482:                 $value =~ s/^\s+|\s+$//g;
15483:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
15484:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
15485:                     if ($field eq 'screenshot') {
15486:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
15487:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
15488:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
15489:                         }
15490:                     }
15491:                 }
15492:             }
15493:         }
15494:     }
15495:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15496:     my (@statuses,%usertypeshash,@overrides);
15497:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
15498:         @statuses = @{$types};
15499:         if (ref($usertypes) eq 'HASH') {
15500:             %usertypeshash = %{$usertypes};
15501:         }
15502:     }
15503:     if (@statuses) {
15504:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
15505:         foreach my $type (@possoverrides) {
15506:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
15507:                 push(@overrides,$type);
15508:             }
15509:         }
15510:         if (@overrides) {
15511:             foreach my $type (@overrides) {
15512:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
15513:                 foreach my $item (@contacts) {
15514:                     if (grep(/^\Q$item\E$/,@standard)) {
15515:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
15516:                         $newsetting{'override_'.$type}{$item} = 1;
15517:                     } else {
15518:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
15519:                         $newsetting{'override_'.$type}{$item} = 0;
15520:                     }
15521:                 }
15522:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
15523:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15524:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
15525:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15526:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
15527:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
15528:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
15529:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15530:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
15531:                 }
15532:             }     
15533:         }
15534:     }
15535:     if (keys(%currsetting) > 0) {
15536:         foreach my $item (@contacts) {
15537:             if ($to{$item} ne $currsetting{$item}) {
15538:                 $changes{$item} = 1;
15539:             }
15540:         }
15541:         foreach my $type (@mailings) {
15542:             foreach my $item (@contacts) {
15543:                 if (ref($currsetting{$type}) eq 'HASH') {
15544:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
15545:                         push(@{$changes{$type}},$item);
15546:                     }
15547:                 } else {
15548:                     push(@{$changes{$type}},@{$newsetting{$type}});
15549:                 }
15550:             }
15551:             if ($others{$type} ne $currsetting{$type}{'others'}) {
15552:                 push(@{$changes{$type}},'others');
15553:             }
15554:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15555:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
15556:                     push(@{$changes{$type}},'bcc'); 
15557:                 }
15558:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
15559:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
15560:                     push(@{$changes{$type}},'include');
15561:                 }
15562:             }
15563:         }
15564:         if (ref($fields) eq 'ARRAY') {
15565:             if (ref($currsetting{'helpform'}) eq 'HASH') {
15566:                 foreach my $field (@{$fields}) {
15567:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
15568:                         push(@{$changes{'helpform'}},$field);
15569:                     }
15570:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15571:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
15572:                             push(@{$changes{'helpform'}},'maxsize');
15573:                         }
15574:                     }
15575:                 }
15576:             } else {
15577:                 foreach my $field (@{$fields}) {
15578:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
15579:                         push(@{$changes{'helpform'}},$field);
15580:                     }
15581:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15582:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
15583:                             push(@{$changes{'helpform'}},'maxsize');
15584:                         }
15585:                     }
15586:                 }
15587:             }
15588:         }
15589:         if (@statuses) {
15590:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
15591:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
15592:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
15593:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
15594:                             foreach my $item (@contacts,'bcc','others','include') {
15595:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
15596:                                     push(@{$changes{'overrides'}},$key);
15597:                                     last;
15598:                                 }
15599:                             }
15600:                         } else {
15601:                             push(@{$changes{'overrides'}},$key);
15602:                         }
15603:                     }
15604:                 }
15605:                 foreach my $key (@overrides) {
15606:                     unless (exists($currsetting{'overrides'}{$key})) {
15607:                         push(@{$changes{'overrides'}},$key);
15608:                     }
15609:                 }
15610:             } else {
15611:                 foreach my $key (@overrides) {
15612:                     push(@{$changes{'overrides'}},$key); 
15613:                 }
15614:             }
15615:         }
15616:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
15617:             foreach my $key ('excluded','weights','threshold','sysmail') {
15618:                 if ($key eq 'excluded') {
15619:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
15620:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
15621:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
15622:                             (@{$currsetting{'lonstatus'}{$key}})) {
15623:                             my @diffs =
15624:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
15625:                                                                    $currsetting{'lonstatus'}{$key});
15626:                             if (@diffs) {
15627:                                 push(@{$changes{'lonstatus'}},$key);
15628:                             }
15629:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
15630:                             push(@{$changes{'lonstatus'}},$key);
15631:                         }
15632:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
15633:                              (@{$currsetting{'lonstatus'}{$key}})) {
15634:                         push(@{$changes{'lonstatus'}},$key);
15635:                     }
15636:                 } elsif ($key eq 'weights') {
15637:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
15638:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
15639:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
15640:                             foreach my $type ('E','W','N','U') {
15641:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
15642:                                         $currsetting{'lonstatus'}{$key}{$type}) {
15643:                                     push(@{$changes{'lonstatus'}},$key);
15644:                                     last;
15645:                                 }
15646:                             }
15647:                         } else {
15648:                             foreach my $type ('E','W','N','U') {
15649:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
15650:                                     push(@{$changes{'lonstatus'}},$key);
15651:                                     last;
15652:                                 }
15653:                             }
15654:                         }
15655:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
15656:                         foreach my $type ('E','W','N','U') {
15657:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
15658:                                 push(@{$changes{'lonstatus'}},$key);
15659:                                 last;
15660:                             }
15661:                         }
15662:                     }
15663:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
15664:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
15665:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
15666:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
15667:                                 push(@{$changes{'lonstatus'}},$key);
15668:                             }
15669:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
15670:                             push(@{$changes{'lonstatus'}},$key);
15671:                         }
15672:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
15673:                         push(@{$changes{'lonstatus'}},$key);
15674:                     }
15675:                 }
15676:             }
15677:         } else {
15678:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
15679:                 foreach my $key ('excluded','weights','threshold','sysmail') {
15680:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
15681:                         push(@{$changes{'lonstatus'}},$key);
15682:                     }
15683:                 }
15684:             }
15685:         }
15686:     } else {
15687:         my %default;
15688:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
15689:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
15690:         $default{'errormail'} = 'adminemail';
15691:         $default{'packagesmail'} = 'adminemail';
15692:         $default{'helpdeskmail'} = 'supportemail';
15693:         $default{'otherdomsmail'} = 'supportemail';
15694:         $default{'lonstatusmail'} = 'adminemail';
15695:         $default{'requestsmail'} = 'adminemail';
15696:         $default{'updatesmail'} = 'adminemail';
15697:         $default{'hostipmail'} = 'adminemail';
15698:         foreach my $item (@contacts) {
15699:            if ($to{$item} ne $default{$item}) {
15700:                $changes{$item} = 1;
15701:            }
15702:         }
15703:         foreach my $type (@mailings) {
15704:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
15705:                 push(@{$changes{$type}},@{$newsetting{$type}});
15706:             }
15707:             if ($others{$type} ne '') {
15708:                 push(@{$changes{$type}},'others');
15709:             }
15710:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15711:                 if ($bcc{$type} ne '') {
15712:                     push(@{$changes{$type}},'bcc');
15713:                 }
15714:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
15715:                     push(@{$changes{$type}},'include');
15716:                 }
15717:             }
15718:         }
15719:         if (ref($fields) eq 'ARRAY') {
15720:             foreach my $field (@{$fields}) {
15721:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
15722:                     push(@{$changes{'helpform'}},$field);
15723:                 }
15724:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15725:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
15726:                         push(@{$changes{'helpform'}},'maxsize');
15727:                     }
15728:                 }
15729:             }
15730:         }
15731:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
15732:             foreach my $key ('excluded','weights','threshold','sysmail') {
15733:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
15734:                     push(@{$changes{'lonstatus'}},$key);
15735:                 }
15736:             }
15737:         }
15738:     }
15739:     foreach my $item (@toggles) {
15740:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
15741:             $changes{$item} = 1;
15742:         } elsif ((!$env{'form.'.$item}) &&
15743:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
15744:             $changes{$item} = 1;
15745:         }
15746:     }
15747:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
15748:                                              $dom);
15749:     if ($putresult eq 'ok') {
15750:         if (keys(%changes) > 0) {
15751:             &Apache::loncommon::devalidate_domconfig_cache($dom);
15752:             if (ref($lastactref) eq 'HASH') {
15753:                 $lastactref->{'domainconfig'} = 1;
15754:             }
15755:             my ($titles,$short_titles)  = &contact_titles();
15756:             $resulttext = &mt('Changes made:').'<ul>';
15757:             foreach my $item (@contacts) {
15758:                 if ($changes{$item}) {
15759:                     $resulttext .= '<li>'.$titles->{$item}.
15760:                                     &mt(' set to: ').
15761:                                     '<span class="LC_cusr_emph">'.
15762:                                     $to{$item}.'</span></li>';
15763:                 }
15764:             }
15765:             foreach my $type (@mailings) {
15766:                 if (ref($changes{$type}) eq 'ARRAY') {
15767:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15768:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
15769:                     } else {
15770:                         $resulttext .= '<li>'.$titles->{$type}.': ';
15771:                     }
15772:                     my @text;
15773:                     foreach my $item (@{$newsetting{$type}}) {
15774:                         push(@text,$short_titles->{$item});
15775:                     }
15776:                     if ($others{$type} ne '') {
15777:                         push(@text,$others{$type});
15778:                     }
15779:                     if (@text) {
15780:                         $resulttext .= '<span class="LC_cusr_emph">'.
15781:                                        join(', ',@text).'</span>';
15782:                     }
15783:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15784:                         if ($bcc{$type} ne '') {
15785:                             my $bcctext;
15786:                             if (@text) {
15787:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
15788:                             } else {
15789:                                 $bcctext = '(Bcc)';
15790:                             }
15791:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
15792:                         } elsif (!@text) {
15793:                             $resulttext .= &mt('No one');
15794:                         }   
15795:                         if ($includestr{$type} ne '') {
15796:                             if ($includeloc{$type} eq 'b') {
15797:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
15798:                             } elsif ($includeloc{$type} eq 's') {
15799:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
15800:                             }
15801:                         }
15802:                     } elsif (!@text) {
15803:                         $resulttext .= &mt('No recipients');
15804:                     }
15805:                     $resulttext .= '</li>';
15806:                 }
15807:             }
15808:             if (ref($changes{'overrides'}) eq 'ARRAY') {
15809:                 my @deletions;
15810:                 foreach my $type (@{$changes{'overrides'}}) {
15811:                     if ($usertypeshash{$type}) {
15812:                         if (grep(/^\Q$type\E/,@overrides)) {
15813:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
15814:                                                       $usertypeshash{$type}).'<ul><li>';
15815:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
15816:                                 my @text;
15817:                                 foreach my $item (@contacts) {
15818:                                     if ($newsetting{'override_'.$type}{$item}) { 
15819:                                         push(@text,$short_titles->{$item});
15820:                                     }
15821:                                 }
15822:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
15823:                                     push(@text,$newsetting{'override_'.$type}{'others'});
15824:                                 }
15825:   
15826:                                 if (@text) {
15827:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
15828:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
15829:                                 }
15830:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
15831:                                     my $bcctext;
15832:                                     if (@text) {
15833:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
15834:                                     } else {
15835:                                         $bcctext = '(Bcc)';
15836:                                     }
15837:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
15838:                                 } elsif (!@text) {
15839:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
15840:                                 }
15841:                                 $resulttext .= '</li>';
15842:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
15843:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
15844:                                     if ($loc eq 'b') {
15845:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
15846:                                     } elsif ($loc eq 's') {
15847:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
15848:                                     }
15849:                                 }
15850:                             }
15851:                             $resulttext .= '</li></ul></li>';
15852:                         } else {
15853:                             push(@deletions,$usertypeshash{$type});
15854:                         }
15855:                     }
15856:                 }
15857:                 if (@deletions) {
15858:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
15859:                                               join(', ',@deletions)).'</li>';
15860:                 }
15861:             }
15862:             my @offon = ('off','on');
15863:             my $corelink = &core_link_msu();
15864:             if ($changes{'reporterrors'}) {
15865:                 $resulttext .= '<li>'.
15866:                                &mt('E-mail error reports to [_1] set to "'.
15867:                                    $offon[$env{'form.reporterrors'}].'".',
15868:                                    $corelink).
15869:                                '</li>';
15870:             }
15871:             if ($changes{'reportupdates'}) {
15872:                 $resulttext .= '<li>'.
15873:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
15874:                                     $offon[$env{'form.reportupdates'}].'".',
15875:                                     $corelink).
15876:                                 '</li>';
15877:             }
15878:             if ($changes{'reportstatus'}) {
15879:                 $resulttext .= '<li>'.
15880:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
15881:                                     $offon[$env{'form.reportstatus'}].'".',
15882:                                     $corelink).
15883:                                 '</li>';
15884:             }
15885:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
15886:                 $resulttext .= '<li>'.
15887:                                &mt('Nightly status check e-mail settings').':<ul>';
15888:                 my (%defval,%use_def,%shown);
15889:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
15890:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
15891:                 $defval{'weights'} =
15892:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
15893:                 $defval{'excluded'} = &mt('None');
15894:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
15895:                     foreach my $item ('threshold','sysmail','weights','excluded') {
15896:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
15897:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
15898:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
15899:                             } elsif ($item eq 'weights') {
15900:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
15901:                                     foreach my $type ('E','W','N','U') {
15902:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
15903:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
15904:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
15905:                                         } else {
15906:                                             $shown{$item} .= $lonstatus_defs->{$type};
15907:                                         }
15908:                                         $shown{$item} .= ', ';
15909:                                     }
15910:                                     $shown{$item} =~ s/, $//;
15911:                                 } else {
15912:                                     $shown{$item} = $defval{$item};
15913:                                 }
15914:                             } elsif ($item eq 'excluded') {
15915:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
15916:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
15917:                                 } else {
15918:                                     $shown{$item} = $defval{$item};
15919:                                 }
15920:                             }
15921:                         } else {
15922:                             $shown{$item} = $defval{$item};
15923:                         }
15924:                     }
15925:                 } else {
15926:                     foreach my $item ('threshold','weights','excluded','sysmail') {
15927:                         $shown{$item} = $defval{$item};
15928:                     }
15929:                 }
15930:                 foreach my $item ('threshold','weights','excluded','sysmail') {
15931:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
15932:                                           $shown{$item}).'</li>';
15933:                 }
15934:                 $resulttext .= '</ul></li>';
15935:             }
15936:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
15937:                 my (@optional,@required,@unused,$maxsizechg);
15938:                 foreach my $field (@{$changes{'helpform'}}) {
15939:                     if ($field eq 'maxsize') {
15940:                         $maxsizechg = 1;
15941:                         next;
15942:                     }
15943:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
15944:                         push(@optional,$field);
15945:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
15946:                         push(@unused,$field);
15947:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
15948:                         push(@required,$field);
15949:                     }
15950:                 }
15951:                 if (@optional) {
15952:                     $resulttext .= '<li>'.
15953:                                    &mt('Help form fields changed to "Optional": [_1].',
15954:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
15955:                                    '</li>';
15956:                 }
15957:                 if (@required) {
15958:                     $resulttext .= '<li>'.
15959:                                    &mt('Help form fields changed to "Required": [_1].',
15960:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
15961:                                    '</li>';
15962:                 }
15963:                 if (@unused) {
15964:                     $resulttext .= '<li>'.
15965:                                    &mt('Help form fields changed to "Not shown": [_1].',
15966:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
15967:                                    '</li>';
15968:                 }
15969:                 if ($maxsizechg) {
15970:                     $resulttext .= '<li>'.
15971:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
15972:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
15973:                                    '</li>';
15974:                 }
15975:             }
15976:             $resulttext .= '</ul>';
15977:         } else {
15978:             $resulttext = &mt('No changes made to contacts and form settings');
15979:         }
15980:     } else {
15981:         $resulttext = '<span class="LC_error">'.
15982:             &mt('An error occurred: [_1].',$putresult).'</span>';
15983:     }
15984:     return $resulttext;
15985: }
15986: 
15987: sub modify_privacy {
15988:     my ($dom,%domconfig) = @_;
15989:     my ($resulttext,%current,%changes);
15990:     if (ref($domconfig{'privacy'}) eq 'HASH') {
15991:         %current = %{$domconfig{'privacy'}};
15992:     }
15993:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
15994:     my @items = ('domain','author','course','community');
15995:     my %names = &Apache::lonlocal::texthash (
15996:                    domain => 'Assigned domain role(s)',
15997:                    author => 'Assigned co-author role(s)',
15998:                    course => 'Assigned course role(s)',
15999:                    community => 'Assigned community role',
16000:                 );
16001:     my %roles = &Apache::lonlocal::texthash (
16002:                    domain => 'Domain role',
16003:                    author => 'Co-author role',
16004:                    course => 'Course role',
16005:                    community => 'Community role',
16006:                 );
16007:     my %titles = &Apache::lonlocal::texthash (
16008:                   approval => 'Approval for role in different domain',
16009:                   othdom   => 'User information available in other domain',
16010:                   priv     => 'Information viewable by privileged user in same domain',
16011:                   unpriv   => 'Information viewable by unprivileged user in same domain',
16012:                   instdom  => 'Other domain shares institution/provider',
16013:                   extdom   => 'Other domain has different institution/provider',
16014:                   none     => 'Not allowed',
16015:                   user     => 'User authorizes',
16016:                   domain   => 'Domain Coordinator authorizes',
16017:                   auto     => 'Unrestricted',
16018:     );
16019:     my %fieldnames = &Apache::lonlocal::texthash (
16020:                         id => 'Student/Employee ID',
16021:                         permanentemail => 'E-mail address',
16022:                         lastname => 'Last Name',
16023:                         firstname => 'First Name',
16024:                         middlename => 'Middle Name',
16025:                         generation => 'Generation',
16026:     );
16027:     my ($othertitle,$usertypes,$types) =
16028:         &Apache::loncommon::sorted_inst_types($dom);
16029:     my (%by_ip,%by_location,@intdoms,@instdoms);
16030:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
16031: 
16032:     my %privacyhash = (
16033:                        'approval' => {
16034:                                        instdom => {},
16035:                                        extdom  => {},
16036:                                      },
16037:                        'othdom'   => {},
16038:                        'priv'     => {},
16039:                        'unpriv'   => {},
16040:                       );
16041:     foreach my $item (@items) {
16042:         if (@instdoms > 1) {
16043:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
16044:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
16045:             }
16046:             if (ref($current{'approval'}) eq 'HASH') {
16047:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
16048:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
16049:                         $changes{'approval'} = 1;
16050:                     }
16051:                 }
16052:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
16053:                 $changes{'approval'} = 1;
16054:             }
16055:         }
16056:         if (keys(%by_location) > 0) {
16057:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
16058:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
16059:             }
16060:             if (ref($current{'approval'}) eq 'HASH') {
16061:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
16062:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
16063:                         $changes{'approval'} = 1;
16064:                     }
16065:                 }
16066:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
16067:                 $changes{'approval'} = 1;
16068:             }
16069:         }
16070:         foreach my $status ('priv','unpriv') {
16071:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
16072:             my @newvalues;
16073:             foreach my $field (@possibles) {
16074:                 if (grep(/^\Q$field\E$/,@fields)) {
16075:                     $privacyhash{$status}{$item}{$field} = 1;
16076:                     push(@newvalues,$field);
16077:                 }
16078:             }
16079:             @newvalues = sort(@newvalues);
16080:             if (ref($current{$status}) eq 'HASH') {
16081:                 if (ref($current{$status}{$item}) eq 'HASH') {
16082:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
16083:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16084:                     if (@diffs > 0) {
16085:                         $changes{$status} = 1;
16086:                     }
16087:                 }
16088:             } else {
16089:                 my @stdfields;
16090:                 foreach my $field (@fields) {
16091:                     if ($field eq 'id') {
16092:                         next if ($status eq 'unpriv');
16093:                         next if (($status eq 'priv') && ($item eq 'community'));
16094:                     }
16095:                     push(@stdfields,$field);
16096:                 }
16097:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16098:                 if (@diffs > 0) {
16099:                     $changes{$status} = 1;
16100:                 }
16101:             }
16102:         }
16103:     }
16104:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
16105:         my @statuses;
16106:         if (ref($types) eq 'ARRAY') {
16107:             @statuses = @{$types};
16108:         }
16109:         foreach my $type (@statuses,'default') {
16110:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
16111:             my @newvalues;
16112:             foreach my $field (sort(@possfields)) {
16113:                 if (grep(/^\Q$field\E$/,@fields)) {
16114:                     $privacyhash{'othdom'}{$type}{$field} = 1;
16115:                     push(@newvalues,$field);
16116:                 }
16117:             }
16118:             @newvalues = sort(@newvalues);
16119:             if (ref($current{'othdom'}) eq 'HASH') {
16120:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
16121:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
16122:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16123:                     if (@diffs > 0) {
16124:                         $changes{'othdom'} = 1;
16125:                     }
16126:                 }
16127:             } else {
16128:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
16129:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16130:                 if (@diffs > 0) {
16131:                     $changes{'othdom'} = 1;
16132:                 }
16133:             }
16134:         }
16135:     }
16136:     my %confighash = (
16137:                         privacy => \%privacyhash,
16138:                      );
16139:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16140:     if ($putresult eq 'ok') {
16141:         if (keys(%changes) > 0) {
16142:             $resulttext = &mt('Changes made: ').'<ul>';
16143:             foreach my $key ('approval','othdom','priv','unpriv') {
16144:                 if ($changes{$key}) {
16145:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16146:                     if ($key eq 'approval') {
16147:                         if (keys(%{$privacyhash{$key}{instdom}})) {
16148:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
16149:                             foreach my $item (@items) {
16150:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
16151:                             }
16152:                             $resulttext .= '</ul></li>';
16153:                         }
16154:                         if (keys(%{$privacyhash{$key}{extdom}})) {
16155:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
16156:                             foreach my $item (@items) {
16157:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
16158:                             }
16159:                             $resulttext .= '</ul></li>';
16160:                         }
16161:                     } elsif ($key eq 'othdom') {
16162:                         my @statuses;
16163:                         if (ref($types) eq 'ARRAY') {
16164:                             @statuses = @{$types};
16165:                         }
16166:                         if (ref($privacyhash{$key}) eq 'HASH') {
16167:                             foreach my $status (@statuses,'default') {
16168:                                 if ($status eq 'default') {
16169:                                     $resulttext .= '<li>'.$othertitle.': ';
16170:                                 } elsif (ref($usertypes) eq 'HASH') {
16171:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
16172:                                 } else {
16173:                                     next;
16174:                                 }
16175:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
16176:                                     if (keys(%{$privacyhash{$key}{$status}})) {
16177:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
16178:                                     } else {
16179:                                         $resulttext .= &mt('none');
16180:                                     }
16181:                                 }
16182:                                 $resulttext .= '</li>';
16183:                             }
16184:                         }
16185:                     } else {
16186:                         foreach my $item (@items) {
16187:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
16188:                                 $resulttext .= '<li>'.$names{$item}.': ';
16189:                                 if (keys(%{$privacyhash{$key}{$item}})) {
16190:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
16191:                                 } else {
16192:                                     $resulttext .= &mt('none');
16193:                                 }
16194:                                 $resulttext .= '</li>';
16195:                             }
16196:                         }
16197:                     }
16198:                     $resulttext .= '</ul></li>';
16199:                 }
16200:             }
16201:         } else {
16202:             $resulttext = &mt('No changes made to user information settings');
16203:         }
16204:     } else {
16205:         $resulttext = '<span class="LC_error">'.
16206:             &mt('An error occurred: [_1]',$putresult).'</span>';
16207:     }
16208:     return $resulttext;
16209: }
16210: 
16211: sub modify_passwords {
16212:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16213:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
16214:         $updatedefaults,$updateconf);
16215:     my $customfn = 'resetpw.html';
16216:     if (ref($domconfig{'passwords'}) eq 'HASH') {
16217:         %current = %{$domconfig{'passwords'}};
16218:     }
16219:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16220:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16221:     if (ref($types) eq 'ARRAY') {
16222:         @oktypes = @{$types};
16223:     }
16224:     push(@oktypes,'default');
16225: 
16226:     my %titles = &Apache::lonlocal::texthash (
16227:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
16228:         intauth_check  => 'Check bcrypt cost if authenticated',
16229:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
16230:         permanent      => 'Permanent e-mail address',
16231:         critical       => 'Critical notification address',
16232:         notify         => 'Notification address',
16233:         min            => 'Minimum password length',
16234:         max            => 'Maximum password length',
16235:         chars          => 'Required characters',
16236:         expire         => 'Password expiration (days)',
16237:         numsaved       => 'Number of previous passwords to save',
16238:         reset          => 'Resetting Forgotten Password',
16239:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
16240:         rules          => 'Rules for LON-CAPA Passwords',
16241:         crsownerchg    => 'Course Owner Changing Student Passwords',
16242:         username       => 'Username',
16243:         email          => 'E-mail address',
16244:     );
16245: 
16246: #
16247: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
16248: #
16249:     my (%curr_defaults,%save_defaults);
16250:     if (ref($domconfig{'defaults'}) eq 'HASH') {
16251:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
16252:             if ($key =~ /^intauth_(cost|check|switch)$/) {
16253:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
16254:             } else {
16255:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
16256:             }
16257:         }
16258:     }
16259:     my %staticdefaults = (
16260:         'resetlink'      => 2,
16261:         'resetcase'      => \@oktypes,
16262:         'resetprelink'   => 'both',
16263:         'resetemail'     => ['critical','notify','permanent'],
16264:         'intauth_cost'   => 10,
16265:         'intauth_check'  => 0,
16266:         'intauth_switch' => 0,
16267:     );
16268:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
16269:     foreach my $type (@oktypes) {
16270:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
16271:     }
16272:     my $linklife = $env{'form.passwords_link'};
16273:     $linklife =~ s/^\s+|\s+$//g;
16274:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
16275:         $newvalues{'resetlink'} = $linklife;
16276:         if ($current{'resetlink'}) {
16277:             if ($current{'resetlink'} ne $linklife) {
16278:                 $changes{'reset'} = 1;
16279:             }
16280:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16281:             if ($staticdefaults{'resetlink'} ne $linklife) {
16282:                 $changes{'reset'} = 1;
16283:             }
16284:         }
16285:     } elsif ($current{'resetlink'}) {
16286:         $changes{'reset'} = 1;
16287:     }
16288:     my @casesens;
16289:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
16290:     foreach my $case (sort(@posscase)) {
16291:         if (grep(/^\Q$case\E$/,@oktypes)) {
16292:             push(@casesens,$case);
16293:         }
16294:     }
16295:     $newvalues{'resetcase'} = \@casesens;
16296:     if (ref($current{'resetcase'}) eq 'ARRAY') {
16297:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
16298:         if (@diffs > 0) {
16299:             $changes{'reset'} = 1;
16300:         }
16301:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16302:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
16303:         if (@diffs > 0) {
16304:             $changes{'reset'} = 1;
16305:         }
16306:     }
16307:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
16308:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
16309:         if (exists($current{'resetprelink'})) {
16310:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
16311:                 $changes{'reset'} = 1;
16312:             }
16313:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16314:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
16315:                 $changes{'reset'} = 1;
16316:             }
16317:         }
16318:     } elsif ($current{'resetprelink'}) {
16319:         $changes{'reset'} = 1;
16320:     }
16321:     foreach my $type (@oktypes) {
16322:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
16323:         my @postlink;
16324:         foreach my $item (sort(@possplink)) {
16325:             if ($item =~ /^(email|username)$/) {
16326:                 push(@postlink,$item);
16327:             }
16328:         }
16329:         $newvalues{'resetpostlink'}{$type} = \@postlink;
16330:         unless ($changes{'reset'}) {
16331:             if (ref($current{'resetpostlink'}) eq 'HASH') {
16332:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
16333:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
16334:                     if (@diffs > 0) {
16335:                         $changes{'reset'} = 1;
16336:                     }
16337:                 } else {
16338:                     $changes{'reset'} = 1;
16339:                 }
16340:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16341:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
16342:                 if (@diffs > 0) {
16343:                     $changes{'reset'} = 1;
16344:                 }
16345:             }
16346:         }
16347:     }
16348:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
16349:     my @resetemail;
16350:     foreach my $item (sort(@possemailsrc)) {
16351:         if ($item =~ /^(permanent|critical|notify)$/) {
16352:             push(@resetemail,$item);
16353:         }
16354:     }
16355:     $newvalues{'resetemail'} = \@resetemail;
16356:     unless ($changes{'reset'}) {
16357:         if (ref($current{'resetemail'}) eq 'ARRAY') {
16358:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
16359:             if (@diffs > 0) {
16360:                 $changes{'reset'} = 1;
16361:             }
16362:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16363:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
16364:             if (@diffs > 0) {
16365:                 $changes{'reset'} = 1;
16366:             }
16367:         }
16368:     }
16369:     if ($env{'form.passwords_stdtext'} == 0) {
16370:         $newvalues{'resetremove'} = 1;
16371:         unless ($current{'resetremove'}) {
16372:             $changes{'reset'} = 1;
16373:         }
16374:     } elsif ($current{'resetremove'}) {
16375:         $changes{'reset'} = 1;
16376:     }
16377:     if ($env{'form.passwords_customfile.filename'} ne '') {
16378:         my $servadm = $r->dir_config('lonAdmEMail');
16379:         my ($configuserok,$author_ok,$switchserver) =
16380:             &config_check($dom,$confname,$servadm);
16381:         my $error;
16382:         if ($configuserok eq 'ok') {
16383:             if ($switchserver) {
16384:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
16385:             } else {
16386:                 if ($author_ok eq 'ok') {
16387:                     my ($result,$customurl) =
16388:                         &publishlogo($r,'upload','passwords_customfile',$dom,
16389:                                      $confname,'customtext/resetpw','','',$customfn);
16390:                     if ($result eq 'ok') {
16391:                         $newvalues{'resetcustom'} = $customurl;
16392:                         $changes{'reset'} = 1;
16393:                     } else {
16394:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
16395:                     }
16396:                 } else {
16397:                     $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);
16398:                 }
16399:             }
16400:         } else {
16401:             $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);
16402:         }
16403:         if ($error) {
16404:             &Apache::lonnet::logthis($error);
16405:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16406:         }
16407:     } elsif ($current{'resetcustom'}) {
16408:         if ($env{'form.passwords_custom_del'}) {
16409:             $changes{'reset'} = 1;
16410:         } else {
16411:             $newvalues{'resetcustom'} = $current{'resetcustom'};
16412:         }
16413:     }
16414:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
16415:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
16416:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
16417:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
16418:             $changes{'intauth'} = 1;
16419:         }
16420:     } else {
16421:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
16422:     }
16423:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
16424:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
16425:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
16426:             $changes{'intauth'} = 1;
16427:         }
16428:     } else {
16429:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16430:     }
16431:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
16432:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
16433:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
16434:             $changes{'intauth'} = 1;
16435:         }
16436:     } else {
16437:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16438:     }
16439:     foreach my $item ('cost','check','switch') {
16440:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
16441:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
16442:             $updatedefaults = 1;
16443:         }
16444:     }
16445:     foreach my $rule ('min','max','expire','numsaved') {
16446:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
16447:         my $ruleok;
16448:         if ($rule eq 'expire') {
16449:             if (($env{'form.passwords_'.$rule} =~ /^\d+(|\.\d*)$/) &&
16450:                 ($env{'form.passwords_'.$rule} ne '0')) {
16451:                 $ruleok = 1;
16452:             }
16453:         } elsif ($rule eq 'min') {
16454:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
16455:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
16456:                     $ruleok = 1;
16457:                 }
16458:             }
16459:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
16460:                  ($env{'form.passwords_'.$rule} ne '0')) {
16461:             $ruleok = 1;
16462:         }
16463:         if ($ruleok) {
16464:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
16465:             if (exists($current{$rule})) {
16466:                 if ($newvalues{$rule} ne $current{$rule}) {
16467:                     $changes{'rules'} = 1;
16468:                 }
16469:             } elsif ($rule eq 'min') {
16470:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
16471:                     $changes{'rules'} = 1;
16472:                 }
16473:             } else {
16474:                 $changes{'rules'} = 1;
16475:             }
16476:         } elsif (exists($current{$rule})) {
16477:             $changes{'rules'} = 1;
16478:         }
16479:     }
16480:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
16481:     my @chars;
16482:     foreach my $item (sort(@posschars)) {
16483:         if ($item =~ /^(uc|lc|num|spec)$/) {
16484:             push(@chars,$item);
16485:         }
16486:     }
16487:     $newvalues{'chars'} = \@chars;
16488:     unless ($changes{'rules'}) {
16489:         if (ref($current{'chars'}) eq 'ARRAY') {
16490:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
16491:             if (@diffs > 0) {
16492:                 $changes{'rules'} = 1;
16493:             }
16494:         } else {
16495:             if (@chars > 0) {
16496:                 $changes{'rules'} = 1;
16497:             }
16498:         }
16499:     }
16500:     my %crsownerchg = (
16501:                         by => [],
16502:                         for => [],
16503:                       );
16504:     foreach my $item ('by','for') {
16505:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
16506:         foreach my $type (sort(@posstypes)) {
16507:             if (grep(/^\Q$type\E$/,@oktypes)) {
16508:                 push(@{$crsownerchg{$item}},$type);
16509:             }
16510:         }
16511:     }
16512:     $newvalues{'crsownerchg'} = \%crsownerchg;
16513:     if (ref($current{'crsownerchg'}) eq 'HASH') {
16514:         foreach my $item ('by','for') {
16515:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
16516:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
16517:                 if (@diffs > 0) {
16518:                     $changes{'crsownerchg'} = 1;
16519:                     last;
16520:                 }
16521:             }
16522:         }
16523:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
16524:         foreach my $item ('by','for') {
16525:             if (@{$crsownerchg{$item}} > 0) {
16526:                 $changes{'crsownerchg'} = 1;
16527:                 last;
16528:             }
16529:         }
16530:     }
16531: 
16532:     my %confighash = (
16533:                         defaults  => \%save_defaults,
16534:                         passwords => \%newvalues,
16535:                      );
16536:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
16537: 
16538:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16539:     if ($putresult eq 'ok') {
16540:         if (keys(%changes) > 0) {
16541:             $resulttext = &mt('Changes made: ').'<ul>';
16542:             foreach my $key ('reset','intauth','rules','crsownerchg') {
16543:                 if ($changes{$key}) {
16544:                     unless ($key eq 'intauth') {
16545:                         $updateconf = 1;
16546:                     }
16547:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16548:                     if ($key eq 'reset') {
16549:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
16550:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
16551:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
16552:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
16553:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
16554:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
16555:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
16556:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
16557:                             }
16558:                         } else {
16559:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
16560:                         }
16561:                         if ($confighash{'passwords'}{'resetlink'}) {
16562:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
16563:                         } else {
16564:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
16565:                                                   &mt('Will default to 2 hours').'</li>';
16566:                         }
16567:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
16568:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
16569:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
16570:                             } else {
16571:                                 my $casesens;
16572:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
16573:                                     if ($type eq 'default') {
16574:                                         $casesens .= $othertitle.', ';
16575:                                     } elsif ($usertypes->{$type} ne '') {
16576:                                         $casesens .= $usertypes->{$type}.', ';
16577:                                     }
16578:                                 }
16579:                                 $casesens =~ s/\Q, \E$//;
16580:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
16581:                             }
16582:                         } else {
16583:                             $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>';
16584:                         }
16585:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
16586:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
16587:                         } else {
16588:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
16589:                         }
16590:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
16591:                             my $output;
16592:                             if (ref($types) eq 'ARRAY') {
16593:                                 foreach my $type (@{$types}) {
16594:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
16595:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
16596:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
16597:                                         } else {
16598:                                             $output .= $usertypes->{$type}.' -- '.
16599:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
16600:                                         }
16601:                                     }
16602:                                 }
16603:                             }
16604:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
16605:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
16606:                                     $output .= $othertitle.' -- '.&mt('none');
16607:                                 } else {
16608:                                     $output .= $othertitle.' -- '.
16609:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
16610:                                 }
16611:                             }
16612:                             if ($output) {
16613:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
16614:                             } else {
16615:                                 $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>';
16616:                             }
16617:                         } else {
16618:                             $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>';
16619:                         }
16620:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
16621:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
16622:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
16623:                             } else {
16624:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
16625:                             }
16626:                         } else {
16627:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
16628:                         }
16629:                         if ($confighash{'passwords'}{'resetremove'}) {
16630:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
16631:                         } else {
16632:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
16633:                         }
16634:                         if ($confighash{'passwords'}{'resetcustom'}) {
16635:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
16636:                                                                             &mt('custom text'),600,500,undef,undef,
16637:                                                                             undef,undef,'background-color:#ffffff');
16638:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
16639:                         } else {
16640:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
16641:                         }
16642:                     } elsif ($key eq 'intauth') {
16643:                         foreach my $item ('cost','switch','check') {
16644:                             my $value = $save_defaults{$key.'_'.$item};
16645:                             if ($item eq 'switch') {
16646:                                 my %optiondesc = &Apache::lonlocal::texthash (
16647:                                                      0 => 'No',
16648:                                                      1 => 'Yes',
16649:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
16650:                                                  );
16651:                                 if ($value =~ /^(0|1|2)$/) {
16652:                                     $value = $optiondesc{$value};
16653:                                 } else {
16654:                                     $value = &mt('none -- defaults to No');
16655:                                 }
16656:                             } elsif ($item eq 'check') {
16657:                                 my %optiondesc = &Apache::lonlocal::texthash (
16658:                                                      0 => 'No',
16659:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
16660:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
16661:                                                  );
16662:                                 if ($value =~ /^(0|1|2)$/) {
16663:                                     $value = $optiondesc{$value};
16664:                                 } else {
16665:                                     $value = &mt('none -- defaults to No');
16666:                                 }
16667:                             }
16668:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
16669:                         }
16670:                     } elsif ($key eq 'rules') {
16671:                         foreach my $rule ('min','max','expire','numsaved') {
16672:                             if ($confighash{'passwords'}{$rule} eq '') {
16673:                                 if ($rule eq 'min') {
16674:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
16675:                                                    ' '.&mt('Default of [_1] will be used',
16676:                                                            $Apache::lonnet::passwdmin).'</li>';
16677:                                 } else {
16678:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
16679:                                 }
16680:                             } else {
16681:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
16682:                             }
16683:                         }
16684:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
16685:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
16686:                                 my %rulenames = &Apache::lonlocal::texthash(
16687:                                                      uc => 'At least one upper case letter',
16688:                                                      lc => 'At least one lower case letter',
16689:                                                      num => 'At least one number',
16690:                                                      spec => 'At least one non-alphanumeric',
16691:                                                    );
16692:                                 my $needed = '<ul><li>'.
16693:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
16694:                                              '</li></ul>'; 
16695:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
16696:                             } else {
16697:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16698:                             }
16699:                         } else {
16700:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16701:                         }
16702:                     } elsif ($key eq 'crsownerchg') {
16703:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
16704:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
16705:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
16706:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
16707:                             } else {
16708:                                 my %crsownerstr;
16709:                                 foreach my $item ('by','for') {
16710:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
16711:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
16712:                                             if ($type eq 'default') {
16713:                                                 $crsownerstr{$item} .= $othertitle.', ';
16714:                                             } elsif ($usertypes->{$type} ne '') {
16715:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
16716:                                             }
16717:                                         }
16718:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
16719:                                     }
16720:                                 }
16721:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
16722:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
16723:                             }
16724:                         } else {
16725:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
16726:                         }
16727:                     }
16728:                     $resulttext .= '</ul></li>';
16729:                 }
16730:             }
16731:             $resulttext .= '</ul>';
16732:         } else {
16733:             $resulttext = &mt('No changes made to password settings');
16734:         }
16735:         my $cachetime = 24*60*60;
16736:         if ($updatedefaults) {
16737:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16738:             if (ref($lastactref) eq 'HASH') {
16739:                 $lastactref->{'domdefaults'} = 1;
16740:             }
16741:         }
16742:         if ($updateconf) {
16743:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
16744:             if (ref($lastactref) eq 'HASH') {
16745:                 $lastactref->{'passwdconf'} = 1;
16746:             }
16747:         }
16748:     } else {
16749:         $resulttext = '<span class="LC_error">'.
16750:             &mt('An error occurred: [_1]',$putresult).'</span>';
16751:     }
16752:     if ($errors) {
16753:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
16754:                        $errors.'</ul></p>';
16755:     }
16756:     return $resulttext;
16757: }
16758: 
16759: sub modify_usercreation {
16760:     my ($dom,%domconfig) = @_;
16761:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
16762:     my $warningmsg;
16763:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
16764:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
16765:             if ($key eq 'cancreate') {
16766:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
16767:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
16768:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
16769:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16770:                         } else {
16771:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16772:                         }
16773:                     }
16774:                 }
16775:             } elsif ($key eq 'email_rule') {
16776:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
16777:             } else {
16778:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
16779:             }
16780:         }
16781:     }
16782:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
16783:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
16784:     my @contexts = ('author','course','requestcrs');
16785:     foreach my $item(@contexts) {
16786:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
16787:     }
16788:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
16789:         foreach my $item (@contexts) {
16790:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
16791:                 push(@{$changes{'cancreate'}},$item);
16792:             }
16793:         }
16794:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
16795:         foreach my $item (@contexts) {
16796:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
16797:                 if ($cancreate{$item} ne 'any') {
16798:                     push(@{$changes{'cancreate'}},$item);
16799:                 }
16800:             } else {
16801:                 if ($cancreate{$item} ne 'none') {
16802:                     push(@{$changes{'cancreate'}},$item);
16803:                 }
16804:             }
16805:         }
16806:     } else {
16807:         foreach my $item (@contexts)  {
16808:             push(@{$changes{'cancreate'}},$item);
16809:         }
16810:     }
16811: 
16812:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
16813:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
16814:             if (!grep(/^\Q$type\E$/,@username_rule)) {
16815:                 push(@{$changes{'username_rule'}},$type);
16816:             }
16817:         }
16818:         foreach my $type (@username_rule) {
16819:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
16820:                 push(@{$changes{'username_rule'}},$type);
16821:             }
16822:         }
16823:     } else {
16824:         push(@{$changes{'username_rule'}},@username_rule);
16825:     }
16826: 
16827:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
16828:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
16829:             if (!grep(/^\Q$type\E$/,@id_rule)) {
16830:                 push(@{$changes{'id_rule'}},$type);
16831:             }
16832:         }
16833:         foreach my $type (@id_rule) {
16834:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
16835:                 push(@{$changes{'id_rule'}},$type);
16836:             }
16837:         }
16838:     } else {
16839:         push(@{$changes{'id_rule'}},@id_rule);
16840:     }
16841: 
16842:     my @authen_contexts = ('author','course','domain');
16843:     my @authtypes = ('int','krb4','krb5','loc','lti');
16844:     my %authhash;
16845:     foreach my $item (@authen_contexts) {
16846:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
16847:         foreach my $auth (@authtypes) {
16848:             if (grep(/^\Q$auth\E$/,@authallowed)) {
16849:                 $authhash{$item}{$auth} = 1;
16850:             } else {
16851:                 $authhash{$item}{$auth} = 0;
16852:             }
16853:         }
16854:     }
16855:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
16856:         foreach my $item (@authen_contexts) {
16857:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
16858:                 foreach my $auth (@authtypes) {
16859:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
16860:                         push(@{$changes{'authtypes'}},$item);
16861:                         last;
16862:                     }
16863:                 }
16864:             }
16865:         }
16866:     } else {
16867:         foreach my $item (@authen_contexts) {
16868:             push(@{$changes{'authtypes'}},$item);
16869:         }
16870:     }
16871: 
16872:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
16873:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
16874:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
16875:     $save_usercreate{'id_rule'} = \@id_rule;
16876:     $save_usercreate{'username_rule'} = \@username_rule,
16877:     $save_usercreate{'authtypes'} = \%authhash;
16878: 
16879:     my %usercreation_hash =  (
16880:         usercreation     => \%save_usercreate,
16881:     );
16882: 
16883:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
16884:                                              $dom);
16885: 
16886:     if ($putresult eq 'ok') {
16887:         if (keys(%changes) > 0) {
16888:             $resulttext = &mt('Changes made:').'<ul>';
16889:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
16890:                 my %lt = &usercreation_types();
16891:                 foreach my $type (@{$changes{'cancreate'}}) {
16892:                     my $chgtext = $lt{$type}.', ';
16893:                     if ($cancreate{$type} eq 'none') {
16894:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
16895:                     } elsif ($cancreate{$type} eq 'any') {
16896:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
16897:                     } elsif ($cancreate{$type} eq 'official') {
16898:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
16899:                     } elsif ($cancreate{$type} eq 'unofficial') {
16900:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
16901:                     }
16902:                     $resulttext .= '<li>'.$chgtext.'</li>';
16903:                 }
16904:             }
16905:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
16906:                 my ($rules,$ruleorder) = 
16907:                     &Apache::lonnet::inst_userrules($dom,'username');
16908:                 my $chgtext = '<ul>';
16909:                 foreach my $type (@username_rule) {
16910:                     if (ref($rules->{$type}) eq 'HASH') {
16911:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
16912:                     }
16913:                 }
16914:                 $chgtext .= '</ul>';
16915:                 if (@username_rule > 0) {
16916:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
16917:                 } else {
16918:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
16919:                 }
16920:             }
16921:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
16922:                 my ($idrules,$idruleorder) = 
16923:                     &Apache::lonnet::inst_userrules($dom,'id');
16924:                 my $chgtext = '<ul>';
16925:                 foreach my $type (@id_rule) {
16926:                     if (ref($idrules->{$type}) eq 'HASH') {
16927:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
16928:                     }
16929:                 }
16930:                 $chgtext .= '</ul>';
16931:                 if (@id_rule > 0) {
16932:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
16933:                 } else {
16934:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
16935:                 }
16936:             }
16937:             my %authname = &authtype_names();
16938:             my %context_title = &context_names();
16939:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
16940:                 my $chgtext = '<ul>';
16941:                 foreach my $type (@{$changes{'authtypes'}}) {
16942:                     my @allowed;
16943:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
16944:                     foreach my $auth (@authtypes) {
16945:                         if ($authhash{$type}{$auth}) {
16946:                             push(@allowed,$authname{$auth});
16947:                         }
16948:                     }
16949:                     if (@allowed > 0) {
16950:                         $chgtext .= join(', ',@allowed).'</li>';
16951:                     } else {
16952:                         $chgtext .= &mt('none').'</li>';
16953:                     }
16954:                 }
16955:                 $chgtext .= '</ul>';
16956:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
16957:                 $resulttext .= '</li>';
16958:             }
16959:             $resulttext .= '</ul>';
16960:         } else {
16961:             $resulttext = &mt('No changes made to user creation settings');
16962:         }
16963:     } else {
16964:         $resulttext = '<span class="LC_error">'.
16965:             &mt('An error occurred: [_1]',$putresult).'</span>';
16966:     }
16967:     if ($warningmsg ne '') {
16968:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
16969:     }
16970:     return $resulttext;
16971: }
16972: 
16973: sub modify_selfcreation {
16974:     my ($dom,$lastactref,%domconfig) = @_;
16975:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
16976:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
16977:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16978:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
16979:     if (ref($typesref) eq 'ARRAY') {
16980:         @types = @{$typesref};
16981:     }
16982:     if (ref($usertypesref) eq 'HASH') {
16983:         %usertypes = %{$usertypesref};
16984:     }
16985:     $usertypes{'default'} = $othertitle;
16986: #
16987: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
16988: #
16989:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
16990:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
16991:             if ($key eq 'cancreate') {
16992:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
16993:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
16994:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
16995:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
16996:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
16997:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
16998:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
16999:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
17000:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17001:                         } else {
17002:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
17003:                         }
17004:                     }
17005:                 }
17006:             } elsif ($key eq 'email_rule') {
17007:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
17008:             } else {
17009:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
17010:             }
17011:         }
17012:     }
17013: #
17014: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
17015: #
17016:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
17017:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
17018:             if ($key eq 'selfcreate') {
17019:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
17020:             } else {
17021:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
17022:             }
17023:         }
17024:     }
17025: #
17026: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
17027: #
17028:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
17029:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
17030:             if ($key eq 'inststatusguest') {
17031:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
17032:             } else {
17033:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
17034:             }
17035:         }
17036:     }
17037: 
17038:     my @contexts = ('selfcreate');
17039:     @{$cancreate{'selfcreate'}} = ();
17040:     %{$cancreate{'emailusername'}} = ();
17041:     if (@types) {
17042:         @{$cancreate{'statustocreate'}} = ();
17043:     }
17044:     %{$cancreate{'selfcreateprocessing'}} = ();
17045:     %{$cancreate{'shibenv'}} = ();
17046:     %{$cancreate{'emailverified'}} = ();
17047:     %{$cancreate{'emailoptions'}} = ();
17048:     %{$cancreate{'emaildomain'}} = ();
17049:     my %selfcreatetypes = (
17050:                              sso   => 'users authenticated by institutional single sign on',
17051:                              login => 'users authenticated by institutional log-in',
17052:                              email => 'users verified by e-mail',
17053:                           );
17054: #
17055: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
17056: # is permitted.
17057: #
17058:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
17059: 
17060:     my (@statuses,%email_rule);
17061:     foreach my $item ('login','sso','email') {
17062:         if ($item eq 'email') {
17063:             if ($env{'form.cancreate_email'}) {
17064:                 if (@types) {
17065:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
17066:                     foreach my $status (@poss_statuses) {
17067:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
17068:                             push(@statuses,$status);
17069:                         }
17070:                     }
17071:                     $save_inststatus{'inststatusguest'} = \@statuses;
17072:                 } else {
17073:                     push(@statuses,'default');
17074:                 }
17075:                 if (@statuses) {
17076:                     my %curr_rule;
17077:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
17078:                         foreach my $type (@statuses) {
17079:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
17080:                         }
17081:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
17082:                         foreach my $type (@statuses) {
17083:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
17084:                         }
17085:                     }
17086:                     push(@{$cancreate{'selfcreate'}},'email');
17087:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
17088:                     my %curremaildom;
17089:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
17090:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
17091:                     }
17092:                     foreach my $type (@statuses) {
17093:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
17094:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
17095:                         }
17096:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
17097:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
17098:                         }
17099:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
17100: #
17101: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
17102: #
17103:                             my $chosen = $1;
17104:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
17105:                                 my $emaildom;
17106:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
17107:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
17108:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
17109:                                     if (ref($curremaildom{$type}) eq 'HASH') {
17110:                                         if (exists($curremaildom{$type}{$chosen})) {
17111:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
17112:                                                 push(@{$changes{'cancreate'}},'emaildomain');
17113:                                             }
17114:                                         } elsif ($emaildom ne '') {
17115:                                             push(@{$changes{'cancreate'}},'emaildomain');
17116:                                         }
17117:                                     } elsif ($emaildom ne '') {
17118:                                         push(@{$changes{'cancreate'}},'emaildomain');
17119:                                     } 
17120:                                 }
17121:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17122:                             } elsif ($chosen eq 'custom') {
17123:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
17124:                                 $email_rule{$type} = [];
17125:                                 if (ref($emailrules) eq 'HASH') {
17126:                                     foreach my $rule (@possemail_rules) {
17127:                                         if (exists($emailrules->{$rule})) {
17128:                                             push(@{$email_rule{$type}},$rule);
17129:                                         }
17130:                                     }
17131:                                 }
17132:                                 if (@{$email_rule{$type}}) {
17133:                                     $cancreate{'emailoptions'}{$type} = 'custom';
17134:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
17135:                                         if (@{$curr_rule{$type}} > 0) {
17136:                                             foreach my $rule (@{$curr_rule{$type}}) {
17137:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
17138:                                                     push(@{$changes{'email_rule'}},$type);
17139:                                                 }
17140:                                             }
17141:                                         }
17142:                                         foreach my $type (@{$email_rule{$type}}) {
17143:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
17144:                                                 push(@{$changes{'email_rule'}},$type);
17145:                                             }
17146:                                         }
17147:                                     } else {
17148:                                         push(@{$changes{'email_rule'}},$type);
17149:                                     }
17150:                                 }
17151:                             } else {
17152:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17153:                             }
17154:                         }
17155:                     }
17156:                     if (@types) {
17157:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17158:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
17159:                             if (@changed) {
17160:                                 push(@{$changes{'inststatus'}},'inststatusguest');
17161:                             }
17162:                         } else {
17163:                             push(@{$changes{'inststatus'}},'inststatusguest');
17164:                         }
17165:                     }
17166:                 } else {
17167:                     delete($env{'form.cancreate_email'});
17168:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17169:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17170:                             push(@{$changes{'inststatus'}},'inststatusguest');
17171:                         }
17172:                     }
17173:                 }
17174:             } else {
17175:                 $save_inststatus{'inststatusguest'} = [];
17176:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17177:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17178:                         push(@{$changes{'inststatus'}},'inststatusguest');
17179:                     }
17180:                 }
17181:             }
17182:         } else {
17183:             if ($env{'form.cancreate_'.$item}) {
17184:                 push(@{$cancreate{'selfcreate'}},$item);
17185:             }
17186:         }
17187:     }
17188:     my (%userinfo,%savecaptcha);
17189:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
17190: #
17191: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
17192: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
17193: #
17194: 
17195:     if ($env{'form.cancreate_email'}) {
17196:         push(@contexts,'emailusername');
17197:         if (@statuses) {
17198:             foreach my $type (@statuses) {
17199:                 if (ref($infofields) eq 'ARRAY') {
17200:                     foreach my $field (@{$infofields}) {
17201:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
17202:                             $cancreate{'emailusername'}{$type}{$field} = $1;
17203:                         }
17204:                     }
17205:                 }
17206:             }
17207:         }
17208: #
17209: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
17210: # queued requests for self-creation of account verified by e-mail.
17211: #
17212: 
17213:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
17214:         @approvalnotify = sort(@approvalnotify);
17215:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
17216:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17217:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
17218:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
17219:                     push(@{$changes{'cancreate'}},'notify');
17220:                 }
17221:             } else {
17222:                 if ($cancreate{'notify'}{'approval'}) {
17223:                     push(@{$changes{'cancreate'}},'notify');
17224:                 }
17225:             }
17226:         } elsif ($cancreate{'notify'}{'approval'}) {
17227:             push(@{$changes{'cancreate'}},'notify');
17228:         }
17229: 
17230:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
17231:     }
17232: #  
17233: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
17234: # institutional log-in.
17235: #
17236:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
17237:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
17238:                ($domdefaults{'auth_def'} eq 'localauth'))) {
17239:             $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.').' '.
17240:                           &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.');
17241:         }
17242:     }
17243:     my @fields = ('lastname','firstname','middlename','generation',
17244:                   'permanentemail','id');
17245:     my @shibfields = (@fields,'inststatus');
17246:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17247: #
17248: # Where usernames may created for institutional log-in and/or institutional single sign on:
17249: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
17250: # may self-create accounts 
17251: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
17252: # which the user may supply, if institutional data is unavailable.
17253: #
17254:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
17255:         if (@types) {
17256:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
17257:             push(@contexts,'statustocreate');
17258:             foreach my $type (@types) {
17259:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
17260:                 foreach my $field (@fields) {
17261:                     if (grep(/^\Q$field\E$/,@modifiable)) {
17262:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
17263:                     } else {
17264:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
17265:                     }
17266:                 }
17267:             }
17268:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
17269:                 foreach my $type (@types) {
17270:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
17271:                         foreach my $field (@fields) {
17272:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
17273:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
17274:                                 push(@{$changes{'selfcreate'}},$type);
17275:                                 last;
17276:                             }
17277:                         }
17278:                     }
17279:                 }
17280:             } else {
17281:                 foreach my $type (@types) {
17282:                     push(@{$changes{'selfcreate'}},$type);
17283:                 }
17284:             }
17285:         }
17286:         foreach my $field (@shibfields) {
17287:             if ($env{'form.shibenv_'.$field} ne '') {
17288:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
17289:             }
17290:         }
17291:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17292:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
17293:                 foreach my $field (@shibfields) {
17294:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
17295:                         push(@{$changes{'cancreate'}},'shibenv');
17296:                     }
17297:                 }
17298:             } else {
17299:                 foreach my $field (@shibfields) {
17300:                     if ($env{'form.shibenv_'.$field}) {
17301:                         push(@{$changes{'cancreate'}},'shibenv');
17302:                         last;
17303:                     }
17304:                 }
17305:             }
17306:         }
17307:     }
17308:     foreach my $item (@contexts) {
17309:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
17310:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
17311:                 if (ref($cancreate{$item}) eq 'ARRAY') {
17312:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
17313:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17314:                             push(@{$changes{'cancreate'}},$item);
17315:                         }
17316:                     }
17317:                 }
17318:             }
17319:             if (ref($cancreate{$item}) eq 'ARRAY') {
17320:                 foreach my $type (@{$cancreate{$item}}) {
17321:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
17322:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17323:                             push(@{$changes{'cancreate'}},$item);
17324:                         }
17325:                     }
17326:                 }
17327:             }
17328:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
17329:             if (ref($cancreate{$item}) eq 'HASH') {
17330:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
17331:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17332:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
17333:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17334:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17335:                                     push(@{$changes{'cancreate'}},$item);
17336:                                 }
17337:                             }
17338:                         }
17339:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17340:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17341:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17342:                                 push(@{$changes{'cancreate'}},$item);
17343:                             }
17344:                         }
17345:                     }
17346:                 }
17347:                 foreach my $type (keys(%{$cancreate{$item}})) {
17348:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17349:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17350:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17351:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17352:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17353:                                         push(@{$changes{'cancreate'}},$item);
17354:                                     }
17355:                                 }
17356:                             } else {
17357:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17358:                                     push(@{$changes{'cancreate'}},$item);
17359:                                 }
17360:                             }
17361:                         }
17362:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17363:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17364:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17365:                                 push(@{$changes{'cancreate'}},$item);
17366:                             }
17367:                         }
17368:                     }
17369:                 }
17370:             }
17371:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
17372:             if (ref($cancreate{$item}) eq 'ARRAY') {
17373:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
17374:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17375:                         push(@{$changes{'cancreate'}},$item);
17376:                     }
17377:                 }
17378:             }
17379:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17380:             if (ref($cancreate{$item}) eq 'HASH') {
17381:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17382:                     push(@{$changes{'cancreate'}},$item);
17383:                 }
17384:             }
17385:         } elsif ($item eq 'emailusername') {
17386:             if (ref($cancreate{$item}) eq 'HASH') {
17387:                 foreach my $type (keys(%{$cancreate{$item}})) {
17388:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17389:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17390:                             if ($cancreate{$item}{$type}{$field}) {
17391:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17392:                                     push(@{$changes{'cancreate'}},$item);
17393:                                 }
17394:                                 last;
17395:                             }
17396:                         }
17397:                     }
17398:                 }
17399:             }
17400:         }
17401:     }
17402: #
17403: # Populate %save_usercreate hash with updates to self-creation configuration.
17404: #
17405:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
17406:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
17407:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
17408:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
17409:     if (ref($cancreate{'notify'}) eq 'HASH') {
17410:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
17411:     }
17412:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
17413:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
17414:     }
17415:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
17416:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
17417:     }
17418:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
17419:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
17420:     }
17421:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
17422:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
17423:     }
17424:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17425:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
17426:     }
17427:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
17428:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
17429:     }
17430:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
17431:     $save_usercreate{'email_rule'} = \%email_rule;
17432: 
17433:     my %userconfig_hash = (
17434:             usercreation     => \%save_usercreate,
17435:             usermodification => \%save_usermodify,
17436:             inststatus       => \%save_inststatus,
17437:     );
17438: 
17439:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
17440:                                              $dom);
17441: #
17442: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
17443: #
17444:     if ($putresult eq 'ok') {
17445:         if (keys(%changes) > 0) {
17446:             $resulttext = &mt('Changes made:').'<ul>';
17447:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
17448:                 my %lt = &selfcreation_types();
17449:                 foreach my $type (@{$changes{'cancreate'}}) {
17450:                     my $chgtext = '';
17451:                     if ($type eq 'selfcreate') {
17452:                         if (@{$cancreate{$type}} == 0) {
17453:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
17454:                         } else {
17455:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
17456:                                         '<ul>';
17457:                             foreach my $case (@{$cancreate{$type}}) {
17458:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
17459:                             }
17460:                             $chgtext .= '</ul>';
17461:                             if (ref($cancreate{$type}) eq 'ARRAY') {
17462:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
17463:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17464:                                         if (@{$cancreate{'statustocreate'}} == 0) {
17465:                                             $chgtext .= '<span class="LC_warning">'.
17466:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
17467:                                                         '</span><br />';
17468:                                         }
17469:                                     }
17470:                                 }
17471:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
17472:                                     if (!@statuses) {
17473:                                         $chgtext .= '<span class="LC_warning">'.
17474:                                                     &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.").
17475:                                                     '</span><br />';
17476: 
17477:                                     }
17478:                                 }
17479:                             }
17480:                         }
17481:                     } elsif ($type eq 'shibenv') {
17482:                         if (keys(%{$cancreate{$type}}) == 0) {
17483:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
17484:                         } else {
17485:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
17486:                                         '<ul>';
17487:                             foreach my $field (@shibfields) {
17488:                                 next if ($cancreate{$type}{$field} eq '');
17489:                                 if ($field eq 'inststatus') {
17490:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
17491:                                 } else {
17492:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
17493:                                 }
17494:                             }
17495:                             $chgtext .= '</ul>';
17496:                         }
17497:                     } elsif ($type eq 'statustocreate') {
17498:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
17499:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
17500:                             if (@{$cancreate{'selfcreate'}} > 0) {
17501:                                 if (@{$cancreate{'statustocreate'}} == 0) {
17502:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
17503:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
17504:                                         $chgtext .= '<br />'.
17505:                                                     '<span class="LC_warning">'.
17506:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
17507:                                                     '</span>';
17508:                                     }
17509:                                 } elsif (keys(%usertypes) > 0) {
17510:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17511:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
17512:                                     } else {
17513:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
17514:                                     }
17515:                                     $chgtext .= '<ul>';
17516:                                     foreach my $case (@{$cancreate{$type}}) {
17517:                                         if ($case eq 'default') {
17518:                                             $chgtext .= '<li>'.$othertitle.'</li>';
17519:                                         } else {
17520:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
17521:                                         }
17522:                                     }
17523:                                     $chgtext .= '</ul>';
17524:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17525:                                         $chgtext .= '<span class="LC_warning">'.
17526:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
17527:                                                     '</span>';
17528:                                     }
17529:                                 }
17530:                             } else {
17531:                                 if (@{$cancreate{$type}} == 0) {
17532:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
17533:                                 } else {
17534:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
17535:                                 }
17536:                             }
17537:                             $chgtext .= '<br />';
17538:                         }
17539:                     } elsif ($type eq 'selfcreateprocessing') {
17540:                         my %choices = &Apache::lonlocal::texthash (
17541:                                                                     automatic => 'Automatic approval',
17542:                                                                     approval  => 'Queued for approval',
17543:                                                                   );
17544:                         if (@types) {
17545:                             if (@statuses) {
17546:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
17547:                                             '<ul>';
17548:                                 foreach my $status (@statuses) {
17549:                                     if ($status eq 'default') {
17550:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17551:                                     } else {
17552:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17553:                                     }
17554:                                 }
17555:                                 $chgtext .= '</ul>';
17556:                             }
17557:                         } else {
17558:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
17559:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
17560:                         }
17561:                     } elsif ($type eq 'emailverified') {
17562:                         my %options = &Apache::lonlocal::texthash (
17563:                                                                     all   => 'Same as e-mail',
17564:                                                                     first => 'Omit @domain',
17565:                                                                     free  => 'Free to choose',
17566:                                                                   );
17567:                         if (@types) {
17568:                             if (@statuses) {
17569:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
17570:                                             '<ul>';
17571:                                 foreach my $status (@statuses) {
17572:                                     if ($status eq 'default') {
17573:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
17574:                                     } else {
17575:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
17576:                                     }
17577:                                 }
17578:                                 $chgtext .= '</ul>';
17579:                             }
17580:                         } else {
17581:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
17582:                                             $options{$cancreate{'emailverified'}{'default'}});
17583:                         }
17584:                     } elsif ($type eq 'emailoptions') {
17585:                         my %options = &Apache::lonlocal::texthash (
17586:                                                                     any     => 'Any e-mail',
17587:                                                                     inst    => 'Institutional only',
17588:                                                                     noninst => 'Non-institutional only',
17589:                                                                     custom  => 'Custom restrictions',
17590:                                                                   );
17591:                         if (@types) {
17592:                             if (@statuses) {
17593:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
17594:                                             '<ul>';
17595:                                 foreach my $status (@statuses) {
17596:                                     if ($type eq 'default') {
17597:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
17598:                                     } else {
17599:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
17600:                                     }
17601:                                 }
17602:                                 $chgtext .= '</ul>';
17603:                             }
17604:                         } else {
17605:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
17606:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
17607:                             } else {
17608:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
17609:                                                 $options{$cancreate{'emailoptions'}{'default'}});
17610:                             }
17611:                         }
17612:                     } elsif ($type eq 'emaildomain') {
17613:                         my $output;
17614:                         if (@statuses) {
17615:                             foreach my $type (@statuses) {
17616:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
17617:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
17618:                                         if ($type eq 'default') {
17619:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17620:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
17621:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
17622:                                             } else {
17623:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
17624:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
17625:                                             }
17626:                                         } else {
17627:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17628:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
17629:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
17630:                                             } else {
17631:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
17632:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
17633:                                             }
17634:                                         }
17635:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
17636:                                         if ($type eq 'default') {
17637:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17638:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
17639:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
17640:                                             } else {
17641:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
17642:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
17643:                                             }
17644:                                         } else {
17645:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17646:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
17647:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
17648:                                             } else {
17649:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
17650:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
17651:                                             }
17652:                                         }
17653:                                     }
17654:                                 }
17655:                             }
17656:                         }
17657:                         if ($output ne '') {
17658:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
17659:                                         '<ul>'.$output.'</ul>';
17660:                         }
17661:                     } elsif ($type eq 'captcha') {
17662:                         if ($savecaptcha{$type} eq 'notused') {
17663:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
17664:                         } else {
17665:                             my %captchas = &captcha_phrases();
17666:                             if ($captchas{$savecaptcha{$type}}) {
17667:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
17668:                             } else {
17669:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
17670:                             }
17671:                         }
17672:                     } elsif ($type eq 'recaptchakeys') {
17673:                         my ($privkey,$pubkey);
17674:                         if (ref($savecaptcha{$type}) eq 'HASH') {
17675:                             $pubkey = $savecaptcha{$type}{'public'};
17676:                             $privkey = $savecaptcha{$type}{'private'};
17677:                         }
17678:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
17679:                         if (!$pubkey) {
17680:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
17681:                         } else {
17682:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
17683:                         }
17684:                         if (!$privkey) {
17685:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
17686:                         } else {
17687:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
17688:                         }
17689:                         $chgtext .= '</ul>';
17690:                     } elsif ($type eq 'recaptchaversion') {
17691:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
17692:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
17693:                         }
17694:                     } elsif ($type eq 'emailusername') {
17695:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
17696:                             if (@statuses) {
17697:                                 foreach my $type (@statuses) {
17698:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
17699:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
17700:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
17701:                                                     '<ul>';
17702:                                             foreach my $field (@{$infofields}) {
17703:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
17704:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
17705:                                                 }
17706:                                             }
17707:                                             $chgtext .= '</ul>';
17708:                                         } else {
17709:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
17710:                                         }
17711:                                     } else {
17712:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
17713:                                     }
17714:                                 }
17715:                             }
17716:                         }
17717:                     } elsif ($type eq 'notify') {
17718:                         my $numapprove = 0;
17719:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
17720:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
17721:                                 if ($cancreate{'notify'}{'approval'}) {
17722:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
17723:                                     $numapprove ++;
17724:                                 }
17725:                             }
17726:                         }
17727:                         unless ($numapprove) {
17728:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
17729:                         }
17730:                     }
17731:                     if ($chgtext) {
17732:                         $resulttext .= '<li>'.$chgtext.'</li>';
17733:                     }
17734:                 }
17735:             }
17736:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
17737:                 my ($emailrules,$emailruleorder) =
17738:                     &Apache::lonnet::inst_userrules($dom,'email');
17739:                 foreach my $type (@{$changes{'email_rule'}}) {
17740:                     if (ref($email_rule{$type}) eq 'ARRAY') {
17741:                         my $chgtext = '<ul>';
17742:                         foreach my $rule (@{$email_rule{$type}}) {
17743:                             if (ref($emailrules->{$rule}) eq 'HASH') {
17744:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
17745:                             }
17746:                         }
17747:                         $chgtext .= '</ul>';
17748:                         my $typename;
17749:                         if (@types) {
17750:                             if ($type eq 'default') {
17751:                                 $typename = $othertitle;
17752:                             } else {
17753:                                 $typename = $usertypes{$type};
17754:                             } 
17755:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
17756:                         }
17757:                         if (@{$email_rule{$type}} > 0) {
17758:                             $resulttext .= '<li>'.
17759:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
17760:                                                $usertypes{$type}).
17761:                                            $chgtext.
17762:                                            '</li>';
17763:                         } else {
17764:                             $resulttext .= '<li>'.
17765:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
17766:                                            '</li>'.
17767:                                            &mt('(Affiliation: [_1])',$typename);
17768:                         }
17769:                     }
17770:                 }
17771:             }
17772:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
17773:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
17774:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
17775:                         my $chgtext = '<ul>';
17776:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
17777:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
17778:                         }
17779:                         $chgtext .= '</ul>';
17780:                         $resulttext .= '<li>'.
17781:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
17782:                                           $chgtext.
17783:                                        '</li>';
17784:                     } else {
17785:                         $resulttext .= '<li>'.
17786:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
17787:                                        '</li>';
17788:                     }
17789:                 }
17790:             }
17791:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
17792:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
17793:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17794:                 foreach my $type (@{$changes{'selfcreate'}}) {
17795:                     my $typename = $type;
17796:                     if (keys(%usertypes) > 0) {
17797:                         if ($usertypes{$type} ne '') {
17798:                             $typename = $usertypes{$type};
17799:                         }
17800:                     }
17801:                     my @modifiable;
17802:                     $resulttext .= '<li>'.
17803:                                     &mt('Self-creation of account by users with status: [_1]',
17804:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
17805:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
17806:                     foreach my $field (@fields) {
17807:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
17808:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
17809:                         }
17810:                     }
17811:                     if (@modifiable > 0) {
17812:                         $resulttext .= join(', ',@modifiable);
17813:                     } else {
17814:                         $resulttext .= &mt('none');
17815:                     }
17816:                     $resulttext .= '</li>';
17817:                 }
17818:                 $resulttext .= '</ul></li>';
17819:             }
17820:             $resulttext .= '</ul>';
17821:             my $cachetime = 24*60*60;
17822:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
17823:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17824:             if (ref($lastactref) eq 'HASH') {
17825:                 $lastactref->{'domdefaults'} = 1;
17826:             }
17827:         } else {
17828:             $resulttext = &mt('No changes made to self-creation settings');
17829:         }
17830:     } else {
17831:         $resulttext = '<span class="LC_error">'.
17832:             &mt('An error occurred: [_1]',$putresult).'</span>';
17833:     }
17834:     if ($warningmsg ne '') {
17835:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
17836:     }
17837:     return $resulttext;
17838: }
17839: 
17840: sub process_captcha {
17841:     my ($container,$changes,$newsettings,$currsettings) = @_;
17842:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
17843:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
17844:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
17845:         $newsettings->{'captcha'} = 'original';
17846:     }
17847:     my %current;
17848:     if (ref($currsettings) eq 'HASH') {
17849:         %current = %{$currsettings};
17850:     }
17851:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
17852:         if ($container eq 'cancreate') {
17853:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
17854:                 push(@{$changes->{'cancreate'}},'captcha');
17855:             } elsif (!defined($changes->{'cancreate'})) {
17856:                 $changes->{'cancreate'} = ['captcha'];
17857:             }
17858:         } elsif ($container eq 'passwords') {
17859:             $changes->{'reset'} = 1;
17860:         } else {
17861:             $changes->{'captcha'} = 1;
17862:         }
17863:     }
17864:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
17865:     if ($newsettings->{'captcha'} eq 'recaptcha') {
17866:         $newpub = $env{'form.'.$container.'_recaptchapub'};
17867:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
17868:         $newpub =~ s/[^\w\-]//g;
17869:         $newpriv =~ s/[^\w\-]//g;
17870:         $newsettings->{'recaptchakeys'} = {
17871:                                              public  => $newpub,
17872:                                              private => $newpriv,
17873:                                           };
17874:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
17875:         $newversion =~ s/\D//g;
17876:         if ($newversion ne '2') {
17877:             $newversion = 1;
17878:         }
17879:         $newsettings->{'recaptchaversion'} = $newversion;
17880:     }
17881:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
17882:         $currpub = $current{'recaptchakeys'}{'public'};
17883:         $currpriv = $current{'recaptchakeys'}{'private'};
17884:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
17885:             $newsettings->{'recaptchakeys'} = {
17886:                                                  public  => '',
17887:                                                  private => '',
17888:                                               }
17889:         }
17890:     }
17891:     if ($current{'captcha'} eq 'recaptcha') {
17892:         $currversion = $current{'recaptchaversion'};
17893:         if ($currversion ne '2') {
17894:             $currversion = 1;
17895:         }
17896:     }
17897:     if ($currversion ne $newversion) {
17898:         if ($container eq 'cancreate') {
17899:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
17900:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
17901:             } elsif (!defined($changes->{'cancreate'})) {
17902:                 $changes->{'cancreate'} = ['recaptchaversion'];
17903:             }
17904:         } elsif ($container eq 'passwords') {
17905:             $changes->{'reset'} = 1;
17906:         } else {
17907:             $changes->{'recaptchaversion'} = 1;
17908:         }
17909:     }
17910:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
17911:         if ($container eq 'cancreate') {
17912:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
17913:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
17914:             } elsif (!defined($changes->{'cancreate'})) {
17915:                 $changes->{'cancreate'} = ['recaptchakeys'];
17916:             }
17917:         } elsif ($container eq 'passwords') {
17918:             $changes->{'reset'} = 1;
17919:         } else {
17920:             $changes->{'recaptchakeys'} = 1;
17921:         }
17922:     }
17923:     return;
17924: }
17925: 
17926: sub modify_usermodification {
17927:     my ($dom,%domconfig) = @_;
17928:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
17929:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
17930:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
17931:             if ($key eq 'selfcreate') {
17932:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
17933:             } else {  
17934:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
17935:             }
17936:         }
17937:     }
17938:     my @contexts = ('author','course');
17939:     my %context_title = (
17940:                            author => 'In author context',
17941:                            course => 'In course context',
17942:                         );
17943:     my @fields = ('lastname','firstname','middlename','generation',
17944:                   'permanentemail','id');
17945:     my %roles = (
17946:                   author => ['ca','aa'],
17947:                   course => ['st','ep','ta','in','cr'],
17948:                 );
17949:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17950:     foreach my $context (@contexts) {
17951:         foreach my $role (@{$roles{$context}}) {
17952:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
17953:             foreach my $item (@fields) {
17954:                 if (grep(/^\Q$item\E$/,@modifiable)) {
17955:                     $modifyhash{$context}{$role}{$item} = 1;
17956:                 } else {
17957:                     $modifyhash{$context}{$role}{$item} = 0;
17958:                 }
17959:             }
17960:         }
17961:         if (ref($curr_usermodification{$context}) eq 'HASH') {
17962:             foreach my $role (@{$roles{$context}}) {
17963:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
17964:                     foreach my $field (@fields) {
17965:                         if ($modifyhash{$context}{$role}{$field} ne 
17966:                                 $curr_usermodification{$context}{$role}{$field}) {
17967:                             push(@{$changes{$context}},$role);
17968:                             last;
17969:                         }
17970:                     }
17971:                 }
17972:             }
17973:         } else {
17974:             foreach my $context (@contexts) {
17975:                 foreach my $role (@{$roles{$context}}) {
17976:                     push(@{$changes{$context}},$role);
17977:                 }
17978:             }
17979:         }
17980:     }
17981:     my %usermodification_hash =  (
17982:                                    usermodification => \%modifyhash,
17983:                                  );
17984:     my $putresult = &Apache::lonnet::put_dom('configuration',
17985:                                              \%usermodification_hash,$dom);
17986:     if ($putresult eq 'ok') {
17987:         if (keys(%changes) > 0) {
17988:             $resulttext = &mt('Changes made: ').'<ul>';
17989:             foreach my $context (@contexts) {
17990:                 if (ref($changes{$context}) eq 'ARRAY') {
17991:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
17992:                     if (ref($changes{$context}) eq 'ARRAY') {
17993:                         foreach my $role (@{$changes{$context}}) {
17994:                             my $rolename;
17995:                             if ($role eq 'cr') {
17996:                                 $rolename = &mt('Custom');
17997:                             } else {
17998:                                 $rolename = &Apache::lonnet::plaintext($role);
17999:                             }
18000:                             my @modifiable;
18001:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
18002:                             foreach my $field (@fields) {
18003:                                 if ($modifyhash{$context}{$role}{$field}) {
18004:                                     push(@modifiable,$fieldtitles{$field});
18005:                                 }
18006:                             }
18007:                             if (@modifiable > 0) {
18008:                                 $resulttext .= join(', ',@modifiable);
18009:                             } else {
18010:                                 $resulttext .= &mt('none'); 
18011:                             }
18012:                             $resulttext .= '</li>';
18013:                         }
18014:                         $resulttext .= '</ul></li>';
18015:                     }
18016:                 }
18017:             }
18018:             $resulttext .= '</ul>';
18019:         } else {
18020:             $resulttext = &mt('No changes made to user modification settings');
18021:         }
18022:     } else {
18023:         $resulttext = '<span class="LC_error">'.
18024:             &mt('An error occurred: [_1]',$putresult).'</span>';
18025:     }
18026:     return $resulttext;
18027: }
18028: 
18029: sub modify_defaults {
18030:     my ($dom,$lastactref,%domconfig) = @_;
18031:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
18032:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18033:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
18034:                  'portal_def');
18035:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
18036:     foreach my $item (@items) {
18037:         $newvalues{$item} = $env{'form.'.$item};
18038:         if ($item eq 'auth_def') {
18039:             if ($newvalues{$item} ne '') {
18040:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
18041:                     push(@errors,$item);
18042:                 }
18043:             }
18044:         } elsif ($item eq 'lang_def') {
18045:             if ($newvalues{$item} ne '') {
18046:                 if ($newvalues{$item} =~ /^(\w+)/) {
18047:                     my $langcode = $1;
18048:                     if ($langcode ne 'x_chef') {
18049:                         if (code2language($langcode) eq '') {
18050:                             push(@errors,$item);
18051:                         }
18052:                     }
18053:                 } else {
18054:                     push(@errors,$item);
18055:                 }
18056:             }
18057:         } elsif ($item eq 'timezone_def') {
18058:             if ($newvalues{$item} ne '') {
18059:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
18060:                     push(@errors,$item);   
18061:                 }
18062:             }
18063:         } elsif ($item eq 'datelocale_def') {
18064:             if ($newvalues{$item} ne '') {
18065:                 my @datelocale_ids = DateTime::Locale->ids();
18066:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
18067:                     push(@errors,$item);
18068:                 }
18069:             }
18070:         } elsif ($item eq 'portal_def') {
18071:             if ($newvalues{$item} ne '') {
18072:                 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])\/?$/) {
18073:                     push(@errors,$item);
18074:                 }
18075:             }
18076:         }
18077:         if (grep(/^\Q$item\E$/,@errors)) {
18078:             $newvalues{$item} = $domdefaults{$item};
18079:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
18080:             $changes{$item} = 1;
18081:         }
18082:         $domdefaults{$item} = $newvalues{$item};
18083:     }
18084:     my %staticdefaults = (
18085:                            'intauth_cost'   => 10,
18086:                            'intauth_check'  => 0,
18087:                            'intauth_switch' => 0,
18088:                          );
18089:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
18090:         if (exists($domdefaults{$item})) {
18091:             $newvalues{$item} = $domdefaults{$item};
18092:         } else {
18093:             $newvalues{$item} = $staticdefaults{$item};
18094:         }
18095:     }
18096:     my %defaults_hash = (
18097:                          defaults => \%newvalues,
18098:                         );
18099:     my $title = &defaults_titles();
18100: 
18101:     my $currinststatus;
18102:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18103:         $currinststatus = $domconfig{'inststatus'};
18104:     } else {
18105:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18106:         $currinststatus = {
18107:                              inststatustypes => $usertypes,
18108:                              inststatusorder => $types,
18109:                              inststatusguest => [],
18110:                           };
18111:     }
18112:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
18113:     my @allpos;
18114:     my %alltypes;
18115:     my @inststatusguest;
18116:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
18117:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
18118:             unless (grep(/^\Q$type\E$/,@todelete)) {
18119:                 push(@inststatusguest,$type);
18120:             }
18121:         }
18122:     }
18123:     my ($currtitles,$currorder);
18124:     if (ref($currinststatus) eq 'HASH') {
18125:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
18126:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
18127:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
18128:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
18129:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
18130:                     }
18131:                 }
18132:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
18133:                     my $position = $env{'form.inststatus_pos_'.$type};
18134:                     $position =~ s/\D+//g;
18135:                     $allpos[$position] = $type;
18136:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
18137:                     $alltypes{$type} =~ s/`//g;
18138:                 }
18139:             }
18140:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
18141:             $currtitles =~ s/,$//;
18142:         }
18143:     }
18144:     if ($env{'form.addinststatus'}) {
18145:         my $newtype = $env{'form.addinststatus'};
18146:         $newtype =~ s/\W//g;
18147:         unless (exists($alltypes{$newtype})) {
18148:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
18149:             $alltypes{$newtype} =~ s/`//g; 
18150:             my $position = $env{'form.addinststatus_pos'};
18151:             $position =~ s/\D+//g;
18152:             if ($position ne '') {
18153:                 $allpos[$position] = $newtype;
18154:             }
18155:         }
18156:     }
18157:     my @orderedstatus;
18158:     foreach my $type (@allpos) {
18159:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
18160:             push(@orderedstatus,$type);
18161:         }
18162:     }
18163:     foreach my $type (keys(%alltypes)) {
18164:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
18165:             delete($alltypes{$type});
18166:         }
18167:     }
18168:     $defaults_hash{'inststatus'} = {
18169:                                      inststatustypes => \%alltypes,
18170:                                      inststatusorder => \@orderedstatus,
18171:                                      inststatusguest => \@inststatusguest,
18172:                                    };
18173:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
18174:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
18175:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
18176:         }
18177:     }
18178:     if ($currorder ne join(',',@orderedstatus)) {
18179:         $changes{'inststatus'}{'inststatusorder'} = 1;
18180:     }
18181:     my $newtitles;
18182:     foreach my $item (@orderedstatus) {
18183:         $newtitles .= $alltypes{$item}.',';
18184:     }
18185:     $newtitles =~ s/,$//;
18186:     if ($currtitles ne $newtitles) {
18187:         $changes{'inststatus'}{'inststatustypes'} = 1;
18188:     }
18189:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
18190:                                              $dom);
18191:     if ($putresult eq 'ok') {
18192:         if (keys(%changes) > 0) {
18193:             $resulttext = &mt('Changes made:').'<ul>';
18194:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
18195:             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";
18196:             foreach my $item (sort(keys(%changes))) {
18197:                 if ($item eq 'inststatus') {
18198:                     if (ref($changes{'inststatus'}) eq 'HASH') {
18199:                         if (@orderedstatus) {
18200:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
18201:                             foreach my $type (@orderedstatus) { 
18202:                                 $resulttext .= $alltypes{$type}.', ';
18203:                             }
18204:                             $resulttext =~ s/, $//;
18205:                             $resulttext .= '</li>';
18206:                         } else {
18207:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
18208:                         }
18209:                     }
18210:                 } else {
18211:                     my $value = $env{'form.'.$item};
18212:                     if ($value eq '') {
18213:                         $value = &mt('none');
18214:                     } elsif ($item eq 'auth_def') {
18215:                         my %authnames = &authtype_names();
18216:                         my %shortauth = (
18217:                                           internal   => 'int',
18218:                                           krb4       => 'krb4',
18219:                                           krb5       => 'krb5',
18220:                                           localauth  => 'loc',
18221:                                           lti        => 'lti',
18222:                         );
18223:                         $value = $authnames{$shortauth{$value}};
18224:                     }
18225:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
18226:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
18227:                 }
18228:             }
18229:             $resulttext .= '</ul>';
18230:             $mailmsgtext .= "\n";
18231:             my $cachetime = 24*60*60;
18232:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18233:             if (ref($lastactref) eq 'HASH') {
18234:                 $lastactref->{'domdefaults'} = 1;
18235:             }
18236:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
18237:                 my $notify = 1;
18238:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
18239:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
18240:                         $notify = 0;
18241:                     }
18242:                 }
18243:                 if ($notify) {
18244:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
18245:                                                "LON-CAPA Domain Settings Change - $dom",
18246:                                                $mailmsgtext);
18247:                 }
18248:             }
18249:         } else {
18250:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
18251:         }
18252:     } else {
18253:         $resulttext = '<span class="LC_error">'.
18254:             &mt('An error occurred: [_1]',$putresult).'</span>';
18255:     }
18256:     if (@errors > 0) {
18257:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
18258:         foreach my $item (@errors) {
18259:             $resulttext .= ' "'.$title->{$item}.'",';
18260:         }
18261:         $resulttext =~ s/,$//;
18262:     }
18263:     return $resulttext;
18264: }
18265: 
18266: sub modify_scantron {
18267:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18268:     my ($resulttext,%confhash,%changes,$errors);
18269:     my $custom = 'custom.tab';
18270:     my $default = 'default.tab';
18271:     my $servadm = $r->dir_config('lonAdmEMail');
18272:     my ($configuserok,$author_ok,$switchserver) =
18273:         &config_check($dom,$confname,$servadm);
18274:     if ($env{'form.scantronformat.filename'} ne '') {
18275:         my $error;
18276:         if ($configuserok eq 'ok') {
18277:             if ($switchserver) {
18278:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
18279:             } else {
18280:                 if ($author_ok eq 'ok') {
18281:                     my ($result,$scantronurl) =
18282:                         &publishlogo($r,'upload','scantronformat',$dom,
18283:                                      $confname,'scantron','','',$custom);
18284:                     if ($result eq 'ok') {
18285:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
18286:                         $changes{'scantronformat'} = 1;
18287:                     } else {
18288:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
18289:                     }
18290:                 } else {
18291:                     $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);
18292:                 }
18293:             }
18294:         } else {
18295:             $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);
18296:         }
18297:         if ($error) {
18298:             &Apache::lonnet::logthis($error);
18299:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18300:         }
18301:     }
18302:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18303:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
18304:             if ($env{'form.scantronformat_del'}) {
18305:                 $confhash{'scantron'}{'scantronformat'} = '';
18306:                 $changes{'scantronformat'} = 1;
18307:             } else {
18308:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
18309:             }
18310:         }
18311:     }
18312:     my @options = ('hdr','pad','rem');
18313:     my @fields = &scantroncsv_fields();
18314:     my %titles = &scantronconfig_titles();
18315:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
18316:     my ($newdat,$currdat,%newcol,%currcol);
18317:     if (grep(/^dat$/,@formats)) {
18318:         $confhash{'scantron'}{config}{dat} = 1;
18319:         $newdat = 1;
18320:     } else {
18321:         $newdat = 0;
18322:     }
18323:     if (grep(/^csv$/,@formats)) {
18324:         my %bynum;
18325:         foreach my $field (@fields) {
18326:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
18327:                 my $posscol = $1;
18328:                 if (($posscol < 20) && (!$bynum{$posscol})) {
18329:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
18330:                     $bynum{$posscol} = $field;
18331:                     $newcol{$field} = $posscol;
18332:                 }
18333:             }
18334:         }
18335:         if (keys(%newcol)) {
18336:             foreach my $option (@options) {
18337:                 if ($env{'form.scantroncsv_'.$option}) {
18338:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
18339:                 }
18340:             }
18341:         }
18342:     }
18343:     $currdat = 1;
18344:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18345:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
18346:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
18347:                 $currdat = 0;
18348:             }
18349:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18350:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18351:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
18352:                 }
18353:             }
18354:         }
18355:     }
18356:     if ($currdat != $newdat) {
18357:         $changes{'config'} = 1;
18358:     } else {
18359:         foreach my $field (@fields) {
18360:             if ($currcol{$field} ne '') {
18361:                 if ($currcol{$field} ne $newcol{$field}) {
18362:                     $changes{'config'} = 1;
18363:                     last;
18364:                 }
18365:             } elsif ($newcol{$field} ne '') {
18366:                 $changes{'config'} = 1;
18367:                 last;
18368:             }
18369:         }
18370:     }
18371:     if (keys(%confhash) > 0) {
18372:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
18373:                                                  $dom);
18374:         if ($putresult eq 'ok') {
18375:             if (keys(%changes) > 0) {
18376:                 if (ref($confhash{'scantron'}) eq 'HASH') {
18377:                     $resulttext = &mt('Changes made:').'<ul>';
18378:                     if ($changes{'scantronformat'}) {
18379:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
18380:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
18381:                         } else {
18382:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
18383:                         }
18384:                     }
18385:                     if ($changes{'config'}) {
18386:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
18387:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
18388:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
18389:                             }
18390:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18391:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18392:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
18393:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
18394:                                         foreach my $field (@fields) {
18395:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
18396:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
18397:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
18398:                                             }
18399:                                         }
18400:                                         $resulttext .= '</ul></li>';
18401:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
18402:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
18403:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
18404:                                                 foreach my $option (@options) {
18405:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
18406:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
18407:                                                     }
18408:                                                 }
18409:                                                 $resulttext .= '</ul></li>';
18410:                                             }
18411:                                         }
18412:                                     }
18413:                                 }
18414:                             }
18415:                         } else {
18416:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
18417:                         }
18418:                     }
18419:                     $resulttext .= '</ul>';
18420:                 } else {
18421:                     $resulttext = &mt('Changes made to bubblesheet format file.');
18422:                 }
18423:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
18424:                 if (ref($lastactref) eq 'HASH') {
18425:                     $lastactref->{'domainconfig'} = 1;
18426:                 }
18427:             } else {
18428:                 $resulttext = &mt('No changes made to bubblesheet format settings');
18429:             }
18430:         } else {
18431:             $resulttext = '<span class="LC_error">'.
18432:                 &mt('An error occurred: [_1]',$putresult).'</span>';
18433:         }
18434:     } else {
18435:         $resulttext = &mt('No changes made to bubblesheet format file'); 
18436:     }
18437:     if ($errors) {
18438:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18439:                        $errors.'</ul></p>';
18440:     }
18441:     return $resulttext;
18442: }
18443: 
18444: sub modify_coursecategories {
18445:     my ($dom,$lastactref,%domconfig) = @_;
18446:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
18447:         $cathash);
18448:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
18449:     my @catitems = ('unauth','auth');
18450:     my @cattypes = ('std','domonly','codesrch','none');
18451:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
18452:         $cathash = $domconfig{'coursecategories'}{'cats'};
18453:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
18454:             $changes{'togglecats'} = 1;
18455:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
18456:         }
18457:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
18458:             $changes{'categorize'} = 1;
18459:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
18460:         }
18461:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
18462:             $changes{'togglecatscomm'} = 1;
18463:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
18464:         }
18465:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
18466:             $changes{'categorizecomm'} = 1;
18467:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
18468: 
18469:         }
18470:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
18471:             $changes{'togglecatsplace'} = 1;
18472:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
18473:         }
18474:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
18475:             $changes{'categorizeplace'} = 1;
18476:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
18477:         }
18478:         foreach my $item (@catitems) {
18479:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18480:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
18481:                     $changes{$item} = 1;
18482:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18483:                 }
18484:             }
18485:         }
18486:     } else {
18487:         $changes{'togglecats'} = 1;
18488:         $changes{'categorize'} = 1;
18489:         $changes{'togglecatscomm'} = 1;
18490:         $changes{'categorizecomm'} = 1;
18491:         $changes{'togglecatsplace'} = 1;
18492:         $changes{'categorizeplace'} = 1;
18493:         $domconfig{'coursecategories'} = {
18494:                                              togglecats => $env{'form.togglecats'},
18495:                                              categorize => $env{'form.categorize'},
18496:                                              togglecatscomm => $env{'form.togglecatscomm'},
18497:                                              categorizecomm => $env{'form.categorizecomm'},
18498:                                              togglecatsplace => $env{'form.togglecatsplace'},
18499:                                              categorizeplace => $env{'form.categorizeplace'},
18500:                                          };
18501:         foreach my $item (@catitems) {
18502:             if ($env{'form.coursecat_'.$item} ne 'std') {
18503:                 $changes{$item} = 1;
18504:             }
18505:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18506:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18507:             }
18508:         }
18509:     }
18510:     if (ref($cathash) eq 'HASH') {
18511:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
18512:             push (@deletecategory,'instcode::0');
18513:         }
18514:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
18515:             push(@deletecategory,'communities::0');
18516:         }
18517:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
18518:             push(@deletecategory,'placement::0');
18519:         }
18520:     }
18521:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
18522:     if (ref($cathash) eq 'HASH') {
18523:         if (@deletecategory > 0) {
18524:             #FIXME Need to remove category from all courses using a deleted category 
18525:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
18526:             foreach my $item (@deletecategory) {
18527:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
18528:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
18529:                     $deletions{$item} = 1;
18530:                     &recurse_cat_deletes($item,$cathash,\%deletions);
18531:                 }
18532:             }
18533:         }
18534:         foreach my $item (keys(%{$cathash})) {
18535:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
18536:             if ($cathash->{$item} ne $env{'form.'.$item}) {
18537:                 $reorderings{$item} = 1;
18538:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
18539:             }
18540:             if ($env{'form.addcategory_name_'.$item} ne '') {
18541:                 my $newcat = $env{'form.addcategory_name_'.$item};
18542:                 my $newdepth = $depth+1;
18543:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18544:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
18545:                 $adds{$newitem} = 1; 
18546:             }
18547:             if ($env{'form.subcat_'.$item} ne '') {
18548:                 my $newcat = $env{'form.subcat_'.$item};
18549:                 my $newdepth = $depth+1;
18550:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18551:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
18552:                 $adds{$newitem} = 1;
18553:             }
18554:         }
18555:     }
18556:     if ($env{'form.instcode'} eq '1') {
18557:         if (ref($cathash) eq 'HASH') {
18558:             my $newitem = 'instcode::0';
18559:             if ($cathash->{$newitem} eq '') {  
18560:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18561:                 $adds{$newitem} = 1;
18562:             }
18563:         } else {
18564:             my $newitem = 'instcode::0';
18565:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18566:             $adds{$newitem} = 1;
18567:         }
18568:     }
18569:     if ($env{'form.communities'} eq '1') {
18570:         if (ref($cathash) eq 'HASH') {
18571:             my $newitem = 'communities::0';
18572:             if ($cathash->{$newitem} eq '') {
18573:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
18574:                 $adds{$newitem} = 1;
18575:             }
18576:         } else {
18577:             my $newitem = 'communities::0';
18578:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
18579:             $adds{$newitem} = 1;
18580:         }
18581:     }
18582:     if ($env{'form.placement'} eq '1') {
18583:         if (ref($cathash) eq 'HASH') {
18584:             my $newitem = 'placement::0';
18585:             if ($cathash->{$newitem} eq '') {
18586:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
18587:                 $adds{$newitem} = 1;
18588:             }
18589:         } else {
18590:             my $newitem = 'placement::0';
18591:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
18592:             $adds{$newitem} = 1;
18593:         }
18594:     }
18595:     if ($env{'form.addcategory_name'} ne '') {
18596:         if (($env{'form.addcategory_name'} ne 'instcode') &&
18597:             ($env{'form.addcategory_name'} ne 'communities') &&
18598:             ($env{'form.addcategory_name'} ne 'placement')) {
18599:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
18600:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
18601:             $adds{$newitem} = 1;
18602:         }
18603:     }
18604:     my $putresult;
18605:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
18606:         if (keys(%deletions) > 0) {
18607:             foreach my $key (keys(%deletions)) {
18608:                 if ($predelallitems{$key} ne '') {
18609:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
18610:                 }
18611:             }
18612:         }
18613:         my (@chkcats,@chktrails,%chkallitems);
18614:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
18615:         if (ref($chkcats[0]) eq 'ARRAY') {
18616:             my $depth = 0;
18617:             my $chg = 0;
18618:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
18619:                 my $name = $chkcats[0][$i];
18620:                 my $item;
18621:                 if ($name eq '') {
18622:                     $chg ++;
18623:                 } else {
18624:                     $item = &escape($name).'::0';
18625:                     if ($chg) {
18626:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
18627:                     }
18628:                     $depth ++; 
18629:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
18630:                     $depth --;
18631:                 }
18632:             }
18633:         }
18634:     }
18635:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
18636:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
18637:         if ($putresult eq 'ok') {
18638:             my %title = (
18639:                          togglecats     => 'Show/Hide a course in catalog',
18640:                          categorize     => 'Assign a category to a course',
18641:                          togglecatscomm => 'Show/Hide a community in catalog',
18642:                          categorizecomm => 'Assign a category to a community',
18643:                         );
18644:             my %level = (
18645:                          dom  => 'set in Domain ("Modify Course/Community")',
18646:                          crs  => 'set in Course ("Course Configuration")',
18647:                          comm => 'set in Community ("Community Configuration")',
18648:                          none     => 'No catalog',
18649:                          std      => 'Standard catalog',
18650:                          domonly  => 'Domain-only catalog',
18651:                          codesrch => 'Code search form',
18652:                         );
18653:             $resulttext = &mt('Changes made:').'<ul>';
18654:             if ($changes{'togglecats'}) {
18655:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
18656:             }
18657:             if ($changes{'categorize'}) {
18658:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
18659:             }
18660:             if ($changes{'togglecatscomm'}) {
18661:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
18662:             }
18663:             if ($changes{'categorizecomm'}) {
18664:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
18665:             }
18666:             if ($changes{'unauth'}) {
18667:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
18668:             }
18669:             if ($changes{'auth'}) {
18670:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
18671:             }
18672:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
18673:                 my $cathash;
18674:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
18675:                     $cathash = $domconfig{'coursecategories'}{'cats'};
18676:                 } else {
18677:                     $cathash = {};
18678:                 } 
18679:                 my (@cats,@trails,%allitems);
18680:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
18681:                 if (keys(%deletions) > 0) {
18682:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
18683:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
18684:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
18685:                     }
18686:                     $resulttext .= '</ul></li>';
18687:                 }
18688:                 if (keys(%reorderings) > 0) {
18689:                     my %sort_by_trail;
18690:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
18691:                     foreach my $key (keys(%reorderings)) {
18692:                         if ($allitems{$key} ne '') {
18693:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
18694:                         }
18695:                     }
18696:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
18697:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
18698:                     }
18699:                     $resulttext .= '</ul></li>';
18700:                 }
18701:                 if (keys(%adds) > 0) {
18702:                     my %sort_by_trail;
18703:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
18704:                     foreach my $key (keys(%adds)) {
18705:                         if ($allitems{$key} ne '') {
18706:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
18707:                         }
18708:                     }
18709:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
18710:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
18711:                     }
18712:                     $resulttext .= '</ul></li>';
18713:                 }
18714:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
18715:                 if (ref($lastactref) eq 'HASH') {
18716:                     $lastactref->{'cats'} = 1;
18717:                 }
18718:             }
18719:             $resulttext .= '</ul>';
18720:             if ($changes{'unauth'} || $changes{'auth'}) {
18721:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
18722:                 if ($changes{'auth'}) {
18723:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
18724:                 }
18725:                 if ($changes{'unauth'}) {
18726:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
18727:                 }
18728:                 my $cachetime = 24*60*60;
18729:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18730:                 if (ref($lastactref) eq 'HASH') {
18731:                     $lastactref->{'domdefaults'} = 1;
18732:                 }
18733:             }
18734:         } else {
18735:             $resulttext = '<span class="LC_error">'.
18736:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18737:         }
18738:     } else {
18739:         $resulttext = &mt('No changes made to course and community categories');
18740:     }
18741:     return $resulttext;
18742: }
18743: 
18744: sub modify_serverstatuses {
18745:     my ($dom,%domconfig) = @_;
18746:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
18747:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
18748:         %currserverstatus = %{$domconfig{'serverstatuses'}};
18749:     }
18750:     my @pages = &serverstatus_pages();
18751:     foreach my $type (@pages) {
18752:         $newserverstatus{$type}{'namedusers'} = '';
18753:         $newserverstatus{$type}{'machines'} = '';
18754:         if (defined($env{'form.'.$type.'_namedusers'})) {
18755:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
18756:             my @okusers;
18757:             foreach my $user (@users) {
18758:                 my ($uname,$udom) = split(/:/,$user);
18759:                 if (($udom =~ /^$match_domain$/) &&   
18760:                     (&Apache::lonnet::domain($udom)) &&
18761:                     ($uname =~ /^$match_username$/)) {
18762:                     if (!grep(/^\Q$user\E/,@okusers)) {
18763:                         push(@okusers,$user);
18764:                     }
18765:                 }
18766:             }
18767:             if (@okusers > 0) {
18768:                  @okusers = sort(@okusers);
18769:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
18770:             }
18771:         }
18772:         if (defined($env{'form.'.$type.'_machines'})) {
18773:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
18774:             my @okmachines;
18775:             foreach my $ip (@machines) {
18776:                 my @parts = split(/\./,$ip);
18777:                 next if (@parts < 4);
18778:                 my $badip = 0;
18779:                 for (my $i=0; $i<4; $i++) {
18780:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
18781:                         $badip = 1;
18782:                         last;
18783:                     }
18784:                 }
18785:                 if (!$badip) {
18786:                     push(@okmachines,$ip);     
18787:                 }
18788:             }
18789:             @okmachines = sort(@okmachines);
18790:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
18791:         }
18792:     }
18793:     my %serverstatushash =  (
18794:                                 serverstatuses => \%newserverstatus,
18795:                             );
18796:     foreach my $type (@pages) {
18797:         foreach my $setting ('namedusers','machines') {
18798:             my (@current,@new);
18799:             if (ref($currserverstatus{$type}) eq 'HASH') {
18800:                 if ($currserverstatus{$type}{$setting} ne '') { 
18801:                     @current = split(/,/,$currserverstatus{$type}{$setting});
18802:                 }
18803:             }
18804:             if ($newserverstatus{$type}{$setting} ne '') {
18805:                 @new = split(/,/,$newserverstatus{$type}{$setting});
18806:             }
18807:             if (@current > 0) {
18808:                 if (@new > 0) {
18809:                     foreach my $item (@current) {
18810:                         if (!grep(/^\Q$item\E$/,@new)) {
18811:                             $changes{$type}{$setting} = 1;
18812:                             last;
18813:                         }
18814:                     }
18815:                     foreach my $item (@new) {
18816:                         if (!grep(/^\Q$item\E$/,@current)) {
18817:                             $changes{$type}{$setting} = 1;
18818:                             last;
18819:                         }
18820:                     }
18821:                 } else {
18822:                     $changes{$type}{$setting} = 1;
18823:                 }
18824:             } elsif (@new > 0) {
18825:                 $changes{$type}{$setting} = 1;
18826:             }
18827:         }
18828:     }
18829:     if (keys(%changes) > 0) {
18830:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
18831:         my $putresult = &Apache::lonnet::put_dom('configuration',
18832:                                                  \%serverstatushash,$dom);
18833:         if ($putresult eq 'ok') {
18834:             $resulttext .= &mt('Changes made:').'<ul>';
18835:             foreach my $type (@pages) {
18836:                 if (ref($changes{$type}) eq 'HASH') {
18837:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
18838:                     if ($changes{$type}{'namedusers'}) {
18839:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
18840:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
18841:                         } else {
18842:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
18843:                         }
18844:                     }
18845:                     if ($changes{$type}{'machines'}) {
18846:                         if ($newserverstatus{$type}{'machines'} eq '') {
18847:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
18848:                         } else {
18849:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
18850:                         }
18851: 
18852:                     }
18853:                     $resulttext .= '</ul></li>';
18854:                 }
18855:             }
18856:             $resulttext .= '</ul>';
18857:         } else {
18858:             $resulttext = '<span class="LC_error">'.
18859:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
18860: 
18861:         }
18862:     } else {
18863:         $resulttext = &mt('No changes made to access to server status pages');
18864:     }
18865:     return $resulttext;
18866: }
18867: 
18868: sub modify_helpsettings {
18869:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18870:     my ($resulttext,$errors,%changes,%helphash);
18871:     my %defaultchecked = ('submitbugs' => 'on');
18872:     my @offon = ('off','on');
18873:     my @toggles = ('submitbugs');
18874:     my %current = ('submitbugs' => '',
18875:                    'adhoc'      => {},
18876:                   );
18877:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
18878:         %current = %{$domconfig{'helpsettings'}};
18879:     }
18880:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18881:     foreach my $item (@toggles) {
18882:         if ($defaultchecked{$item} eq 'on') { 
18883:             if ($current{$item} eq '') {
18884:                 if ($env{'form.'.$item} eq '0') {
18885:                     $changes{$item} = 1;
18886:                 }
18887:             } elsif ($current{$item} ne $env{'form.'.$item}) {
18888:                 $changes{$item} = 1;
18889:             }
18890:         } elsif ($defaultchecked{$item} eq 'off') {
18891:             if ($current{$item} eq '') {
18892:                 if ($env{'form.'.$item} eq '1') {
18893:                     $changes{$item} = 1;
18894:                 }
18895:             } elsif ($current{$item} ne $env{'form.'.$item}) {
18896:                 $changes{$item} = 1;
18897:             }
18898:         }
18899:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
18900:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
18901:         }
18902:     }
18903:     my $maxnum = $env{'form.helproles_maxnum'};
18904:     my $confname = $dom.'-domainconfig';
18905:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
18906:     my (@allpos,%newsettings,%changedprivs,$newrole);
18907:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18908:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
18909:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
18910:     my %lt = &Apache::lonlocal::texthash(
18911:                     s      => 'system',
18912:                     d      => 'domain',
18913:                     order  => 'Display order',
18914:                     access => 'Role usage',
18915:                     all    => 'All with domain helpdesk or helpdesk assistant role',
18916:                     dh     => 'All with domain helpdesk role',
18917:                     da     => 'All with domain helpdesk assistant role',
18918:                     none   => 'None',
18919:                     status => 'Determined based on institutional status',
18920:                     inc    => 'Include all, but exclude specific personnel',
18921:                     exc    => 'Exclude all, but include specific personnel',
18922:     );
18923:     for (my $num=0; $num<=$maxnum; $num++) {
18924:         my ($prefix,$identifier,$rolename,%curr);
18925:         if ($num == $maxnum) {
18926:             next unless ($env{'form.newcusthelp'} == $maxnum);
18927:             $identifier = 'custhelp'.$num;
18928:             $prefix = 'helproles_'.$num;
18929:             $rolename = $env{'form.custhelpname'.$num};
18930:             $rolename=~s/[^A-Za-z0-9]//gs;
18931:             next if ($rolename eq '');
18932:             next if (exists($existing{'rolesdef_'.$rolename}));
18933:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
18934:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
18935:                                                      $newprivs{'c'},$confname,$dom);
18936:             if ($result ne 'ok') {
18937:                 $errors .= '<li><span class="LC_error">'.
18938:                            &mt('An error occurred storing the new custom role: [_1]',
18939:                            $result).'</span></li>';
18940:                 next;
18941:             } else {
18942:                 $changedprivs{$rolename} = \%newprivs;
18943:                 $newrole = $rolename;
18944:             }
18945:         } else {
18946:             $prefix = 'helproles_'.$num;
18947:             $rolename = $env{'form.'.$prefix};
18948:             next if ($rolename eq '');
18949:             next unless (exists($existing{'rolesdef_'.$rolename}));
18950:             $identifier = 'custhelp'.$num;
18951:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
18952:             my %currprivs;
18953:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
18954:                 split(/\_/,$existing{'rolesdef_'.$rolename});
18955:             foreach my $level ('c','d','s') {
18956:                 if ($newprivs{$level} ne $currprivs{$level}) {
18957:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
18958:                                                              $newprivs{'c'},$confname,$dom);
18959:                     if ($result ne 'ok') {
18960:                         $errors .= '<li><span class="LC_error">'.
18961:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
18962:                                        $rolename,$result).'</span></li>';
18963:                     } else {
18964:                         $changedprivs{$rolename} = \%newprivs;
18965:                     }
18966:                     last;
18967:                 }
18968:             }
18969:             if (ref($current{'adhoc'}) eq 'HASH') {
18970:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
18971:                     %curr = %{$current{'adhoc'}{$rolename}};
18972:                 }
18973:             }
18974:         }
18975:         my $newpos = $env{'form.'.$prefix.'_pos'};
18976:         $newpos =~ s/\D+//g;
18977:         $allpos[$newpos] = $rolename;
18978:         my $newdesc = $env{'form.'.$prefix.'_desc'};
18979:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
18980:         if ($curr{'desc'}) {
18981:             if ($curr{'desc'} ne $newdesc) {
18982:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
18983:                 $newsettings{$rolename}{'desc'} = $newdesc;
18984:             }
18985:         } elsif ($newdesc ne '') {
18986:             $changes{'customrole'}{$rolename}{'desc'} = 1;
18987:             $newsettings{$rolename}{'desc'} = $newdesc;
18988:         }
18989:         my $access = $env{'form.'.$prefix.'_access'};
18990:         if (grep(/^\Q$access\E$/,@accesstypes)) {
18991:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
18992:             if ($access eq 'status') {
18993:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
18994:                 if (scalar(@statuses) == 0) {
18995:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
18996:                 } else {
18997:                     my (@shownstatus,$numtypes);
18998:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
18999:                     if (ref($types) eq 'ARRAY') {
19000:                         $numtypes = scalar(@{$types});
19001:                         foreach my $type (sort(@statuses)) {
19002:                             if ($type eq 'default') {
19003:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
19004:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
19005:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
19006:                                 push(@shownstatus,$usertypes->{$type});
19007:                             }
19008:                         }
19009:                     }
19010:                     if (grep(/^default$/,@statuses)) {
19011:                         push(@shownstatus,$othertitle);
19012:                     }
19013:                     if (scalar(@shownstatus) == 1+$numtypes) {
19014:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
19015:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
19016:                     } else {
19017:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
19018:                         if (ref($curr{'status'}) eq 'ARRAY') {
19019:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
19020:                             if (@diffs) {
19021:                                 $changes{'customrole'}{$rolename}{$access} = 1;
19022:                             }
19023:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19024:                             $changes{'customrole'}{$rolename}{$access} = 1;
19025:                         }
19026:                     }
19027:                 }
19028:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
19029:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
19030:                 my @newspecstaff;
19031:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
19032:                 foreach my $person (sort(@personnel)) {
19033:                     if ($domhelpdesk{$person}) {
19034:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
19035:                     }
19036:                 }
19037:                 if (ref($curr{$access}) eq 'ARRAY') {
19038:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
19039:                     if (@diffs) {
19040:                         $changes{'customrole'}{$rolename}{$access} = 1;
19041:                     }
19042:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19043:                     $changes{'customrole'}{$rolename}{$access} = 1;
19044:                 }
19045:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19046:                     my ($uname,$udom) = split(/:/,$person);
19047:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
19048:                 }
19049:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
19050:             }
19051:         } else {
19052:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
19053:         }
19054:         unless ($curr{'access'} eq $access) {
19055:             $changes{'customrole'}{$rolename}{'access'} = 1;
19056:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
19057:         }
19058:     }
19059:     if (@allpos > 0) {
19060:         my $idx = 0;
19061:         foreach my $rolename (@allpos) {
19062:             if ($rolename ne '') {
19063:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
19064:                 if (ref($current{'adhoc'}) eq 'HASH') {
19065:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
19066:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
19067:                             $changes{'customrole'}{$rolename}{'order'} = 1;
19068:                             $newsettings{$rolename}{'order'} = $idx+1;
19069:                         }
19070:                     }
19071:                 }
19072:                 $idx ++;
19073:             }
19074:         }
19075:     }
19076:     my $putresult;
19077:     if (keys(%changes) > 0) {
19078:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
19079:         if ($putresult eq 'ok') {
19080:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
19081:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
19082:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
19083:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
19084:                 }
19085:             }
19086:             my $cachetime = 24*60*60;
19087:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19088:             if (ref($lastactref) eq 'HASH') {
19089:                 $lastactref->{'domdefaults'} = 1;
19090:             }
19091:         } else {
19092:             $errors .= '<li><span class="LC_error">'.
19093:                        &mt('An error occurred storing the settings: [_1]',
19094:                            $putresult).'</span></li>';
19095:         }
19096:     }
19097:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
19098:         $resulttext = &mt('Changes made:').'<ul>';
19099:         my (%shownprivs,@levelorder);
19100:         @levelorder = ('c','d','s');
19101:         if ((keys(%changes)) && ($putresult eq 'ok')) {
19102:             foreach my $item (sort(keys(%changes))) {
19103:                 if ($item eq 'submitbugs') {
19104:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
19105:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
19106:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
19107:                 } elsif ($item eq 'customrole') {
19108:                     if (ref($changes{'customrole'}) eq 'HASH') {
19109:                         my @keyorder = ('order','desc','access','status','exc','inc');
19110:                         my %keytext = &Apache::lonlocal::texthash(
19111:                                                                    order  => 'Order',
19112:                                                                    desc   => 'Role description',
19113:                                                                    access => 'Role usage',
19114:                                                                    status => 'Allowed institutional types',
19115:                                                                    exc    => 'Allowed personnel',
19116:                                                                    inc    => 'Disallowed personnel',
19117:                         );
19118:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
19119:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
19120:                                 if ($role eq $newrole) {
19121:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
19122:                                                               $role).'<ul>';
19123:                                 } else {
19124:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19125:                                                               $role).'<ul>';
19126:                                 }
19127:                                 foreach my $key (@keyorder) {
19128:                                     if ($changes{'customrole'}{$role}{$key}) {
19129:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
19130:                                                                   $keytext{$key},$newsettings{$role}{$key}).
19131:                                                        '</li>';
19132:                                     }
19133:                                 }
19134:                                 if (ref($changedprivs{$role}) eq 'HASH') {
19135:                                     $shownprivs{$role} = 1;
19136:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
19137:                                     foreach my $level (@levelorder) {
19138:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
19139:                                             next if ($item eq '');
19140:                                             my ($priv) = split(/\&/,$item,2);
19141:                                             if (&Apache::lonnet::plaintext($priv)) {
19142:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
19143:                                                 unless ($level eq 'c') {
19144:                                                     $resulttext .= ' ('.$lt{$level}.')';
19145:                                                 }
19146:                                                 $resulttext .= '</li>';
19147:                                             }
19148:                                         }
19149:                                     }
19150:                                     $resulttext .= '</ul>';
19151:                                 }
19152:                                 $resulttext .= '</ul></li>';
19153:                             }
19154:                         }
19155:                     }
19156:                 }
19157:             }
19158:         }
19159:         if (keys(%changedprivs)) {
19160:             foreach my $role (sort(keys(%changedprivs))) {
19161:                 unless ($shownprivs{$role}) {
19162:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19163:                                               $role).'<ul>'.
19164:                                    '<li>'.&mt('Privileges set to :').'<ul>';
19165:                     foreach my $level (@levelorder) {
19166:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
19167:                             next if ($item eq '');
19168:                             my ($priv) = split(/\&/,$item,2);
19169:                             if (&Apache::lonnet::plaintext($priv)) {
19170:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
19171:                                 unless ($level eq 'c') {
19172:                                     $resulttext .= ' ('.$lt{$level}.')';
19173:                                 }
19174:                                 $resulttext .= '</li>';
19175:                             }
19176:                         }
19177:                     }
19178:                     $resulttext .= '</ul></li></ul></li>';
19179:                 }
19180:             }
19181:         }
19182:         $resulttext .= '</ul>';
19183:     } else {
19184:         $resulttext = &mt('No changes made to help settings');
19185:     }
19186:     if ($errors) {
19187:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
19188:                                     $errors.'</ul>';
19189:     }
19190:     return $resulttext;
19191: }
19192: 
19193: sub modify_coursedefaults {
19194:     my ($dom,$lastactref,%domconfig) = @_;
19195:     my ($resulttext,$errors,%changes,%defaultshash);
19196:     my %defaultchecked = (
19197:                            'canuse_pdfforms' => 'off',
19198:                            'uselcmath'       => 'on',
19199:                            'usejsme'         => 'on'
19200:                          );
19201:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme');
19202:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
19203:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
19204:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
19205:                    'mysqltables_textbook','mysqltables_placement');
19206:     my @types = ('official','unofficial','community','textbook','placement');
19207:     my %staticdefaults = (
19208:                            anonsurvey_threshold => 10,
19209:                            uploadquota          => 500,
19210:                            postsubmit           => 60,
19211:                            mysqltables          => 172800,
19212:                          );
19213:     my %texoptions = (
19214:                         MathJax  => 'MathJax',
19215:                         mimetex  => &mt('Convert to Images'),
19216:                         tth      => &mt('TeX to HTML'),
19217:                      );
19218:     $defaultshash{'coursedefaults'} = {};
19219: 
19220:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
19221:         if ($domconfig{'coursedefaults'} eq '') {
19222:             $domconfig{'coursedefaults'} = {};
19223:         }
19224:     }
19225: 
19226:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
19227:         foreach my $item (@toggles) {
19228:             if ($defaultchecked{$item} eq 'on') {
19229:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19230:                     ($env{'form.'.$item} eq '0')) {
19231:                     $changes{$item} = 1;
19232:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19233:                     $changes{$item} = 1;
19234:                 }
19235:             } elsif ($defaultchecked{$item} eq 'off') {
19236:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19237:                     ($env{'form.'.$item} eq '1')) {
19238:                     $changes{$item} = 1;
19239:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19240:                     $changes{$item} = 1;
19241:                 }
19242:             }
19243:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
19244:         }
19245:         foreach my $item (@numbers) {
19246:             my ($currdef,$newdef);
19247:             $newdef = $env{'form.'.$item};
19248:             if ($item eq 'anonsurvey_threshold') {
19249:                 $currdef = $domconfig{'coursedefaults'}{$item};
19250:                 $newdef =~ s/\D//g;
19251:                 if ($newdef eq '' || $newdef < 1) {
19252:                     $newdef = 1;
19253:                 }
19254:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
19255:             } else {
19256:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
19257:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
19258:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
19259:                 }
19260:                 $newdef =~ s/[^\w.\-]//g;
19261:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
19262:             }
19263:             if ($currdef ne $newdef) {
19264:                 if ($item eq 'anonsurvey_threshold') {
19265:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
19266:                         $changes{$item} = 1;
19267:                     }
19268:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
19269:                     my $setting = $1;
19270:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
19271:                         $changes{$setting} = 1;
19272:                     }
19273:                 }
19274:             }
19275:         }
19276:         my $texengine;
19277:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
19278:             $texengine = $env{'form.texengine'};
19279:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
19280:             if ($currdef eq '') {
19281:                 unless ($texengine eq $Apache::lonnet::deftex) {
19282:                     $changes{'texengine'} = 1;
19283:                 }
19284:             } elsif ($currdef ne $texengine) {
19285:                 $changes{'texengine'} = 1;
19286:             }
19287:         }
19288:         if ($texengine ne '') {
19289:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
19290:         }
19291:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
19292:         my @currclonecode;
19293:         if (ref($currclone) eq 'HASH') {
19294:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
19295:                 @currclonecode = @{$currclone->{'instcode'}};
19296:             }
19297:         }
19298:         my $newclone;
19299:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
19300:             $newclone = $env{'form.canclone'};
19301:         }
19302:         if ($newclone eq 'instcode') {
19303:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
19304:             my (%codedefaults,@code_order,@clonecode);
19305:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
19306:                                                     \@code_order);
19307:             foreach my $item (@code_order) {
19308:                 if (grep(/^\Q$item\E$/,@newcodes)) {
19309:                     push(@clonecode,$item);
19310:                 }
19311:             }
19312:             if (@clonecode) {
19313:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
19314:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
19315:                 if (@diffs) {
19316:                     $changes{'canclone'} = 1;
19317:                 }
19318:             } else {
19319:                 $newclone eq '';
19320:             }
19321:         } elsif ($newclone ne '') {
19322:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
19323:         }
19324:         if ($newclone ne $currclone) {
19325:             $changes{'canclone'} = 1;
19326:         }
19327:         my %credits;
19328:         foreach my $type (@types) {
19329:             unless ($type eq 'community') {
19330:                 $credits{$type} = $env{'form.'.$type.'_credits'};
19331:                 $credits{$type} =~ s/[^\d.]+//g;
19332:             }
19333:         }
19334:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
19335:             ($env{'form.coursecredits'} eq '1')) {
19336:             $changes{'coursecredits'} = 1;
19337:             foreach my $type (keys(%credits)) {
19338:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19339:             }
19340:         } else {
19341:             if ($env{'form.coursecredits'} eq '1') {
19342:                 foreach my $type (@types) {
19343:                     unless ($type eq 'community') {
19344:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
19345:                             $changes{'coursecredits'} = 1;
19346:                         }
19347:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19348:                     }
19349:                 }
19350:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19351:                 foreach my $type (@types) {
19352:                     unless ($type eq 'community') {
19353:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
19354:                             $changes{'coursecredits'} = 1;
19355:                             last;
19356:                         }
19357:                     }
19358:                 }
19359:             }
19360:         }
19361:         if ($env{'form.postsubmit'} eq '1') {
19362:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
19363:             my %currtimeout;
19364:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19365:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
19366:                     $changes{'postsubmit'} = 1;
19367:                 }
19368:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19369:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
19370:                 }
19371:             } else {
19372:                 $changes{'postsubmit'} = 1;
19373:             }
19374:             foreach my $type (@types) {
19375:                 my $timeout = $env{'form.'.$type.'_timeout'};
19376:                 $timeout =~ s/\D//g;
19377:                 if ($timeout == $staticdefaults{'postsubmit'}) {
19378:                     $timeout = '';
19379:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
19380:                     $timeout = '0';
19381:                 }
19382:                 unless ($timeout eq '') {
19383:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
19384:                 }
19385:                 if (exists($currtimeout{$type})) {
19386:                     if ($timeout ne $currtimeout{$type}) {
19387:                         $changes{'postsubmit'} = 1;
19388:                     }
19389:                 } elsif ($timeout ne '') {
19390:                     $changes{'postsubmit'} = 1;
19391:                 }
19392:             }
19393:         } else {
19394:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
19395:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19396:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
19397:                     $changes{'postsubmit'} = 1;
19398:                 }
19399:             } else {
19400:                 $changes{'postsubmit'} = 1;
19401:             }
19402:         }
19403:     }
19404:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19405:                                              $dom);
19406:     if ($putresult eq 'ok') {
19407:         if (keys(%changes) > 0) {
19408:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19409:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
19410:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
19411:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
19412:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','texengine') {
19413:                     if ($changes{$item}) {
19414:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
19415:                     }
19416:                 }
19417:                 if ($changes{'coursecredits'}) {
19418:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19419:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
19420:                             $domdefaults{$type.'credits'} =
19421:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
19422:                         }
19423:                     }
19424:                 }
19425:                 if ($changes{'postsubmit'}) {
19426:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19427:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
19428:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19429:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
19430:                                 $domdefaults{$type.'postsubtimeout'} =
19431:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19432:                             }
19433:                         }
19434:                     }
19435:                 }
19436:                 if ($changes{'uploadquota'}) {
19437:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19438:                         foreach my $type (@types) {
19439:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
19440:                         }
19441:                     }
19442:                 }
19443:                 if ($changes{'canclone'}) {
19444:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
19445:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
19446:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
19447:                             if (@clonecodes) {
19448:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
19449:                             }
19450:                         }
19451:                     } else {
19452:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
19453:                     }
19454:                 }
19455:                 my $cachetime = 24*60*60;
19456:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19457:                 if (ref($lastactref) eq 'HASH') {
19458:                     $lastactref->{'domdefaults'} = 1;
19459:                 }
19460:             }
19461:             $resulttext = &mt('Changes made:').'<ul>';
19462:             foreach my $item (sort(keys(%changes))) {
19463:                 if ($item eq 'canuse_pdfforms') {
19464:                     if ($env{'form.'.$item} eq '1') {
19465:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
19466:                     } else {
19467:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
19468:                     }
19469:                 } elsif ($item eq 'uselcmath') {
19470:                     if ($env{'form.'.$item} eq '1') {
19471:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
19472:                     } else {
19473:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
19474:                     }
19475:                 } elsif ($item eq 'usejsme') {
19476:                     if ($env{'form.'.$item} eq '1') {
19477:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
19478:                     } else {
19479:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
19480:                     }
19481:                 } elsif ($item eq 'texengine') {
19482:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
19483:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
19484:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
19485:                     }
19486:                 } elsif ($item eq 'anonsurvey_threshold') {
19487:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
19488:                 } elsif ($item eq 'uploadquota') {
19489:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19490:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
19491:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
19492:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
19493:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
19494:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
19495:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
19496:                                        '</ul>'.
19497:                                        '</li>';
19498:                     } else {
19499:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
19500:                     }
19501:                 } elsif ($item eq 'mysqltables') {
19502:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
19503:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
19504:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
19505:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
19506:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
19507:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
19508:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
19509:                                        '</ul>'.
19510:                                        '</li>';
19511:                     } else {
19512:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
19513:                     }
19514:                 } elsif ($item eq 'postsubmit') {
19515:                     if ($domdefaults{'postsubmit'} eq 'off') {
19516:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
19517:                     } else {
19518:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
19519:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19520:                             $resulttext .= &mt('durations:').'<ul>';
19521:                             foreach my $type (@types) {
19522:                                 $resulttext .= '<li>';
19523:                                 my $timeout;
19524:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19525:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19526:                                 }
19527:                                 my $display;
19528:                                 if ($timeout eq '0') {
19529:                                     $display = &mt('unlimited');
19530:                                 } elsif ($timeout eq '') {
19531:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
19532:                                 } else {
19533:                                     $display = &mt('[quant,_1,second]',$timeout);
19534:                                 }
19535:                                 if ($type eq 'community') {
19536:                                     $resulttext .= &mt('Communities');
19537:                                 } elsif ($type eq 'official') {
19538:                                     $resulttext .= &mt('Official courses');
19539:                                 } elsif ($type eq 'unofficial') {
19540:                                     $resulttext .= &mt('Unofficial courses');
19541:                                 } elsif ($type eq 'textbook') {
19542:                                     $resulttext .= &mt('Textbook courses');
19543:                                 } elsif ($type eq 'placement') {
19544:                                     $resulttext .= &mt('Placement tests');
19545:                                 }
19546:                                 $resulttext .= ' -- '.$display.'</li>';
19547:                             }
19548:                             $resulttext .= '</ul>';
19549:                         }
19550:                         $resulttext .= '</li>';
19551:                     }
19552:                 } elsif ($item eq 'coursecredits') {
19553:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19554:                         if (($domdefaults{'officialcredits'} eq '') &&
19555:                             ($domdefaults{'unofficialcredits'} eq '') &&
19556:                             ($domdefaults{'textbookcredits'} eq '')) {
19557:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
19558:                         } else {
19559:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
19560:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
19561:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
19562:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
19563:                                            '</ul>'.
19564:                                            '</li>';
19565:                         }
19566:                     } else {
19567:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
19568:                     }
19569:                 } elsif ($item eq 'canclone') {
19570:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
19571:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
19572:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
19573:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
19574:                         }
19575:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
19576:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
19577:                     } else {
19578:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
19579:                     }
19580:                 }
19581:             }
19582:             $resulttext .= '</ul>';
19583:         } else {
19584:             $resulttext = &mt('No changes made to course defaults');
19585:         }
19586:     } else {
19587:         $resulttext = '<span class="LC_error">'.
19588:             &mt('An error occurred: [_1]',$putresult).'</span>';
19589:     }
19590:     return $resulttext;
19591: }
19592: 
19593: sub modify_selfenrollment {
19594:     my ($dom,$lastactref,%domconfig) = @_;
19595:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
19596:     my @types = ('official','unofficial','community','textbook','placement');
19597:     my %titles = &tool_titles();
19598:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
19599:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
19600:     $ordered{'default'} = ['types','registered','approval','limit'];
19601: 
19602:     my (%roles,%shown,%toplevel);
19603:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
19604: 
19605:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
19606:         if ($domconfig{'selfenrollment'} eq '') {
19607:             $domconfig{'selfenrollment'} = {};
19608:         }
19609:     }
19610:     %toplevel = (
19611:                   admin      => 'Configuration Rights',
19612:                   default    => 'Default settings',
19613:                   validation => 'Validation of self-enrollment requests',
19614:                 );
19615:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
19616: 
19617:     if (ref($ordered{'admin'}) eq 'ARRAY') {
19618:         foreach my $item (@{$ordered{'admin'}}) {
19619:             foreach my $type (@types) {
19620:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
19621:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
19622:                 } else {
19623:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
19624:                 }
19625:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
19626:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
19627:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
19628:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
19629:                             push(@{$changes{'admin'}{$type}},$item);
19630:                         }
19631:                     } else {
19632:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
19633:                             push(@{$changes{'admin'}{$type}},$item);
19634:                         }
19635:                     }
19636:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
19637:                     push(@{$changes{'admin'}{$type}},$item);
19638:                 }
19639:             }
19640:         }
19641:     }
19642: 
19643:     foreach my $item (@{$ordered{'default'}}) {
19644:         foreach my $type (@types) {
19645:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
19646:             if ($item eq 'types') {
19647:                 unless (($value eq 'all') || ($value eq 'dom')) {
19648:                     $value = '';
19649:                 }
19650:             } elsif ($item eq 'registered') {
19651:                 unless ($value eq '1') {
19652:                     $value = 0;
19653:                 }
19654:             } elsif ($item eq 'approval') {
19655:                 unless ($value =~ /^[012]$/) {
19656:                     $value = 0;
19657:                 }
19658:             } else {
19659:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
19660:                     $value = 'none';
19661:                 }
19662:             }
19663:             $selfenrollhash{'default'}{$type}{$item} = $value;
19664:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
19665:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
19666:                     if ($selfenrollhash{'default'}{$type}{$item} ne
19667:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
19668:                          push(@{$changes{'default'}{$type}},$item);
19669:                     }
19670:                 } else {
19671:                     push(@{$changes{'default'}{$type}},$item);
19672:                 }
19673:             } else {
19674:                 push(@{$changes{'default'}{$type}},$item);
19675:             }
19676:             if ($item eq 'limit') {
19677:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
19678:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
19679:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
19680:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
19681:                     }
19682:                 } else {
19683:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
19684:                 }
19685:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
19686:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
19687:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
19688:                          push(@{$changes{'default'}{$type}},'cap');
19689:                     }
19690:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
19691:                     push(@{$changes{'default'}{$type}},'cap');
19692:                 }
19693:             }
19694:         }
19695:     }
19696: 
19697:     foreach my $item (@{$itemsref}) {
19698:         if ($item eq 'fields') {
19699:             my @changed;
19700:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
19701:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
19702:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
19703:             }
19704:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
19705:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
19706:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
19707:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
19708:                 } else {
19709:                     @changed = @{$selfenrollhash{'validation'}{$item}};
19710:                 }
19711:             } else {
19712:                 @changed = @{$selfenrollhash{'validation'}{$item}};
19713:             }
19714:             if (@changed) {
19715:                 if ($selfenrollhash{'validation'}{$item}) { 
19716:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
19717:                 } else {
19718:                     $changes{'validation'}{$item} = &mt('None');
19719:                 }
19720:             }
19721:         } else {
19722:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
19723:             if ($item eq 'markup') {
19724:                if ($env{'form.selfenroll_validation_'.$item}) {
19725:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
19726:                }
19727:             }
19728:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
19729:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
19730:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
19731:                 }
19732:             }
19733:         }
19734:     }
19735: 
19736:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
19737:                                              $dom);
19738:     if ($putresult eq 'ok') {
19739:         if (keys(%changes) > 0) {
19740:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19741:             $resulttext = &mt('Changes made:').'<ul>';
19742:             foreach my $key ('admin','default','validation') {
19743:                 if (ref($changes{$key}) eq 'HASH') {
19744:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
19745:                     if ($key eq 'validation') {
19746:                         foreach my $item (@{$itemsref}) {
19747:                             if (exists($changes{$key}{$item})) {
19748:                                 if ($item eq 'markup') {
19749:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
19750:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
19751:                                 } else {  
19752:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
19753:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
19754:                                 }
19755:                             }
19756:                         }
19757:                     } else {
19758:                         foreach my $type (@types) {
19759:                             if ($type eq 'community') {
19760:                                 $roles{'1'} = &mt('Community personnel');
19761:                             } else {
19762:                                 $roles{'1'} = &mt('Course personnel');
19763:                             }
19764:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
19765:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
19766:                                     if ($key eq 'admin') {
19767:                                         my @mgrdc = ();
19768:                                         if (ref($ordered{$key}) eq 'ARRAY') {
19769:                                             foreach my $item (@{$ordered{'admin'}}) {
19770:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
19771:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
19772:                                                         push(@mgrdc,$item);
19773:                                                     }
19774:                                                 }
19775:                                             }
19776:                                             if (@mgrdc) {
19777:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
19778:                                             } else {
19779:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
19780:                                             }
19781:                                         }
19782:                                     } else {
19783:                                         if (ref($ordered{$key}) eq 'ARRAY') {
19784:                                             foreach my $item (@{$ordered{$key}}) {
19785:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
19786:                                                     $domdefaults{$type.'selfenroll'.$item} =
19787:                                                         $selfenrollhash{$key}{$type}{$item};
19788:                                                 }
19789:                                             }
19790:                                         }
19791:                                     }
19792:                                 }
19793:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
19794:                                 foreach my $item (@{$ordered{$key}}) {
19795:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
19796:                                         $resulttext .= '<li>';
19797:                                         if ($key eq 'admin') {
19798:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
19799:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
19800:                                         } else {
19801:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
19802:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
19803:                                         }
19804:                                         $resulttext .= '</li>';
19805:                                     }
19806:                                 }
19807:                                 $resulttext .= '</ul></li>';
19808:                             }
19809:                         }
19810:                         $resulttext .= '</ul></li>'; 
19811:                     }
19812:                 }
19813:             }
19814:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
19815:                 my $cachetime = 24*60*60;
19816:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19817:                 if (ref($lastactref) eq 'HASH') {
19818:                     $lastactref->{'domdefaults'} = 1;
19819:                 }
19820:             }
19821:             $resulttext .= '</ul>';
19822:         } else {
19823:             $resulttext = &mt('No changes made to self-enrollment settings');
19824:         }
19825:     } else {
19826:         $resulttext = '<span class="LC_error">'.
19827:             &mt('An error occurred: [_1]',$putresult).'</span>';
19828:     }
19829:     return $resulttext;
19830: }
19831: 
19832: sub modify_wafproxy {
19833:     my ($dom,$action,$lastactref,%domconfig) = @_;
19834:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19835:     my (%othercontrol,%canset,%values,%curralias,%currvalue,@warnings,%wafproxy,
19836:         %changes,%expirecache);
19837:     foreach my $server (sort(keys(%servers))) {
19838:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
19839:         if ($serverhome eq $server) {
19840:             my $serverdom = &Apache::lonnet::host_domain($server);
19841:             if ($serverdom eq $dom) {
19842:                 $canset{$server} = 1;
19843:             }
19844:         }
19845:     }
19846:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
19847:         %{$values{$dom}} = ();
19848:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
19849:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
19850:         }
19851:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
19852:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
19853:         }
19854:     }
19855:     my $output;
19856:     if (keys(%canset)) {
19857:         %{$wafproxy{'alias'}} = ();
19858:         foreach my $key (sort(keys(%canset))) {
19859:             if ($env{'form.wafproxy_'.$dom}) {
19860:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
19861:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
19862:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
19863:                     $changes{'alias'} = 1;
19864:                 }
19865:             } else {
19866:                 $wafproxy{'alias'}{$key} = '';
19867:                 if ($curralias{$key}) {
19868:                     $changes{'alias'} = 1;
19869:                 }
19870:             }
19871:             if ($wafproxy{'alias'}{$key} eq '') {
19872:                 if ($curralias{$key}) {
19873:                     $expirecache{$key} = 1;
19874:                 }
19875:                 delete($wafproxy{'alias'}{$key});
19876:             }
19877:         }
19878:         unless (keys(%{$wafproxy{'alias'}})) {
19879:             delete($wafproxy{'alias'});
19880:         }
19881:         # Localization for values in %warn occus in &mt() calls separately.
19882:         my %warn = (
19883:                      trusted => 'trusted IP range(s)',
19884:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
19885:                      vpnext => 'IP range(s) for backend WAF connections',
19886:                    );
19887:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
19888:             my $possible = $env{'form.wafproxy_'.$item};
19889:             $possible =~ s/^\s+|\s+$//g;
19890:             if ($possible ne '') {
19891:                 if ($item eq 'remoteip') {
19892:                     if ($possible =~ /^[mhn]$/) {
19893:                         $wafproxy{$item} = $possible;
19894:                     }
19895:                 } elsif ($item eq 'ipheader') {
19896:                     if ($wafproxy{'remoteip'} eq 'h') {
19897:                         $wafproxy{$item} = $possible;
19898:                     }
19899:                 } elsif ($item eq 'sslopt') {
19900:                     if ($possible =~ /^0|1$/) {
19901:                         $wafproxy{$item} = $possible;
19902:                     }
19903:                 } else {
19904:                     my (@ok,$count);
19905:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
19906:                         unless ($env{'form.wafproxy_vpnaccess'}) {
19907:                             $possible = '';
19908:                         }
19909:                     } elsif ($item eq 'trusted') {
19910:                         unless ($wafproxy{'remoteip'} eq 'h') {
19911:                             $possible = '';
19912:                         }
19913:                     }
19914:                     unless ($possible eq '') {
19915:                         $possible =~ s/[\r\n]+/\s/g;
19916:                         $possible =~ s/\s*-\s*/-/g;
19917:                         $possible =~ s/\s+/,/g;
19918:                     }
19919:                     $count = 0;
19920:                     if ($possible ne '') {
19921:                         foreach my $poss (split(/\,/,$possible)) {
19922:                             $count ++;
19923:                             if (&validate_ip_pattern($poss)) {
19924:                                 push(@ok,$poss);
19925:                             }
19926:                         }
19927:                         if (@ok) {
19928:                             $wafproxy{$item} = join(',',@ok);
19929:                         }
19930:                         my $diff = $count - scalar(@ok);
19931:                         if ($diff) {
19932:                             push(@warnings,'<li>'.
19933:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
19934:                                      $diff,$warn{$item}).
19935:                                  '</li>');
19936:                         }
19937:                     }
19938:                 }
19939:                 if ($wafproxy{$item} ne $currvalue{$item}) {
19940:                     $changes{$item} = 1;
19941:                 }
19942:             } elsif ($currvalue{$item}) {
19943:                 $changes{$item} = 1;
19944:             } 
19945:         }
19946:     } else {
19947:         if (keys(%curralias)) {
19948:             $changes{'alias'} = 1;
19949:         } 
19950:         if (keys(%currvalue)) {
19951:             foreach my $key (keys(%currvalue)) {
19952:                 $changes{$key} = 1;
19953:             }
19954:         }
19955:     }
19956:     if (keys(%changes)) {
19957:         my %defaultshash = (
19958:                               wafproxy => \%wafproxy,
19959:                            ); 
19960:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19961:                                                  $dom);
19962:         if ($putresult eq 'ok') {
19963:             my $cachetime = 24*60*60;
19964:             my (%domdefaults,$updatedomdefs);
19965:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
19966:                 if ($changes{$item}) {
19967:                     unless ($updatedomdefs) {
19968:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
19969:                         $updatedomdefs = 1;
19970:                     }
19971:                     if ($wafproxy{$item}) {
19972:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
19973:                     } elsif (exists($domdefaults{'waf_'.$item})) {
19974:                         delete($domdefaults{'waf_'.$item});
19975:                     } 
19976:                 }
19977:             }
19978:             if ($updatedomdefs) {
19979:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19980:                 if (ref($lastactref) eq 'HASH') {
19981:                     $lastactref->{'domdefaults'} = 1;
19982:                 }
19983:             }
19984:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
19985:                 my %updates = %expirecache;
19986:                 foreach my $key (keys(%expirecache)) {
19987:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
19988:                 }
19989:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
19990:                     my $cachetime = 24*60*60;
19991:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
19992:                         $updates{$key} = 1;
19993:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
19994:                                                       $cachetime);
19995:                     }
19996:                 }
19997:                 if (ref($lastactref) eq 'HASH') {
19998:                     $lastactref->{'proxyalias'} = \%updates;
19999:                 }
20000:             }
20001:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
20002:             foreach my $item ('alias','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
20003:                 if ($changes{$item}) {
20004:                     if ($item eq 'alias') {
20005:                         my $numaliased = 0;
20006:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
20007:                             my $shown;
20008:                             if (keys(%{$wafproxy{'alias'}})) {
20009:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
20010:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
20011:                                                          &Apache::lonnet::hostname($server),
20012:                                                          $wafproxy{'alias'}{$server}).'</li>';
20013:                                     $numaliased ++;
20014:                                 }
20015:                                 if ($numaliased) {
20016:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
20017:                                                           '<ul>'.$shown.'</ul>').'</li>';
20018:                                 }
20019:                             }
20020:                         }
20021:                         unless ($numaliased) {
20022:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
20023:                         }
20024:                     } else {
20025:                         if ($item eq 'remoteip') {
20026:                             my %ip_methods = &remoteip_methods();
20027:                             if ($wafproxy{$item} =~ /^[mh]$/) {
20028:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
20029:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
20030:                             } else {
20031:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
20032:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
20033:                                                '</li>';
20034:                                 } else {
20035:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
20036:                                 }
20037:                             }
20038:                         } elsif ($item eq 'ipheader') {
20039:                             if ($wafproxy{$item}) {
20040:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
20041:                                                       $wafproxy{$item}).'</li>';
20042:                             } else {
20043:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
20044:                             }
20045:                         } elsif ($item eq 'trusted') {
20046:                             if ($wafproxy{$item}) {
20047:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
20048:                                                       $wafproxy{$item}).'</li>';
20049:                             } else {
20050:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
20051:                             }
20052:                         } elsif ($item eq 'vpnint') {
20053:                             if ($wafproxy{$item}) {
20054:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
20055:                                                        $wafproxy{$item}).'</li>';
20056:                             } else {
20057:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
20058:                             }
20059:                         } elsif ($item eq 'vpnext') {
20060:                             if ($wafproxy{$item}) {
20061:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
20062:                                                        $wafproxy{$item}).'</li>';
20063:                             } else {
20064:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
20065:                             }
20066:                         } elsif ($item eq 'sslopt') {
20067:                             if ($wafproxy{$item}) {
20068:                                 $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>';
20069:                             } else {
20070:                                 $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>';
20071:                             }
20072:                         }
20073:                     }
20074:                 }
20075:             }
20076:         } else {
20077:             $output = '<span class="LC_error">'.
20078:                       &mt('An error occurred: [_1]',$putresult).'</span>';
20079:         }
20080:     } elsif (keys(%canset)) {
20081:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
20082:     }
20083:     if (@warnings) {
20084:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
20085:                        join("\n",@warnings).'</ul>';
20086:     }
20087:     return $output;
20088: }
20089: 
20090: sub validate_ip_pattern {
20091:     my ($pattern) = @_;
20092:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
20093:         my ($start,$end) = ($1,$2);
20094:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
20095:             return 1;
20096:         }
20097:     } elsif (&Net::CIDR::cidrvalidate($pattern)) {
20098:         return 1;
20099:     }
20100:     return
20101: }
20102: 
20103: sub modify_usersessions {
20104:     my ($dom,$lastactref,%domconfig) = @_;
20105:     my @hostingtypes = ('version','excludedomain','includedomain');
20106:     my @offloadtypes = ('primary','default');
20107:     my %types = (
20108:                   remote => \@hostingtypes,
20109:                   hosted => \@hostingtypes,
20110:                   spares => \@offloadtypes,
20111:                 );
20112:     my @prefixes = ('remote','hosted','spares');
20113:     my @lcversions = &Apache::lonnet::all_loncaparevs();
20114:     my (%by_ip,%by_location,@intdoms,@instdoms);
20115:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20116:     my @locations = sort(keys(%by_location));
20117:     my (%defaultshash,%changes);
20118:     foreach my $prefix (@prefixes) {
20119:         $defaultshash{'usersessions'}{$prefix} = {};
20120:     }
20121:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20122:     my $resulttext;
20123:     my %iphost = &Apache::lonnet::get_iphost();
20124:     foreach my $prefix (@prefixes) {
20125:         next if ($prefix eq 'spares');
20126:         foreach my $type (@{$types{$prefix}}) {
20127:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20128:             if ($type eq 'version') {
20129:                 my $value = $env{'form.'.$prefix.'_'.$type};
20130:                 my $okvalue;
20131:                 if ($value ne '') {
20132:                     if (grep(/^\Q$value\E$/,@lcversions)) {
20133:                         $okvalue = $value;
20134:                     }
20135:                 }
20136:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20137:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20138:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
20139:                             if ($inuse == 0) {
20140:                                 $changes{$prefix}{$type} = 1;
20141:                             } else {
20142:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
20143:                                     $changes{$prefix}{$type} = 1;
20144:                                 }
20145:                                 if ($okvalue ne '') {
20146:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20147:                                 } 
20148:                             }
20149:                         } else {
20150:                             if (($inuse == 1) && ($okvalue ne '')) {
20151:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20152:                                 $changes{$prefix}{$type} = 1;
20153:                             }
20154:                         }
20155:                     } else {
20156:                         if (($inuse == 1) && ($okvalue ne '')) {
20157:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20158:                             $changes{$prefix}{$type} = 1;
20159:                         }
20160:                     }
20161:                 } else {
20162:                     if (($inuse == 1) && ($okvalue ne '')) {
20163:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20164:                         $changes{$prefix}{$type} = 1;
20165:                     }
20166:                 }
20167:             } else {
20168:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20169:                 my @okvals;
20170:                 foreach my $val (@vals) {
20171:                     if ($val =~ /:/) {
20172:                         my @items = split(/:/,$val);
20173:                         foreach my $item (@items) {
20174:                             if (ref($by_location{$item}) eq 'ARRAY') {
20175:                                 push(@okvals,$item);
20176:                             }
20177:                         }
20178:                     } else {
20179:                         if (ref($by_location{$val}) eq 'ARRAY') {
20180:                             push(@okvals,$val);
20181:                         }
20182:                     }
20183:                 }
20184:                 @okvals = sort(@okvals);
20185:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20186:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20187:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20188:                             if ($inuse == 0) {
20189:                                 $changes{$prefix}{$type} = 1; 
20190:                             } else {
20191:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20192:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
20193:                                 if (@changed > 0) {
20194:                                     $changes{$prefix}{$type} = 1;
20195:                                 }
20196:                             }
20197:                         } else {
20198:                             if ($inuse == 1) {
20199:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20200:                                 $changes{$prefix}{$type} = 1;
20201:                             }
20202:                         } 
20203:                     } else {
20204:                         if ($inuse == 1) {
20205:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20206:                             $changes{$prefix}{$type} = 1;
20207:                         }
20208:                     }
20209:                 } else {
20210:                     if ($inuse == 1) {
20211:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20212:                         $changes{$prefix}{$type} = 1;
20213:                     }
20214:                 }
20215:             }
20216:         }
20217:     }
20218: 
20219:     my @alldoms = &Apache::lonnet::all_domains();
20220:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20221:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
20222:     my $savespares;
20223: 
20224:     foreach my $lonhost (sort(keys(%servers))) {
20225:         my $serverhomeID =
20226:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
20227:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
20228:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
20229:         my %spareschg;
20230:         foreach my $type (@{$types{'spares'}}) {
20231:             my @okspares;
20232:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
20233:             foreach my $server (@checked) {
20234:                 if (&Apache::lonnet::hostname($server) ne '') {
20235:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
20236:                         unless (grep(/^\Q$server\E$/,@okspares)) {
20237:                             push(@okspares,$server);
20238:                         }
20239:                     }
20240:                 }
20241:             }
20242:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
20243:             my $newspare;
20244:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
20245:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
20246:                     $newspare = $new;
20247:                 }
20248:             }
20249:             my @spares;
20250:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
20251:                 @spares = sort(@okspares,$newspare);
20252:             } else {
20253:                 @spares = sort(@okspares);
20254:             }
20255:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
20256:             if (ref($spareid{$lonhost}) eq 'HASH') {
20257:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
20258:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
20259:                     if (@diffs > 0) {
20260:                         $spareschg{$type} = 1;
20261:                     }
20262:                 }
20263:             }
20264:         }
20265:         if (keys(%spareschg) > 0) {
20266:             $changes{'spares'}{$lonhost} = \%spareschg;
20267:         }
20268:     }
20269:     $defaultshash{'usersessions'}{'offloadnow'} = {};
20270:     $defaultshash{'usersessions'}{'offloadoth'} = {};
20271:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
20272:     my @okoffload;
20273:     if (@offloadnow) {
20274:         foreach my $server (@offloadnow) {
20275:             if (&Apache::lonnet::hostname($server) ne '') {
20276:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
20277:                     push(@okoffload,$server);
20278:                 }
20279:             }
20280:         }
20281:         if (@okoffload) {
20282:             foreach my $lonhost (@okoffload) {
20283:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
20284:             }
20285:         }
20286:     }
20287:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
20288:     my @okoffloadoth;
20289:     if (@offloadoth) {
20290:         foreach my $server (@offloadoth) {
20291:             if (&Apache::lonnet::hostname($server) ne '') {
20292:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
20293:                     push(@okoffloadoth,$server);
20294:                 }
20295:             }
20296:         }
20297:         if (@okoffloadoth) {
20298:             foreach my $lonhost (@okoffloadoth) {
20299:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
20300:             }
20301:         }
20302:     }
20303:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
20304:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
20305:             if (ref($changes{'spares'}) eq 'HASH') {
20306:                 if (keys(%{$changes{'spares'}}) > 0) {
20307:                     $savespares = 1;
20308:                 }
20309:             }
20310:         } else {
20311:             $savespares = 1;
20312:         }
20313:         foreach my $offload ('offloadnow','offloadoth') {
20314:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
20315:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
20316:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
20317:                         $changes{$offload} = 1;
20318:                         last;
20319:                     }
20320:                 }
20321:                 unless ($changes{$offload}) {
20322:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
20323:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
20324:                             $changes{$offload} = 1;
20325:                             last;
20326:                         }
20327:                     }
20328:                 }
20329:             } else {
20330:                 if (($offload eq 'offloadnow') && (@okoffload)) {
20331:                      $changes{'offloadnow'} = 1;
20332:                 }
20333:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
20334:                     $changes{'offloadoth'} = 1;
20335:                 }
20336:             } 
20337:         }
20338:     } else {
20339:         if (@okoffload) {
20340:             $changes{'offloadnow'} = 1;
20341:         }
20342:         if (@okoffloadoth) {
20343:             $changes{'offloadoth'} = 1;
20344:         }
20345:     }
20346:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
20347:     if ((keys(%changes) > 0) || ($savespares)) {
20348:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20349:                                                  $dom);
20350:         if ($putresult eq 'ok') {
20351:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20352:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
20353:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
20354:                 }
20355:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
20356:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
20357:                 }
20358:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20359:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
20360:                 }
20361:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20362:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
20363:                 }
20364:             }
20365:             my $cachetime = 24*60*60;
20366:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20367:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
20368:             if (ref($lastactref) eq 'HASH') {
20369:                 $lastactref->{'domdefaults'} = 1;
20370:                 $lastactref->{'usersessions'} = 1;
20371:             }
20372:             if (keys(%changes) > 0) {
20373:                 my %lt = &usersession_titles();
20374:                 $resulttext = &mt('Changes made:').'<ul>';
20375:                 foreach my $prefix (@prefixes) {
20376:                     if (ref($changes{$prefix}) eq 'HASH') {
20377:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
20378:                         if ($prefix eq 'spares') {
20379:                             if (ref($changes{$prefix}) eq 'HASH') {
20380:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
20381:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
20382:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
20383:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
20384:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
20385:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
20386:                                         foreach my $type (@{$types{$prefix}}) {
20387:                                             if ($changes{$prefix}{$lonhost}{$type}) {
20388:                                                 my $offloadto = &mt('None');
20389:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
20390:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
20391:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
20392:                                                     }
20393:                                                 }
20394:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
20395:                                             }
20396:                                         }
20397:                                     }
20398:                                     $resulttext .= '</li>';
20399:                                 }
20400:                             }
20401:                         } else {
20402:                             foreach my $type (@{$types{$prefix}}) {
20403:                                 if (defined($changes{$prefix}{$type})) {
20404:                                     my ($newvalue,$notinuse);
20405:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20406:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
20407:                                             if ($type eq 'version') {
20408:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
20409:                                             } else {
20410:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20411:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
20412:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
20413:                                                     }
20414:                                                 } else {
20415:                                                     $notinuse = 1;
20416:                                                 }
20417:                                             }
20418:                                         }
20419:                                     }
20420:                                     if ($newvalue eq '') {
20421:                                         if ($type eq 'version') {
20422:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
20423:                                         } elsif ($notinuse) {
20424:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
20425:                                         } else {
20426:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
20427:                                         }
20428:                                     } else {
20429:                                         if ($type eq 'version') {
20430:                                             $newvalue .= ' '.&mt('(or later)');
20431:                                         }
20432:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
20433:                                     }
20434:                                 }
20435:                             }
20436:                         }
20437:                         $resulttext .= '</ul>';
20438:                     }
20439:                 }
20440:                 if ($changes{'offloadnow'}) {
20441:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20442:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
20443:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
20444:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
20445:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20446:                             }
20447:                             $resulttext .= '</ul>';
20448:                         } else {
20449:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
20450:                         }
20451:                     } else {
20452:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
20453:                     }
20454:                 }
20455:                 if ($changes{'offloadoth'}) {
20456:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20457:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
20458:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
20459:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
20460:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20461:                             }
20462:                             $resulttext .= '</ul>';
20463:                         } else {
20464:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
20465:                         }
20466:                     } else {
20467:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
20468:                     }
20469:                 }
20470:                 $resulttext .= '</ul>';
20471:             } else {
20472:                 $resulttext = $nochgmsg;
20473:             }
20474:         } else {
20475:             $resulttext = '<span class="LC_error">'.
20476:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20477:         }
20478:     } else {
20479:         $resulttext = $nochgmsg;
20480:     }
20481:     return $resulttext;
20482: }
20483: 
20484: sub modify_ssl {
20485:     my ($dom,$lastactref,%domconfig) = @_;
20486:     my (%by_ip,%by_location,@intdoms,@instdoms);
20487:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20488:     my @locations = sort(keys(%by_location));
20489:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20490:     my (%defaultshash,%changes);
20491:     my $action = 'ssl';
20492:     my @prefixes = ('connto','connfrom','replication');
20493:     foreach my $prefix (@prefixes) {
20494:         $defaultshash{$action}{$prefix} = {};
20495:     }
20496:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20497:     my $resulttext;
20498:     my %iphost = &Apache::lonnet::get_iphost();
20499:     my @reptypes = ('certreq','nocertreq');
20500:     my @connecttypes = ('dom','intdom','other');
20501:     my %types = (
20502:                   connto      => \@connecttypes,
20503:                   connfrom    => \@connecttypes,
20504:                   replication => \@reptypes,
20505:                 );
20506:     foreach my $prefix (sort(keys(%types))) {
20507:         foreach my $type (@{$types{$prefix}}) {
20508:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
20509:                 my $value = 'yes';
20510:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
20511:                     $value = $env{'form.'.$prefix.'_'.$type};
20512:                 }
20513:                 if (ref($domconfig{$action}) eq 'HASH') {
20514:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
20515:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
20516:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
20517:                                 $changes{$prefix}{$type} = 1;
20518:                             }
20519:                             $defaultshash{$action}{$prefix}{$type} = $value;
20520:                         } else {
20521:                             $defaultshash{$action}{$prefix}{$type} = $value;
20522:                             $changes{$prefix}{$type} = 1;
20523:                         }
20524:                     } else {
20525:                         $defaultshash{$action}{$prefix}{$type} = $value;
20526:                         $changes{$prefix}{$type} = 1;
20527:                     }
20528:                 } else {
20529:                     $defaultshash{$action}{$prefix}{$type} = $value;
20530:                     $changes{$prefix}{$type} = 1;
20531:                 }
20532:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
20533:                     delete($changes{$prefix}{$type});
20534:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
20535:                     delete($changes{$prefix}{$type});
20536:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
20537:                     delete($changes{$prefix}{$type});
20538:                 }
20539:             } elsif ($prefix eq 'replication') {
20540:                 if (@locations > 0) {
20541:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20542:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20543:                     my @okvals;
20544:                     foreach my $val (@vals) {
20545:                         if ($val =~ /:/) {
20546:                             my @items = split(/:/,$val);
20547:                             foreach my $item (@items) {
20548:                                 if (ref($by_location{$item}) eq 'ARRAY') {
20549:                                     push(@okvals,$item);
20550:                                 }
20551:                             }
20552:                         } else {
20553:                             if (ref($by_location{$val}) eq 'ARRAY') {
20554:                                 push(@okvals,$val);
20555:                             }
20556:                         }
20557:                     }
20558:                     @okvals = sort(@okvals);
20559:                     if (ref($domconfig{$action}) eq 'HASH') {
20560:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
20561:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
20562:                                 if ($inuse == 0) {
20563:                                     $changes{$prefix}{$type} = 1;
20564:                                 } else {
20565:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
20566:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
20567:                                     if (@changed > 0) {
20568:                                         $changes{$prefix}{$type} = 1;
20569:                                     }
20570:                                 }
20571:                             } else {
20572:                                 if ($inuse == 1) {
20573:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
20574:                                     $changes{$prefix}{$type} = 1;
20575:                                 }
20576:                             }
20577:                         } else {
20578:                             if ($inuse == 1) {
20579:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
20580:                                 $changes{$prefix}{$type} = 1;
20581:                             }
20582:                         }
20583:                     } else {
20584:                         if ($inuse == 1) {
20585:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
20586:                             $changes{$prefix}{$type} = 1;
20587:                         }
20588:                     }
20589:                 }
20590:             }
20591:         }
20592:     }
20593:     if (keys(%changes)) {
20594:         foreach my $prefix (keys(%changes)) {
20595:             if (ref($changes{$prefix}) eq 'HASH') {
20596:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
20597:                     delete($changes{$prefix});
20598:                 }
20599:             } else {
20600:                 delete($changes{$prefix});
20601:             }
20602:         }
20603:     }
20604:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
20605:     if (keys(%changes) > 0) {
20606:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20607:                                                  $dom);
20608:         if ($putresult eq 'ok') {
20609:             if (ref($defaultshash{$action}) eq 'HASH') {
20610:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
20611:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
20612:                 }
20613:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
20614:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
20615:                 }
20616:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
20617:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
20618:                 }
20619:             }
20620:             my $cachetime = 24*60*60;
20621:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20622:             if (ref($lastactref) eq 'HASH') {
20623:                 $lastactref->{'domdefaults'} = 1;
20624:             }
20625:             if (keys(%changes) > 0) {
20626:                 my %titles = &ssl_titles();
20627:                 $resulttext = &mt('Changes made:').'<ul>';
20628:                 foreach my $prefix (@prefixes) {
20629:                     if (ref($changes{$prefix}) eq 'HASH') {
20630:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
20631:                         foreach my $type (@{$types{$prefix}}) {
20632:                             if (defined($changes{$prefix}{$type})) {
20633:                                 my ($newvalue,$notinuse);
20634:                                 if (ref($defaultshash{$action}) eq 'HASH') {
20635:                                     if (ref($defaultshash{$action}{$prefix})) {
20636:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
20637:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
20638:                                         } else {
20639:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
20640:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
20641:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
20642:                                                 }
20643:                                             } else {
20644:                                                 $notinuse = 1;
20645:                                             }
20646:                                         }
20647:                                     }
20648:                                     if ($notinuse) {
20649:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
20650:                                     } elsif ($newvalue eq '') {
20651:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
20652:                                     } else {
20653:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
20654:                                     }
20655:                                 }
20656:                             }
20657:                         }
20658:                         $resulttext .= '</ul>';
20659:                     }
20660:                 }
20661:             } else {
20662:                 $resulttext = $nochgmsg;
20663:             }
20664:         } else {
20665:             $resulttext = '<span class="LC_error">'.
20666:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20667:         }
20668:     } else {
20669:         $resulttext = $nochgmsg;
20670:     }
20671:     return $resulttext;
20672: }
20673: 
20674: sub modify_trust {
20675:     my ($dom,$lastactref,%domconfig) = @_;
20676:     my (%by_ip,%by_location,@intdoms,@instdoms);
20677:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20678:     my @locations = sort(keys(%by_location));
20679:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
20680:     my @types = ('exc','inc');
20681:     my (%defaultshash,%changes);
20682:     foreach my $prefix (@prefixes) {
20683:         $defaultshash{'trust'}{$prefix} = {};
20684:     }
20685:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20686:     my $resulttext;
20687:     foreach my $prefix (@prefixes) {
20688:         foreach my $type (@types) {
20689:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20690:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20691:             my @okvals;
20692:             foreach my $val (@vals) {
20693:                 if ($val =~ /:/) {
20694:                     my @items = split(/:/,$val);
20695:                     foreach my $item (@items) {
20696:                         if (ref($by_location{$item}) eq 'ARRAY') {
20697:                             push(@okvals,$item);
20698:                         }
20699:                     }
20700:                 } else {
20701:                     if (ref($by_location{$val}) eq 'ARRAY') {
20702:                         push(@okvals,$val);
20703:                     }
20704:                 }
20705:             }
20706:             @okvals = sort(@okvals);
20707:             if (ref($domconfig{'trust'}) eq 'HASH') {
20708:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
20709:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
20710:                         if ($inuse == 0) {
20711:                             $changes{$prefix}{$type} = 1;
20712:                         } else {
20713:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20714:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
20715:                             if (@changed > 0) {
20716:                                 $changes{$prefix}{$type} = 1;
20717:                             }
20718:                         }
20719:                     } else {
20720:                         if ($inuse == 1) {
20721:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20722:                             $changes{$prefix}{$type} = 1;
20723:                         }
20724:                     }
20725:                 } else {
20726:                     if ($inuse == 1) {
20727:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20728:                         $changes{$prefix}{$type} = 1;
20729:                     }
20730:                 }
20731:             } else {
20732:                 if ($inuse == 1) {
20733:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20734:                     $changes{$prefix}{$type} = 1;
20735:                 }
20736:             }
20737:         }
20738:     }
20739:     my $nochgmsg = &mt('No changes made to trust settings.');
20740:     if (keys(%changes) > 0) {
20741:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20742:                                                  $dom);
20743:         if ($putresult eq 'ok') {
20744:             if (ref($defaultshash{'trust'}) eq 'HASH') {
20745:                 foreach my $prefix (@prefixes) {
20746:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
20747:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
20748:                     }
20749:                 }
20750:             }
20751:             my $cachetime = 24*60*60;
20752:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20753:             if (ref($lastactref) eq 'HASH') {
20754:                 $lastactref->{'domdefaults'} = 1;
20755:             }
20756:             if (keys(%changes) > 0) {
20757:                 my %lt = &trust_titles();
20758:                 $resulttext = &mt('Changes made:').'<ul>';
20759:                 foreach my $prefix (@prefixes) {
20760:                     if (ref($changes{$prefix}) eq 'HASH') {
20761:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
20762:                         foreach my $type (@types) {
20763:                             if (defined($changes{$prefix}{$type})) {
20764:                                 my ($newvalue,$notinuse);
20765:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
20766:                                     if (ref($defaultshash{'trust'}{$prefix})) {
20767:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
20768:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
20769:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
20770:                                             }
20771:                                         } else {
20772:                                             $notinuse = 1;
20773:                                         }
20774:                                     }
20775:                                 }
20776:                                 if ($notinuse) {
20777:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
20778:                                 } elsif ($newvalue eq '') {
20779:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
20780:                                 } else {
20781:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
20782:                                 }
20783:                             }
20784:                         }
20785:                         $resulttext .= '</ul>';
20786:                     }
20787:                 }
20788:                 $resulttext .= '</ul>';
20789:             } else {
20790:                 $resulttext = $nochgmsg;
20791:             }
20792:         } else {
20793:             $resulttext = '<span class="LC_error">'.
20794:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20795:         }
20796:     } else {
20797:         $resulttext = $nochgmsg;
20798:     }
20799:     return $resulttext;
20800: }
20801: 
20802: sub modify_loadbalancing {
20803:     my ($dom,%domconfig) = @_;
20804:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
20805:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
20806:     my ($othertitle,$usertypes,$types) =
20807:         &Apache::loncommon::sorted_inst_types($dom);
20808:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20809:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
20810:     my @sparestypes = ('primary','default');
20811:     my %typetitles = &sparestype_titles();
20812:     my $resulttext;
20813:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
20814:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
20815:         %existing = %{$domconfig{'loadbalancing'}};
20816:     }
20817:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
20818:                               \%currtargets,\%currrules,\%currcookies);
20819:     my ($saveloadbalancing,%defaultshash,%changes);
20820:     my ($alltypes,$othertypes,$titles) =
20821:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
20822:     my %ruletitles = &offloadtype_text();
20823:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
20824:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
20825:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
20826:         if ($balancer eq '') {
20827:             next;
20828:         }
20829:         if (!exists($servers{$balancer})) {
20830:             if (exists($currbalancer{$balancer})) {
20831:                 push(@{$changes{'delete'}},$balancer);
20832:             }
20833:             next;
20834:         }
20835:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
20836:             push(@{$changes{'delete'}},$balancer);
20837:             next;
20838:         }
20839:         if (!exists($currbalancer{$balancer})) {
20840:             push(@{$changes{'add'}},$balancer);
20841:         }
20842:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
20843:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
20844:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
20845:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
20846:             $saveloadbalancing = 1;
20847:         }
20848:         foreach my $sparetype (@sparestypes) {
20849:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
20850:             my @offloadto;
20851:             foreach my $target (@targets) {
20852:                 if (($servers{$target}) && ($target ne $balancer)) {
20853:                     if ($sparetype eq 'default') {
20854:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
20855:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
20856:                         }
20857:                     }
20858:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
20859:                         push(@offloadto,$target);
20860:                     }
20861:                 }
20862:             }
20863:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
20864:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
20865:                     push(@offloadto,$balancer);
20866:                 }
20867:             }
20868:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
20869:         }
20870:         if ($env{'form.loadbalancing_cookie_'.$i}) {
20871:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
20872:             if (exists($currbalancer{$balancer})) { 
20873:                 unless ($currcookies{$balancer}) {
20874:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
20875:                 }
20876:             }
20877:         } elsif (exists($currbalancer{$balancer})) {
20878:             if ($currcookies{$balancer}) {
20879:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
20880:             }
20881:         }
20882:         if (ref($currtargets{$balancer}) eq 'HASH') {
20883:             foreach my $sparetype (@sparestypes) {
20884:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
20885:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
20886:                     if (@targetdiffs > 0) {
20887:                         $changes{'curr'}{$balancer}{'targets'} = 1;
20888:                     }
20889:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20890:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
20891:                         $changes{'curr'}{$balancer}{'targets'} = 1;
20892:                     }
20893:                 }
20894:             }
20895:         } else {
20896:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
20897:                 foreach my $sparetype (@sparestypes) {
20898:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20899:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
20900:                             $changes{'curr'}{$balancer}{'targets'} = 1;
20901:                         }
20902:                     }
20903:                 }
20904:             }
20905:         }
20906:         my $ishomedom;
20907:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
20908:             $ishomedom = 1;
20909:         }
20910:         if (ref($alltypes) eq 'ARRAY') {
20911:             foreach my $type (@{$alltypes}) {
20912:                 my $rule;
20913:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
20914:                          (!$ishomedom)) {
20915:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
20916:                 }
20917:                 if ($rule eq 'specific') {
20918:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
20919:                     if (exists($servers{$specifiedhost})) {
20920:                         $rule = $specifiedhost;
20921:                     }
20922:                 }
20923:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
20924:                 if (ref($currrules{$balancer}) eq 'HASH') {
20925:                     if ($rule ne $currrules{$balancer}{$type}) {
20926:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
20927:                     }
20928:                 } elsif ($rule ne '') {
20929:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
20930:                 }
20931:             }
20932:         }
20933:     }
20934:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
20935:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
20936:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
20937:             $defaultshash{'loadbalancing'} = {};
20938:         }
20939:         my $putresult = &Apache::lonnet::put_dom('configuration',
20940:                                                  \%defaultshash,$dom);
20941:         if ($putresult eq 'ok') {
20942:             if (keys(%changes) > 0) {
20943:                 my %toupdate;
20944:                 if (ref($changes{'delete'}) eq 'ARRAY') {
20945:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
20946:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
20947:                         $toupdate{$balancer} = 1;
20948:                     }
20949:                 }
20950:                 if (ref($changes{'add'}) eq 'ARRAY') {
20951:                     foreach my $balancer (sort(@{$changes{'add'}})) {
20952:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
20953:                         $toupdate{$balancer} = 1;
20954:                     }
20955:                 }
20956:                 if (ref($changes{'curr'}) eq 'HASH') {
20957:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
20958:                         $toupdate{$balancer} = 1;
20959:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
20960:                             if ($changes{'curr'}{$balancer}{'targets'}) {
20961:                                 my %offloadstr;
20962:                                 foreach my $sparetype (@sparestypes) {
20963:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20964:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
20965:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
20966:                                         }
20967:                                     }
20968:                                 }
20969:                                 if (keys(%offloadstr) == 0) {
20970:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
20971:                                 } else {
20972:                                     my $showoffload;
20973:                                     foreach my $sparetype (@sparestypes) {
20974:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
20975:                                         if (defined($offloadstr{$sparetype})) {
20976:                                             $showoffload .= $offloadstr{$sparetype};
20977:                                         } else {
20978:                                             $showoffload .= &mt('None');
20979:                                         }
20980:                                         $showoffload .= ('&nbsp;'x3);
20981:                                     }
20982:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
20983:                                 }
20984:                             }
20985:                         }
20986:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
20987:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
20988:                                 foreach my $type (@{$alltypes}) {
20989:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
20990:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
20991:                                         my $balancetext;
20992:                                         if ($rule eq '') {
20993:                                             $balancetext =  $ruletitles{'default'};
20994:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
20995:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
20996:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
20997:                                                 foreach my $sparetype (@sparestypes) {
20998:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20999:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
21000:                                                     }
21001:                                                 }
21002:                                                 foreach my $item (@{$alltypes}) {
21003:                                                     next if ($item =~  /^_LC_ipchange/);
21004:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
21005:                                                     if ($hasrule eq 'homeserver') {
21006:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
21007:                                                     } else {
21008:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
21009:                                                             if ($servers{$hasrule}) {
21010:                                                                 $toupdate{$hasrule} = 1;
21011:                                                             }
21012:                                                         }
21013:                                                     }
21014:                                                 }
21015:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
21016:                                                     $balancetext =  $ruletitles{$rule};
21017:                                                 } else {
21018:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
21019:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
21020:                                                     if ($receiver) {
21021:                                                         $toupdate{$receiver};
21022:                                                     }
21023:                                                 }
21024:                                             } else {
21025:                                                 $balancetext =  $ruletitles{$rule};
21026:                                             }
21027:                                         } else {
21028:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
21029:                                         }
21030:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
21031:                                     }
21032:                                 }
21033:                             }
21034:                         }
21035:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
21036:                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
21037:                                                       $balancer).'</li>'; 
21038:                         }
21039:                     }
21040:                 }
21041:                 if (keys(%toupdate)) {
21042:                     my %thismachine;
21043:                     my $updatedhere;
21044:                     my $cachetime = 60*60*24;
21045:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
21046:                     foreach my $lonhost (keys(%toupdate)) {
21047:                         if ($thismachine{$lonhost}) {
21048:                             unless ($updatedhere) {
21049:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
21050:                                                               $defaultshash{'loadbalancing'},
21051:                                                               $cachetime);
21052:                                 $updatedhere = 1;
21053:                             }
21054:                         } else {
21055:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
21056:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
21057:                         }
21058:                     }
21059:                 }
21060:                 if ($resulttext ne '') {
21061:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
21062:                 } else {
21063:                     $resulttext = $nochgmsg;
21064:                 }
21065:             } else {
21066:                 $resulttext = $nochgmsg;
21067:             }
21068:         } else {
21069:             $resulttext = '<span class="LC_error">'.
21070:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21071:         }
21072:     } else {
21073:         $resulttext = $nochgmsg;
21074:     }
21075:     return $resulttext;
21076: }
21077: 
21078: sub recurse_check {
21079:     my ($chkcats,$categories,$depth,$name) = @_;
21080:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
21081:         my $chg = 0;
21082:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
21083:             my $category = $chkcats->[$depth]{$name}[$j];
21084:             my $item;
21085:             if ($category eq '') {
21086:                 $chg ++;
21087:             } else {
21088:                 my $deeper = $depth + 1;
21089:                 $item = &escape($category).':'.&escape($name).':'.$depth;
21090:                 if ($chg) {
21091:                     $categories->{$item} -= $chg;
21092:                 }
21093:                 &recurse_check($chkcats,$categories,$deeper,$category);
21094:                 $deeper --;
21095:             }
21096:         }
21097:     }
21098:     return;
21099: }
21100: 
21101: sub recurse_cat_deletes {
21102:     my ($item,$coursecategories,$deletions) = @_;
21103:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
21104:     my $subdepth = $depth + 1;
21105:     if (ref($coursecategories) eq 'HASH') {
21106:         foreach my $subitem (keys(%{$coursecategories})) {
21107:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
21108:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
21109:                 delete($coursecategories->{$subitem});
21110:                 $deletions->{$subitem} = 1;
21111:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
21112:             }
21113:         }
21114:     }
21115:     return;
21116: }
21117: 
21118: sub active_dc_picker {
21119:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
21120:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
21121:     my @domcoord = keys(%domcoords);
21122:     if (keys(%currhash)) {
21123:         foreach my $dc (keys(%currhash)) {
21124:             unless (exists($domcoords{$dc})) {
21125:                 push(@domcoord,$dc);
21126:             }
21127:         }
21128:     }
21129:     @domcoord = sort(@domcoord);
21130:     my $numdcs = scalar(@domcoord);
21131:     my $rows = 0;
21132:     my $table;
21133:     if ($numdcs > 1) {
21134:         $table = '<table>';
21135:         for (my $i=0; $i<@domcoord; $i++) {
21136:             my $rem = $i%($numinrow);
21137:             if ($rem == 0) {
21138:                 if ($i > 0) {
21139:                     $table .= '</tr>';
21140:                 }
21141:                 $table .= '<tr>';
21142:                 $rows ++;
21143:             }
21144:             my $check = '';
21145:             if ($inputtype eq 'radio') {
21146:                 if (keys(%currhash) == 0) {
21147:                     if (!$i) {
21148:                         $check = ' checked="checked"';
21149:                     }
21150:                 } elsif (exists($currhash{$domcoord[$i]})) {
21151:                     $check = ' checked="checked"';
21152:                 }
21153:             } else {
21154:                 if (exists($currhash{$domcoord[$i]})) {
21155:                     $check = ' checked="checked"';
21156:                 }
21157:             }
21158:             if ($i == @domcoord - 1) {
21159:                 my $colsleft = $numinrow - $rem;
21160:                 if ($colsleft > 1) {
21161:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
21162:                 } else {
21163:                     $table .= '<td class="LC_left_item">';
21164:                 }
21165:             } else {
21166:                 $table .= '<td class="LC_left_item">';
21167:             }
21168:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
21169:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21170:             $table .= '<span class="LC_nobreak"><label>'.
21171:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
21172:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
21173:             if ($user ne $dcname.':'.$dcdom) {
21174:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21175:             }
21176:             $table .= '</label></span></td>';
21177:         }
21178:         $table .= '</tr></table>';
21179:     } elsif ($numdcs == 1) {
21180:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
21181:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21182:         if ($inputtype eq 'radio') {
21183:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
21184:             if ($user ne $dcname.':'.$dcdom) {
21185:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21186:             }
21187:         } else {
21188:             my $check;
21189:             if (exists($currhash{$domcoord[0]})) {
21190:                 $check = ' checked="checked"';
21191:             }
21192:             $table = '<span class="LC_nobreak"><label>'.
21193:                      '<input type="checkbox" name="'.$name.'" '.
21194:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
21195:             if ($user ne $dcname.':'.$dcdom) {
21196:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21197:             }
21198:             $table .= '</label></span>';
21199:             $rows ++;
21200:         }
21201:     }
21202:     return ($numdcs,$table,$rows);
21203: }
21204: 
21205: sub usersession_titles {
21206:     return &Apache::lonlocal::texthash(
21207:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
21208:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
21209:                spares => 'Servers offloaded to, when busy',
21210:                version => 'LON-CAPA version requirement',
21211:                excludedomain => 'Allow all, but exclude specific domains',
21212:                includedomain => 'Deny all, but include specific domains',
21213:                primary => 'Primary (checked first)',
21214:                default => 'Default',
21215:            );
21216: }
21217: 
21218: sub id_for_thisdom {
21219:     my (%servers) = @_;
21220:     my %altids;
21221:     foreach my $server (keys(%servers)) {
21222:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21223:         if ($serverhome ne $server) {
21224:             $altids{$serverhome} = $server;
21225:         }
21226:     }
21227:     return %altids;
21228: }
21229: 
21230: sub count_servers {
21231:     my ($currbalancer,%servers) = @_;
21232:     my (@spares,$numspares);
21233:     foreach my $lonhost (sort(keys(%servers))) {
21234:         next if ($currbalancer eq $lonhost);
21235:         push(@spares,$lonhost);
21236:     }
21237:     if ($currbalancer) {
21238:         $numspares = scalar(@spares);
21239:     } else {
21240:         $numspares = scalar(@spares) - 1;
21241:     }
21242:     return ($numspares,@spares);
21243: }
21244: 
21245: sub lonbalance_targets_js {
21246:     my ($dom,$types,$servers,$settings) = @_;
21247:     my $select = &mt('Select');
21248:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
21249:     if (ref($servers) eq 'HASH') {
21250:         $alltargets = join("','",sort(keys(%{$servers})));
21251:         my @homedoms;
21252:         foreach my $server (sort(keys(%{$servers}))) {
21253:             if (&Apache::lonnet::host_domain($server) eq $dom) {
21254:                 push(@homedoms,'1');
21255:             } else {
21256:                 push(@homedoms,'0');
21257:             }
21258:         }
21259:         $allishome = join("','",@homedoms);
21260:     }
21261:     if (ref($types) eq 'ARRAY') {
21262:         if (@{$types} > 0) {
21263:             @alltypes = @{$types};
21264:         }
21265:     }
21266:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
21267:     $allinsttypes = join("','",@alltypes);
21268:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
21269:     if (ref($settings) eq 'HASH') {
21270:         %existing = %{$settings};
21271:     }
21272:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
21273:                               \%currtargets,\%currrules,\%currcookies);
21274:     my $balancers = join("','",sort(keys(%currbalancer)));
21275:     return <<"END";
21276: 
21277: <script type="text/javascript">
21278: // <![CDATA[
21279: 
21280: currBalancers = new Array('$balancers');
21281: 
21282: function toggleTargets(balnum) {
21283:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21284:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
21285:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
21286:     var prevbalancer = prevhostitem.value;
21287:     var baltotal = document.getElementById('loadbalancing_total').value;
21288:     prevhostitem.value = balancer;
21289:     if (prevbalancer != '') {
21290:         var prevIdx = currBalancers.indexOf(prevbalancer);
21291:         if (prevIdx != -1) {
21292:             currBalancers.splice(prevIdx,1);
21293:         }
21294:     }
21295:     if (balancer == '') {
21296:         hideSpares(balnum);
21297:     } else {
21298:         var currIdx = currBalancers.indexOf(balancer);
21299:         if (currIdx == -1) {
21300:             currBalancers.push(balancer);
21301:         }
21302:         var homedoms = new Array('$allishome');
21303:         var ishomedom = homedoms[lonhostitem.selectedIndex];
21304:         showSpares(balancer,ishomedom,balnum);
21305:     }
21306:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
21307:     return;
21308: }
21309: 
21310: function showSpares(balancer,ishomedom,balnum) {
21311:     var alltargets = new Array('$alltargets');
21312:     var insttypes = new Array('$allinsttypes');
21313:     var offloadtypes = new Array('primary','default');
21314: 
21315:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
21316:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
21317:  
21318:     for (var i=0; i<offloadtypes.length; i++) {
21319:         var count = 0;
21320:         for (var j=0; j<alltargets.length; j++) {
21321:             if (alltargets[j] != balancer) {
21322:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
21323:                 item.value = alltargets[j];
21324:                 item.style.textAlign='left';
21325:                 item.style.textFace='normal';
21326:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
21327:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
21328:                     item.disabled = '';
21329:                 } else {
21330:                     item.disabled = 'disabled';
21331:                     item.checked = false;
21332:                 }
21333:                 count ++;
21334:             }
21335:         }
21336:     }
21337:     for (var k=0; k<insttypes.length; k++) {
21338:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
21339:             if (ishomedom == 1) {
21340:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21341:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21342:             } else {
21343:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21344:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21345:             }
21346:         } else {
21347:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21348:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21349:         }
21350:         if ((insttypes[k] != '_LC_external') && 
21351:             ((insttypes[k] != '_LC_internetdom') ||
21352:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
21353:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
21354:             item.options.length = 0;
21355:             item.options[0] = new Option("","",true,true);
21356:             var idx = 0;
21357:             for (var m=0; m<alltargets.length; m++) {
21358:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
21359:                     idx ++;
21360:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
21361:                 }
21362:             }
21363:         }
21364:     }
21365:     return;
21366: }
21367: 
21368: function hideSpares(balnum) {
21369:     var alltargets = new Array('$alltargets');
21370:     var insttypes = new Array('$allinsttypes');
21371:     var offloadtypes = new Array('primary','default');
21372: 
21373:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
21374:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
21375: 
21376:     var total = alltargets.length - 1;
21377:     for (var i=0; i<offloadtypes; i++) {
21378:         for (var j=0; j<total; j++) {
21379:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
21380:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
21381:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
21382:         }
21383:     }
21384:     for (var k=0; k<insttypes.length; k++) {
21385:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21386:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21387:         if (insttypes[k] != '_LC_external') {
21388:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
21389:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
21390:         }
21391:     }
21392:     return;
21393: }
21394: 
21395: function checkOffloads(item,balnum,type) {
21396:     var alltargets = new Array('$alltargets');
21397:     var offloadtypes = new Array('primary','default');
21398:     if (item.checked) {
21399:         var total = alltargets.length - 1;
21400:         var other;
21401:         if (type == offloadtypes[0]) {
21402:             other = offloadtypes[1];
21403:         } else {
21404:             other = offloadtypes[0];
21405:         }
21406:         for (var i=0; i<total; i++) {
21407:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
21408:             if (server == item.value) {
21409:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
21410:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
21411:                 }
21412:             }
21413:         }
21414:     }
21415:     return;
21416: }
21417: 
21418: function singleServerToggle(balnum,type) {
21419:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
21420:     if (offloadtoSelIdx == 0) {
21421:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
21422:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21423: 
21424:     } else {
21425:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
21426:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21427:     }
21428:     return;
21429: }
21430: 
21431: function balanceruleChange(formname,balnum,type) {
21432:     if (type == '_LC_external') {
21433:         return;
21434:     }
21435:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
21436:     for (var i=0; i<typesRules.length; i++) {
21437:         if (formname.elements[typesRules[i]].checked) {
21438:             if (formname.elements[typesRules[i]].value != 'specific') {
21439:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
21440:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21441:             } else {
21442:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21443:             }
21444:         }
21445:     }
21446:     return;
21447: }
21448: 
21449: function balancerDeleteChange(balnum) {
21450:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21451:     var baltotal = document.getElementById('loadbalancing_total').value;
21452:     var addtarget;
21453:     var removetarget;
21454:     var action = 'delete';
21455:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
21456:         var lonhost = hostitem.value;
21457:         var currIdx = currBalancers.indexOf(lonhost);
21458:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
21459:             if (currIdx != -1) {
21460:                 currBalancers.splice(currIdx,1);
21461:             }
21462:             addtarget = lonhost;
21463:         } else {
21464:             if (currIdx == -1) {
21465:                 currBalancers.push(lonhost);
21466:             }
21467:             removetarget = lonhost;
21468:             action = 'undelete';
21469:         }
21470:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
21471:     }
21472:     return;
21473: }
21474: 
21475: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
21476:     if (baltotal > 1) {
21477:         var offloadtypes = new Array('primary','default');
21478:         var alltargets = new Array('$alltargets');
21479:         var insttypes = new Array('$allinsttypes');
21480:         for (var i=0; i<baltotal; i++) {
21481:             if (i != balnum) {
21482:                 for (var j=0; j<offloadtypes.length; j++) {
21483:                     var total = alltargets.length - 1;
21484:                     for (var k=0; k<total; k++) {
21485:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
21486:                         var server = serveritem.value;
21487:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
21488:                             if (server == addtarget) {
21489:                                 serveritem.disabled = '';
21490:                             }
21491:                         }
21492:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
21493:                             if (server == removetarget) {
21494:                                 serveritem.disabled = 'disabled';
21495:                                 serveritem.checked = false;
21496:                             }
21497:                         }
21498:                     }
21499:                 }
21500:                 for (var j=0; j<insttypes.length; j++) {
21501:                     if (insttypes[j] != '_LC_external') {
21502:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
21503:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
21504:                             var currSel = singleserver.selectedIndex;
21505:                             var currVal = singleserver.options[currSel].value;
21506:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
21507:                                 var numoptions = singleserver.options.length;
21508:                                 var needsnew = 1;
21509:                                 for (var k=0; k<numoptions; k++) {
21510:                                     if (singleserver.options[k] == addtarget) {
21511:                                         needsnew = 0;
21512:                                         break;
21513:                                     }
21514:                                 }
21515:                                 if (needsnew == 1) {
21516:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
21517:                                 }
21518:                             }
21519:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
21520:                                 singleserver.options.length = 0;
21521:                                 if ((currVal) && (currVal != removetarget)) {
21522:                                     singleserver.options[0] = new Option("","",false,false);
21523:                                 } else {
21524:                                     singleserver.options[0] = new Option("","",true,true);
21525:                                 }
21526:                                 var idx = 0;
21527:                                 for (var m=0; m<alltargets.length; m++) {
21528:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
21529:                                         idx ++;
21530:                                         if (currVal == alltargets[m]) {
21531:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
21532:                                         } else {
21533:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
21534:                                         }
21535:                                     }
21536:                                 }
21537:                             }
21538:                         }
21539:                     }
21540:                 }
21541:             }
21542:         }
21543:     }
21544:     return;
21545: }
21546: 
21547: // ]]>
21548: </script>
21549: 
21550: END
21551: }
21552: 
21553: 
21554: sub new_spares_js {
21555:     my @sparestypes = ('primary','default');
21556:     my $types = join("','",@sparestypes);
21557:     my $select = &mt('Select');
21558:     return <<"END";
21559: 
21560: <script type="text/javascript">
21561: // <![CDATA[
21562: 
21563: function updateNewSpares(formname,lonhost) {
21564:     var types = new Array('$types');
21565:     var include = new Array();
21566:     var exclude = new Array();
21567:     for (var i=0; i<types.length; i++) {
21568:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
21569:         for (var j=0; j<spareboxes.length; j++) {
21570:             if (formname.elements[spareboxes[j]].checked) {
21571:                 exclude.push(formname.elements[spareboxes[j]].value);
21572:             } else {
21573:                 include.push(formname.elements[spareboxes[j]].value);
21574:             }
21575:         }
21576:     }
21577:     for (var i=0; i<types.length; i++) {
21578:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
21579:         var selIdx = newSpare.selectedIndex;
21580:         var currnew = newSpare.options[selIdx].value;
21581:         var okSpares = new Array();
21582:         for (var j=0; j<newSpare.options.length; j++) {
21583:             var possible = newSpare.options[j].value;
21584:             if (possible != '') {
21585:                 if (exclude.indexOf(possible) == -1) {
21586:                     okSpares.push(possible);
21587:                 } else {
21588:                     if (currnew == possible) {
21589:                         selIdx = 0;
21590:                     }
21591:                 }
21592:             }
21593:         }
21594:         for (var k=0; k<include.length; k++) {
21595:             if (okSpares.indexOf(include[k]) == -1) {
21596:                 okSpares.push(include[k]);
21597:             }
21598:         }
21599:         okSpares.sort();
21600:         newSpare.options.length = 0;
21601:         if (selIdx == 0) {
21602:             newSpare.options[0] = new Option("$select","",true,true);
21603:         } else {
21604:             newSpare.options[0] = new Option("$select","",false,false);
21605:         }
21606:         for (var m=0; m<okSpares.length; m++) {
21607:             var idx = m+1;
21608:             var selThis = 0;
21609:             if (selIdx != 0) {
21610:                 if (okSpares[m] == currnew) {
21611:                     selThis = 1;
21612:                 }
21613:             }
21614:             if (selThis == 1) {
21615:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
21616:             } else {
21617:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
21618:             }
21619:         }
21620:     }
21621:     return;
21622: }
21623: 
21624: function checkNewSpares(lonhost,type) {
21625:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
21626:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
21627:     if (chosen != '') {
21628:         var othertype;
21629:         var othernewSpare;
21630:         if (type == 'primary') {
21631:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
21632:         }
21633:         if (type == 'default') {
21634:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
21635:         }
21636:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
21637:             othernewSpare.selectedIndex = 0;
21638:         }
21639:     }
21640:     return;
21641: }
21642: 
21643: // ]]>
21644: </script>
21645: 
21646: END
21647: 
21648: }
21649: 
21650: sub common_domprefs_js {
21651:     return <<"END";
21652: 
21653: <script type="text/javascript">
21654: // <![CDATA[
21655: 
21656: function getIndicesByName(formname,item) {
21657:     var group = new Array();
21658:     for (var i=0;i<formname.elements.length;i++) {
21659:         if (formname.elements[i].name == item) {
21660:             group.push(formname.elements[i].id);
21661:         }
21662:     }
21663:     return group;
21664: }
21665: 
21666: // ]]>
21667: </script>
21668: 
21669: END
21670: 
21671: }
21672: 
21673: sub recaptcha_js {
21674:     my %lt = &captcha_phrases();
21675:     return <<"END";
21676: 
21677: <script type="text/javascript">
21678: // <![CDATA[
21679: 
21680: function updateCaptcha(caller,context) {
21681:     var privitem;
21682:     var pubitem;
21683:     var privtext;
21684:     var pubtext;
21685:     var versionitem;
21686:     var versiontext;
21687:     if (document.getElementById(context+'_recaptchapub')) {
21688:         pubitem = document.getElementById(context+'_recaptchapub');
21689:     } else {
21690:         return;
21691:     }
21692:     if (document.getElementById(context+'_recaptchapriv')) {
21693:         privitem = document.getElementById(context+'_recaptchapriv');
21694:     } else {
21695:         return;
21696:     }
21697:     if (document.getElementById(context+'_recaptchapubtxt')) {
21698:         pubtext = document.getElementById(context+'_recaptchapubtxt');
21699:     } else {
21700:         return;
21701:     }
21702:     if (document.getElementById(context+'_recaptchaprivtxt')) {
21703:         privtext = document.getElementById(context+'_recaptchaprivtxt');
21704:     } else {
21705:         return;
21706:     }
21707:     if (document.getElementById(context+'_recaptchaversion')) {
21708:         versionitem = document.getElementById(context+'_recaptchaversion');
21709:     } else {
21710:         return;
21711:     }
21712:     if (document.getElementById(context+'_recaptchavertxt')) {
21713:         versiontext = document.getElementById(context+'_recaptchavertxt');
21714:     } else {
21715:         return;
21716:     }
21717:     if (caller.checked) {
21718:         if (caller.value == 'recaptcha') {
21719:             pubitem.type = 'text';
21720:             privitem.type = 'text';
21721:             pubitem.size = '40';
21722:             privitem.size = '40';
21723:             pubtext.innerHTML = "$lt{'pub'}";
21724:             privtext.innerHTML = "$lt{'priv'}";
21725:             versionitem.type = 'text';
21726:             versionitem.size = '3';
21727:             versiontext.innerHTML = "$lt{'ver'}";
21728:         } else {
21729:             pubitem.type = 'hidden';
21730:             privitem.type = 'hidden';
21731:             versionitem.type = 'hidden';
21732:             pubtext.innerHTML = '';
21733:             privtext.innerHTML = '';
21734:             versiontext.innerHTML = '';
21735:         }
21736:     }
21737:     return;
21738: }
21739: 
21740: // ]]>
21741: </script>
21742: 
21743: END
21744: 
21745: }
21746: 
21747: sub toggle_display_js {
21748:     return <<"END";
21749: 
21750: <script type="text/javascript">
21751: // <![CDATA[
21752: 
21753: function toggleDisplay(domForm,caller) {
21754:     if (document.getElementById(caller)) {
21755:         var divitem = document.getElementById(caller);
21756:         var optionsElement = domForm.coursecredits;
21757:         var checkval = 1;
21758:         var dispval = 'block';
21759:         var selfcreateRegExp = /^cancreate_emailverified/;
21760:         if (caller == 'emailoptions') {
21761:             optionsElement = domForm.cancreate_email;
21762:         }
21763:         if (caller == 'studentsubmission') {
21764:             optionsElement = domForm.postsubmit;
21765:         }
21766:         if (caller == 'cloneinstcode') {
21767:             optionsElement = domForm.canclone;
21768:             checkval = 'instcode';
21769:         }
21770:         if (selfcreateRegExp.test(caller)) {
21771:             optionsElement = domForm.elements[caller];
21772:             checkval = 'other';
21773:             dispval = 'inline'
21774:         }
21775:         if (optionsElement.length) {
21776:             var currval;
21777:             for (var i=0; i<optionsElement.length; i++) {
21778:                 if (optionsElement[i].checked) {
21779:                    currval = optionsElement[i].value;
21780:                 }
21781:             }
21782:             if (currval == checkval) {
21783:                 divitem.style.display = dispval;
21784:             } else {
21785:                 divitem.style.display = 'none';
21786:             }
21787:         }
21788:     }
21789:     return;
21790: }
21791: 
21792: // ]]>
21793: </script>
21794: 
21795: END
21796: 
21797: }
21798: 
21799: sub captcha_phrases {
21800:     return &Apache::lonlocal::texthash (
21801:                  priv => 'Private key',
21802:                  pub  => 'Public key',
21803:                  original  => 'original (CAPTCHA)',
21804:                  recaptcha => 'successor (ReCAPTCHA)',
21805:                  notused   => 'unused',
21806:                  ver => 'ReCAPTCHA version (1 or 2)',
21807:     );
21808: }
21809: 
21810: sub devalidate_remote_domconfs {
21811:     my ($dom,$cachekeys) = @_;
21812:     return unless (ref($cachekeys) eq 'HASH');
21813:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21814:     my %thismachine;
21815:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
21816:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
21817:                       'directorysrch','passwdconf','cats','proxyalias');
21818:     if (keys(%servers)) {
21819:         foreach my $server (keys(%servers)) {
21820:             next if ($thismachine{$server});
21821:             my @cached;
21822:             foreach my $name (@posscached) {
21823:                 if ($cachekeys->{$name}) {
21824:                     if ($name eq 'proxyalias') {
21825:                         if (ref($cachekeys->{$name}) eq 'HASH') {  
21826:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
21827:                                 push(@cached,&escape($name).':'.&escape($key));
21828:                             }
21829:                         }
21830:                     } else {
21831:                         push(@cached,&escape($name).':'.&escape($dom));
21832:                     }
21833:                 }
21834:             }
21835:             if (@cached) {
21836:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
21837:             }
21838:         }
21839:     }
21840:     return;
21841: }
21842: 
21843: 1;

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