File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.381: download - view: text, annotated - select for diffs
Sun Apr 18 02:08:46 2021 UTC (3 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6914
 - Update domain config UI to support settings documented in
   Domain_Configuration_WAF_Proxy.tex
 - Use /adm/migrateuser to handle redirects when user with a LON-CAPA session
   switches between access via VPN and not via VPN (and vice versa).

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.381 2021/04/18 02:08:46 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{$domain}) eq 'HASH') {
 7341:                 if (ref($config{$domain}{'wafproxy'}) eq 'HASH') {
 7342:                     $aliases{$domain} = $config{$domain}{'wafproxy'}{'alias'};
 7343:                     foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7344:                         $values{$domain}{$item} = $config{$domain}{'wafproxy'}{$item};
 7345:                     }
 7346:                 }
 7347:             }
 7348:         }
 7349:     }
 7350:     if ($position eq 'top') {
 7351:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7352:         my %aliasinfo;
 7353:         foreach my $server (sort(keys(%servers))) {
 7354:             $itemcount ++;
 7355:             my $dom_in_effect;
 7356:             my $aliasrows = '<tr>'.
 7357:                             '<td class="LC_left_item">'.&mt('Hostname').':&nbsp;'.
 7358:                             &Apache::lonnet::hostname($server).'</td>';
 7359:             if ($othercontrol{$server}) {
 7360:                 $dom_in_effect = $othercontrol{$server};
 7361:                 my $current;
 7362:                 if (ref($aliases{$othercontrol{$server}}) eq 'HASH') {
 7363:                     $current = $aliases{$othercontrol{$server}{$server}};
 7364:                 }
 7365:                 if ($current) {
 7366:                     $aliasrows .= $current;
 7367:                 } else {
 7368:                     $aliasrows .= &mt('None in effect');
 7369:                 }
 7370:                 $aliasrows .= '<td class="LC_left_item"><span class="LC_small">('.
 7371:                               &mt('WAF/Reverse Proxy controlled by domain: [_1]',
 7372:                                   '<b>'.$othercontrol{$server}.'</b>').'</span></td>';
 7373:             } else {
 7374:                 $dom_in_effect = $dom;
 7375:                 my $current;
 7376:                 if (ref($aliases{$dom}) eq 'HASH') {
 7377:                     if ($aliases{$dom}{$server}) {
 7378:                         $current = $aliases{$dom}{$server};
 7379:                     }
 7380:                 }
 7381:                 $aliasrows .= '<td class="LC_left_item">'.&mt('WAF/Reverse Proxy Alias').':&nbsp;'.
 7382:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 7383:                               'value="'.$current.'" size="30" /></td>';
 7384:             }
 7385:             $aliasrows .= '</tr>';
 7386:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 7387:         }
 7388:         if ($aliasinfo{$dom}) {
 7389:             my ($onclick,$wafon,$wafoff,$showtable);
 7390:             $onclick = ' onclick="javascript:toggleWAF();"';
 7391:             $wafoff = ' checked="checked"';
 7392:             $showtable = ' style="display:none";';
 7393:             if ($showdom) {
 7394:                 $wafon = $wafoff;
 7395:                 $wafoff = '';
 7396:                 $showtable = ' style="display:inline;"';
 7397:             }
 7398:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7399:             $datatable = '<tr'.$css_class.'>'.
 7400:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 7401:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 7402:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 7403:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 7404:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 7405:                          &mt('No').'</label></span></td>'.
 7406:                          '<td class="LC_left_item">'.
 7407:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 7408:                          '</table></td></tr>';
 7409:             $itemcount++;
 7410:         }
 7411:         if (keys(%othercontrol)) {
 7412:             foreach my $key (sort(keys(%othercontrol))) {
 7413:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7414:                 $datatable = '<tr'.$css_class.'>'.
 7415:                              '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 7416:                              '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 7417:                              '</table></td></tr>';
 7418:                 $itemcount++;
 7419:             }
 7420:         }
 7421:     } else {
 7422:         if ($setdom) {
 7423:             $itemcount ++;
 7424:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7425:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 7426:                 $currwafvpn,$wafrangestyle);
 7427:             $wafstyle = ' style="display:none;"';
 7428:             $nowafstyle = ' style="display:table-row;"';
 7429:             $currwafdisplay = ' style="display: none"';
 7430:             $wafrangestyle = ' style="display: none"';
 7431:             $curr_remotip = 'n';
 7432:             if ($showdom) {
 7433:                 $wafstyle = ' style="display:table-row;"';
 7434:                 $nowafstyle =  ' style="display:none;"';
 7435:                 if (keys(%{$values{$dom}})) {
 7436:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 7437:                         $curr_remotip = $values{$dom}{remoteip};
 7438:                     }
 7439:                     if ($curr_remotip eq 'h') {
 7440:                         $currwafdisplay = ' style="display:table-row"';
 7441:                         $wafrangestyle = ' style="display:inline-block;"';
 7442:                     }
 7443:                 }
 7444:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 7445:                     $vpndircheck = ' checked="checked"';
 7446:                     $currwafvpn = ' style="display:table-row;"';
 7447:                     $wafrangestyle = ' style="display:inline-block;"';
 7448:                 } else {
 7449:                     $vpnaliascheck = ' checked="checked"';
 7450:                     $currwafvpn = ' style="display:none;"';
 7451:                 }
 7452:             }
 7453:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7454:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 7455:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 7456:                           '</tr>'.
 7457:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 7458:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 7459:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 7460:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'</div></td>'.
 7461:                           '<td class="LC_left_item"><table>'.
 7462:                           '<tr>'.
 7463:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 7464:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 7465:             my %ip_methods = &remoteip_methods();
 7466:             foreach my $option ('m','h','n') {
 7467:                 my $sel;
 7468:                 if ($option eq $curr_remotip) {
 7469:                    $sel = ' selected="selected"';
 7470:                 }
 7471:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 7472:                               $ip_methods{$option}.'</option>';
 7473:             }
 7474:             $datatable .= '</select></td></tr>'."\n".
 7475:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 7476:                           $lt{'ipheader'}.':&nbsp;'.
 7477:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 7478:                           'name="wafproxy_ipheader" />'.
 7479:                           '</td></tr>'."\n".
 7480:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 7481:                           $lt{'trusted'}.':&nbsp;'.
 7482:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 7483:                           $values{$dom}{'trusted'}.'</textarea>'.
 7484:                           '</td></tr>'."\n".
 7485:                           '<tr><td><hr /></td></tr>'."\n".
 7486:                           '<tr>'.
 7487:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 7488:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 7489:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 7490:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 7491:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 7492:             foreach my $item ('vpnint','vpnext') {
 7493:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 7494:                               '<td valign="top">'.$lt{$item}.':&nbsp;'.
 7495:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 7496:                               $values{$dom}{$item}.'</textarea>'.
 7497:                               '</td></tr>'."\n";
 7498:             }
 7499:             $datatable .= '</table></td></tr>';
 7500:         }
 7501:         if (keys(%otherdoms)) {
 7502:             foreach my $domain (sort(keys(%otherdoms))) {
 7503:                 $itemcount ++;
 7504:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7505:                 $datatable .= '<tr'.$css_class.'>'.
 7506:                               '<td class="LC_left_item">'.&mt('Domain: [_1]',$domain).'</td>'.
 7507:                               '<td class="LC_left_item"><table>';
 7508:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 7509:                     my $showval = &mt('None');
 7510:                     if ($values{$domain}{$item}) {
 7511:                         $showval = $values{$domain}{$item};
 7512:                     }
 7513:                     $datatable .= '<tr>'.
 7514:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 7515:                 }
 7516:                 $datatable .= '</table></td></tr>';
 7517:             }
 7518:         }
 7519:     }
 7520:     $$rowtotal += $itemcount;
 7521:     return $datatable;
 7522: }
 7523: 
 7524: sub wafproxy_titles {
 7525:     return &Apache::lonlocal::texthash(
 7526:                remoteip   => "Method for determining user's IP",
 7527:                ipheader   => 'Request header containing remote IP',
 7528:                trusted    => 'Trusted IP range(s)',
 7529:                vpnaccess  => 'Access from institutional VPN',
 7530:                vpndirect  => 'via regular hostname (no WAF)',
 7531:                vpnaliased => 'via aliased hostname (WAF)',
 7532:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 7533:                vpnext     => 'IP Range(s) for backend WAF connections',
 7534:                ssloptions => 'Forwarding http/https',
 7535:                alltossl   => 'WAF forwards both http and https requests to https',
 7536:                ssltossl   => 'WAF forwards http requests to http and https to https',
 7537:            );
 7538: }
 7539: 
 7540: sub remoteip_methods {
 7541:     return &Apache::lonlocal::texthash(
 7542:               m => 'Use Apache mod_remoteip',
 7543:               h => 'Use headers parsed by LON-CAPA',
 7544:               n => 'Not in use',
 7545:            );
 7546: }
 7547: 
 7548: sub print_usersessions {
 7549:     my ($position,$dom,$settings,$rowtotal) = @_;
 7550:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 7551:     my (%by_ip,%by_location,@intdoms,@instdoms);
 7552:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7553: 
 7554:     my @alldoms = &Apache::lonnet::all_domains();
 7555:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7556:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7557:     my %altids = &id_for_thisdom(%servers);
 7558:     if ($position eq 'top') {
 7559:         if (keys(%serverhomes) > 1) {
 7560:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 7561:             my ($curroffloadnow,$curroffloadoth);
 7562:             if (ref($settings) eq 'HASH') {
 7563:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 7564:                     $curroffloadnow = $settings->{'offloadnow'};
 7565:                 }
 7566:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 7567:                     $curroffloadoth = $settings->{'offloadoth'};
 7568:                 }
 7569:             }
 7570:             my $other_insts = scalar(keys(%by_location));
 7571:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 7572:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 7573:         } else {
 7574:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 7575:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 7576:                           '</td></tr>';
 7577:         }
 7578:     } else {
 7579:         my %titles = &usersession_titles();
 7580:         my ($prefix,@types);
 7581:         if ($position eq 'bottom') {
 7582:             $prefix = 'remote';
 7583:             @types = ('version','excludedomain','includedomain');
 7584:         } else {
 7585:             $prefix = 'hosted';
 7586:             @types = ('excludedomain','includedomain');
 7587:         }
 7588:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7589:     }
 7590:     $$rowtotal += $itemcount;
 7591:     return $datatable;
 7592: }
 7593: 
 7594: sub rules_by_location {
 7595:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 7596:     my ($datatable,$itemcount,$css_class);
 7597:     if (keys(%{$by_location}) == 0) {
 7598:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7599:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 7600:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 7601:                      '</td></tr>';
 7602:         $itemcount = 1;
 7603:     } else {
 7604:         $itemcount = 0;
 7605:         my $numinrow = 5;
 7606:         my (%current,%checkedon,%checkedoff);
 7607:         my @locations = sort(keys(%{$by_location}));
 7608:         foreach my $type (@{$types}) {
 7609:             $checkedon{$type} = '';
 7610:             $checkedoff{$type} = ' checked="checked"';
 7611:         }
 7612:         if (ref($settings) eq 'HASH') {
 7613:             if (ref($settings->{$prefix}) eq 'HASH') {
 7614:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 7615:                     $current{$key} = $settings->{$prefix}{$key};
 7616:                     if ($key eq 'version') {
 7617:                         if ($current{$key} ne '') {
 7618:                             $checkedon{$key} = ' checked="checked"';
 7619:                             $checkedoff{$key} = '';
 7620:                         }
 7621:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 7622:                         $checkedon{$key} = ' checked="checked"';
 7623:                         $checkedoff{$key} = '';
 7624:                     }
 7625:                 }
 7626:             }
 7627:         }
 7628:         foreach my $type (@{$types}) {
 7629:             next if ($type ne 'version' && !@locations);
 7630:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7631:             $datatable .= '<tr'.$css_class.'>
 7632:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 7633:                            <span class="LC_nobreak">&nbsp;
 7634:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 7635:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 7636:             if ($type eq 'version') {
 7637:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 7638:                 my $selector = '<select name="'.$prefix.'_version">';
 7639:                 foreach my $version (@lcversions) {
 7640:                     my $selected = '';
 7641:                     if ($current{'version'} eq $version) {
 7642:                         $selected = ' selected="selected"';
 7643:                     }
 7644:                     $selector .= ' <option value="'.$version.'"'.
 7645:                                  $selected.'>'.$version.'</option>';
 7646:                 }
 7647:                 $selector .= '</select> ';
 7648:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 7649:             } else {
 7650:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 7651:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 7652:                              ' />'.('&nbsp;'x2).
 7653:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 7654:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 7655:                              "\n".
 7656:                              '</div><div><table>';
 7657:                 my $rem;
 7658:                 for (my $i=0; $i<@locations; $i++) {
 7659:                     my ($showloc,$value,$checkedtype);
 7660:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 7661:                         my $ip = $by_location->{$locations[$i]}->[0];
 7662:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7663:                             $value = join(':',@{$by_ip->{$ip}});
 7664:                             $showloc = join(', ',@{$by_ip->{$ip}});
 7665:                             if (ref($current{$type}) eq 'ARRAY') {
 7666:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 7667:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 7668:                                         $checkedtype = ' checked="checked"';
 7669:                                         last;
 7670:                                     }
 7671:                                 }
 7672:                             }
 7673:                         }
 7674:                     }
 7675:                     $rem = $i%($numinrow);
 7676:                     if ($rem == 0) {
 7677:                         if ($i > 0) {
 7678:                             $datatable .= '</tr>';
 7679:                         }
 7680:                         $datatable .= '<tr>';
 7681:                     }
 7682:                     $datatable .= '<td class="LC_left_item">'.
 7683:                                   '<span class="LC_nobreak"><label>'.
 7684:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 7685:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 7686:                                   '</label></span></td>';
 7687:                 }
 7688:                 $rem = @locations%($numinrow);
 7689:                 my $colsleft = $numinrow - $rem;
 7690:                 if ($colsleft > 1 ) {
 7691:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 7692:                                   '&nbsp;</td>';
 7693:                 } elsif ($colsleft == 1) {
 7694:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 7695:                 }
 7696:                 $datatable .= '</tr></table>';
 7697:             }
 7698:             $datatable .= '</td></tr>';
 7699:             $itemcount ++;
 7700:         }
 7701:     }
 7702:     return ($datatable,$itemcount);
 7703: }
 7704: 
 7705: sub print_ssl {
 7706:     my ($position,$dom,$settings,$rowtotal) = @_;
 7707:     my ($css_class,$datatable);
 7708:     my $itemcount = 1;
 7709:     if ($position eq 'top') {
 7710:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7711:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7712:         my $same_institution;
 7713:         if ($intdom ne '') {
 7714:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 7715:             if (ref($internet_names) eq 'ARRAY') {
 7716:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 7717:                     $same_institution = 1;
 7718:                 }
 7719:             }
 7720:         }
 7721:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7722:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 7723:         if ($same_institution) {
 7724:             my %domservers = &Apache::lonnet::get_servers($dom);
 7725:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 7726:         } else {
 7727:             $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.");
 7728:         }
 7729:         $datatable .= '</td></tr>';
 7730:         $itemcount ++;
 7731:     } else {
 7732:         my %titles = &ssl_titles();
 7733:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7734:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7735:         my @alldoms = &Apache::lonnet::all_domains();
 7736:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 7737:         my @domservers = &Apache::lonnet::get_servers($dom);
 7738:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 7739:         my %altids = &id_for_thisdom(%servers);
 7740:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 7741:             my $legacy;
 7742:             unless (ref($settings) eq 'HASH') {
 7743:                 my $name;
 7744:                 if ($position eq 'connto') {
 7745:                     $name = 'loncAllowInsecure';
 7746:                 } else {
 7747:                     $name = 'londAllowInsecure';
 7748:                 }
 7749:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 7750:                 my @ids=&Apache::lonnet::current_machine_ids();
 7751:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 7752:                     my %what = (
 7753:                                    $name => 1,
 7754:                                );
 7755:                     my ($result,$returnhash) =
 7756:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 7757:                     if ($result eq 'ok') {
 7758:                         if (ref($returnhash) eq 'HASH') {
 7759:                             $legacy = $returnhash->{$name};
 7760:                         }
 7761:                     }
 7762:                 } else {
 7763:                     $legacy = $Apache::lonnet::perlvar{$name};
 7764:                 }
 7765:             }
 7766:             foreach my $type ('dom','intdom','other') {
 7767:                 my %checked;
 7768:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7769:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 7770:                               '<td class="LC_right_item">';
 7771:                 my $skip; 
 7772:                 if ($type eq 'dom') {
 7773:                     unless (keys(%servers) > 1) {
 7774:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 7775:                         $skip = 1;
 7776:                     }
 7777:                 }
 7778:                 if ($type eq 'intdom') {
 7779:                     unless (@instdoms > 1) {
 7780:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 7781:                         $skip = 1;
 7782:                     } 
 7783:                 } elsif ($type eq 'other') {
 7784:                     if (keys(%by_location) == 0) {
 7785:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 7786:                         $skip = 1;
 7787:                     }
 7788:                 }
 7789:                 unless ($skip) {
 7790:                     $checked{'yes'} = ' checked="checked"'; 
 7791:                     if (ref($settings) eq 'HASH') {
 7792:                         if (ref($settings->{$position}) eq 'HASH') {
 7793:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 7794:                                 $checked{$1} = $checked{'yes'};
 7795:                                 delete($checked{'yes'}); 
 7796:                             }
 7797:                         }
 7798:                     } else {
 7799:                         if ($legacy == 0) {
 7800:                             $checked{'req'} = $checked{'yes'};
 7801:                             delete($checked{'yes'});    
 7802:                         }
 7803:                     }
 7804:                     foreach my $option ('no','yes','req') {
 7805:                         $datatable .= '<span class="LC_nobreak"><label>'.
 7806:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 7807:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7808:                                       '</label></span>'.('&nbsp;'x2);
 7809:                     }
 7810:                 }
 7811:                 $datatable .= '</td></tr>';
 7812:                 $itemcount ++; 
 7813:             }
 7814:         } else {
 7815:             my $prefix = 'replication';
 7816:             my @types = ('certreq','nocertreq');
 7817:             if (keys(%by_location) == 0) {
 7818:                 $datatable .= '<tr'.$css_class.'><td>'.
 7819:                               &mt('Nothing to set here, as there are no other institutions').
 7820:                               '</td></tr>';
 7821:                 $itemcount ++;
 7822:             } else {
 7823:                 ($datatable,$itemcount) = 
 7824:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7825:             }
 7826:         }
 7827:     }
 7828:     $$rowtotal += $itemcount;
 7829:     return $datatable;
 7830: }
 7831: 
 7832: sub ssl_titles {
 7833:     return &Apache::lonlocal::texthash (
 7834:                dom           => 'LON-CAPA servers/VMs from same domain',
 7835:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 7836:                other         => 'External LON-CAPA servers/VMs',
 7837:                connto        => 'Connections to other servers',
 7838:                connfrom      => 'Connections from other servers',
 7839:                replication   => 'Replicating content to other institutions',
 7840:                certreq       => 'Client certificate required, but specific domains exempt',
 7841:                nocertreq     => 'No client certificate required, except for specific domains',
 7842:                no            => 'SSL not used',
 7843:                yes           => 'SSL Optional (used if available)',
 7844:                req           => 'SSL Required',
 7845:     );
 7846: }
 7847: 
 7848: sub print_trust {
 7849:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 7850:     my ($css_class,$datatable,%checked,%choices);
 7851:     my (%by_ip,%by_location,@intdoms,@instdoms);
 7852:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7853:     my $itemcount = 1;
 7854:     my %titles = &trust_titles();
 7855:     my @types = ('exc','inc');
 7856:     if ($prefix eq 'top') {
 7857:         $prefix = 'content';
 7858:     } elsif ($prefix eq 'bottom') {
 7859:         $prefix = 'msg';
 7860:     }
 7861:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 7862:     $$rowtotal += $itemcount;
 7863:     return $datatable;
 7864: }
 7865: 
 7866: sub trust_titles {
 7867:     return &Apache::lonlocal::texthash(
 7868:                content  => "Access to this domain's content by others",
 7869:                shared   => "Access to other domain's content by this domain",
 7870:                enroll   => "Enrollment in this domain's courses by others", 
 7871:                othcoau  => "Co-author roles in this domain for others",
 7872:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 7873:                domroles => "Domain roles in this domain assignable to others",
 7874:                catalog  => "Course Catalog for this domain displayed elsewhere",
 7875:                reqcrs   => "Requests for creation of courses in this domain by others",
 7876:                msg      => "Users in other domains can send messages to this domain",
 7877:                exc      => "Allow all, but exclude specific domains",
 7878:                inc      => "Deny all, but include specific domains",
 7879:            );
 7880: } 
 7881: 
 7882: sub build_location_hashes {
 7883:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 7884:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 7885:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 7886:     my %iphost = &Apache::lonnet::get_iphost();
 7887:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 7888:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 7889:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 7890:         foreach my $id (@{$iphost{$primary_ip}}) {
 7891:             my $intdom = &Apache::lonnet::internet_dom($id);
 7892:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 7893:                 push(@{$intdoms},$intdom);
 7894:             }
 7895:         }
 7896:     }
 7897:     foreach my $ip (keys(%iphost)) {
 7898:         if (ref($iphost{$ip}) eq 'ARRAY') {
 7899:             foreach my $id (@{$iphost{$ip}}) {
 7900:                 my $location = &Apache::lonnet::internet_dom($id);
 7901:                 if ($location) {
 7902:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 7903:                         my $dom = &Apache::lonnet::host_domain($id);
 7904:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 7905:                             push(@{$instdoms},$dom);
 7906:                         }
 7907:                         next;
 7908:                     }
 7909:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7910:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 7911:                             push(@{$by_ip->{$ip}},$location);
 7912:                         }
 7913:                     } else {
 7914:                         $by_ip->{$ip} = [$location];
 7915:                     }
 7916:                 }
 7917:             }
 7918:         }
 7919:     }
 7920:     foreach my $ip (sort(keys(%{$by_ip}))) {
 7921:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 7922:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 7923:             my $first = $by_ip->{$ip}->[0];
 7924:             if (ref($by_location->{$first}) eq 'ARRAY') {
 7925:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 7926:                     push(@{$by_location->{$first}},$ip);
 7927:                 }
 7928:             } else {
 7929:                 $by_location->{$first} = [$ip];
 7930:             }
 7931:         }
 7932:     }
 7933:     return;
 7934: }
 7935: 
 7936: sub current_offloads_to {
 7937:     my ($dom,$settings,$servers) = @_;
 7938:     my (%spareid,%otherdomconfigs);
 7939:     if (ref($servers) eq 'HASH') {
 7940:         foreach my $lonhost (sort(keys(%{$servers}))) {
 7941:             my $gotspares;
 7942:             if (ref($settings) eq 'HASH') {
 7943:                 if (ref($settings->{'spares'}) eq 'HASH') {
 7944:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 7945:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 7946:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 7947:                         $gotspares = 1;
 7948:                     }
 7949:                 }
 7950:             }
 7951:             unless ($gotspares) {
 7952:                 my $gotspares;
 7953:                 my $serverhomeID =
 7954:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 7955:                 my $serverhomedom =
 7956:                     &Apache::lonnet::host_domain($serverhomeID);
 7957:                 if ($serverhomedom ne $dom) {
 7958:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 7959:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 7960:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 7961:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 7962:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 7963:                                 $gotspares = 1;
 7964:                             }
 7965:                         }
 7966:                     } else {
 7967:                         $otherdomconfigs{$serverhomedom} =
 7968:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 7969:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 7970:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 7971:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 7972:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 7973:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 7974:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 7975:                                         $gotspares = 1;
 7976:                                     }
 7977:                                 }
 7978:                             }
 7979:                         }
 7980:                     }
 7981:                 }
 7982:             }
 7983:             unless ($gotspares) {
 7984:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 7985:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 7986:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 7987:                } else {
 7988:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 7989:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 7990:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 7991:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 7992:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 7993:                     } else {
 7994:                         my %what = (
 7995:                              spareid => 1,
 7996:                         );
 7997:                         my ($result,$returnhash) = 
 7998:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 7999:                         if ($result eq 'ok') { 
 8000:                             if (ref($returnhash) eq 'HASH') {
 8001:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 8002:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 8003:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 8004:                                 }
 8005:                             }
 8006:                         }
 8007:                     }
 8008:                 }
 8009:             }
 8010:         }
 8011:     }
 8012:     return %spareid;
 8013: }
 8014: 
 8015: sub spares_row {
 8016:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 8017:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 8018:     my $css_class;
 8019:     my $numinrow = 4;
 8020:     my $itemcount = 1;
 8021:     my $datatable;
 8022:     my %typetitles = &sparestype_titles();
 8023:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8024:         foreach my $server (sort(keys(%{$servers}))) {
 8025:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 8026:             my ($othercontrol,$serverdom);
 8027:             if ($serverhome ne $server) {
 8028:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 8029:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8030:             } else {
 8031:                 $serverdom = &Apache::lonnet::host_domain($server);
 8032:                 if ($serverdom ne $dom) {
 8033:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 8034:                 }
 8035:             }
 8036:             next unless (ref($spareid->{$server}) eq 'HASH');
 8037:             my ($checkednow,$checkedoth);
 8038:             if (ref($curroffloadnow) eq 'HASH') {
 8039:                 if ($curroffloadnow->{$server}) {
 8040:                     $checkednow = ' checked="checked"';
 8041:                 }
 8042:             }
 8043:             if (ref($curroffloadoth) eq 'HASH') {
 8044:                 if ($curroffloadoth->{$server}) {
 8045:                     $checkedoth = ' checked="checked"';
 8046:                 }
 8047:             }
 8048:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8049:             $datatable .= '<tr'.$css_class.'>
 8050:                            <td rowspan="2">
 8051:                             <span class="LC_nobreak">'.
 8052:                           &mt('[_1] when busy, offloads to:'
 8053:                               ,'<b>'.$server.'</b>').'</span><br />'.
 8054:                           '<span class="LC_nobreak">'."\n".
 8055:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 8056:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 8057:                           "\n";
 8058:             if ($other_insts) {
 8059:                 $datatable .= '<br />'.
 8060:                               '<span class="LC_nobreak">'."\n".
 8061:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 8062:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 8063:                           "\n";
 8064:             }
 8065:             my (%current,%canselect);
 8066:             my @choices = 
 8067:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 8068:             foreach my $type ('primary','default') {
 8069:                 if (ref($spareid->{$server}) eq 'HASH') {
 8070:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 8071:                         my @spares = @{$spareid->{$server}{$type}};
 8072:                         if (@spares > 0) {
 8073:                             if ($othercontrol) {
 8074:                                 $current{$type} = join(', ',@spares);
 8075:                             } else {
 8076:                                 $current{$type} .= '<table>';
 8077:                                 my $numspares = scalar(@spares);
 8078:                                 for (my $i=0;  $i<@spares; $i++) {
 8079:                                     my $rem = $i%($numinrow);
 8080:                                     if ($rem == 0) {
 8081:                                         if ($i > 0) {
 8082:                                             $current{$type} .= '</tr>';
 8083:                                         }
 8084:                                         $current{$type} .= '<tr>';
 8085:                                     }
 8086:                                     $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;'.
 8087:                                                        $spareid->{$server}{$type}[$i].
 8088:                                                        '</label></td>'."\n";
 8089:                                 }
 8090:                                 my $rem = @spares%($numinrow);
 8091:                                 my $colsleft = $numinrow - $rem;
 8092:                                 if ($colsleft > 1 ) {
 8093:                                     $current{$type} .= '<td colspan="'.$colsleft.
 8094:                                                        '" class="LC_left_item">'.
 8095:                                                        '&nbsp;</td>';
 8096:                                 } elsif ($colsleft == 1) {
 8097:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 8098:                                 }
 8099:                                 $current{$type} .= '</tr></table>';
 8100:                             }
 8101:                         }
 8102:                     }
 8103:                     if ($current{$type} eq '') {
 8104:                         $current{$type} = &mt('None specified');
 8105:                     }
 8106:                     if ($othercontrol) {
 8107:                         if ($type eq 'primary') {
 8108:                             $canselect{$type} = $othercontrol;
 8109:                         }
 8110:                     } else {
 8111:                         $canselect{$type} = 
 8112:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 8113:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 8114:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 8115:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 8116:                         if (@choices > 0) {
 8117:                             foreach my $lonhost (@choices) {
 8118:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 8119:                             }
 8120:                         }
 8121:                         $canselect{$type} .= '</select>'."\n";
 8122:                     }
 8123:                 } else {
 8124:                     $current{$type} = &mt('Could not be determined');
 8125:                     if ($type eq 'primary') {
 8126:                         $canselect{$type} =  $othercontrol;
 8127:                     }
 8128:                 }
 8129:                 if ($type eq 'default') {
 8130:                     $datatable .= '<tr'.$css_class.'>';
 8131:                 }
 8132:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 8133:                               '<td>'.$current{$type}.'</td>'."\n".
 8134:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 8135:             }
 8136:             $itemcount ++;
 8137:         }
 8138:     }
 8139:     $$rowtotal += $itemcount;
 8140:     return $datatable;
 8141: }
 8142: 
 8143: sub possible_newspares {
 8144:     my ($server,$currspares,$serverhomes,$altids) = @_;
 8145:     my $serverhostname = &Apache::lonnet::hostname($server);
 8146:     my %excluded;
 8147:     if ($serverhostname ne '') {
 8148:         %excluded = (
 8149:                        $serverhostname => 1,
 8150:                     );
 8151:     }
 8152:     if (ref($currspares) eq 'HASH') {
 8153:         foreach my $type (keys(%{$currspares})) {
 8154:             if (ref($currspares->{$type}) eq 'ARRAY') {
 8155:                 if (@{$currspares->{$type}} > 0) {
 8156:                     foreach my $curr (@{$currspares->{$type}}) {
 8157:                         my $hostname = &Apache::lonnet::hostname($curr);
 8158:                         $excluded{$hostname} = 1;
 8159:                     }
 8160:                 }
 8161:             }
 8162:         }
 8163:     }
 8164:     my @choices;
 8165:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 8166:         if (keys(%{$serverhomes}) > 1) {
 8167:             foreach my $name (sort(keys(%{$serverhomes}))) {
 8168:                 unless ($excluded{$name}) {
 8169:                     if (exists($altids->{$serverhomes->{$name}})) {
 8170:                         push(@choices,$altids->{$serverhomes->{$name}});
 8171:                     } else {
 8172:                         push(@choices,$serverhomes->{$name});
 8173:                     }
 8174:                 }
 8175:             }
 8176:         }
 8177:     }
 8178:     return sort(@choices);
 8179: }
 8180: 
 8181: sub print_loadbalancing {
 8182:     my ($dom,$settings,$rowtotal) = @_;
 8183:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8184:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8185:     my $numinrow = 1;
 8186:     my $datatable;
 8187:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8188:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 8189:     if (ref($settings) eq 'HASH') {
 8190:         %existing = %{$settings};
 8191:     }
 8192:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 8193:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 8194:                                   \%currtargets,\%currrules,\%currcookies);
 8195:     } else {
 8196:         return;
 8197:     }
 8198:     my ($othertitle,$usertypes,$types) =
 8199:         &Apache::loncommon::sorted_inst_types($dom);
 8200:     my $rownum = 8;
 8201:     if (ref($types) eq 'ARRAY') {
 8202:         $rownum += scalar(@{$types});
 8203:     }
 8204:     my @css_class = ('LC_odd_row','LC_even_row');
 8205:     my $balnum = 0;
 8206:     my $islast;
 8207:     my (@toshow,$disabledtext);
 8208:     if (keys(%currbalancer) > 0) {
 8209:         @toshow = sort(keys(%currbalancer));
 8210:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 8211:             push(@toshow,'');
 8212:         }
 8213:     } else {
 8214:         @toshow = ('');
 8215:         $disabledtext = &mt('No existing load balancer');
 8216:     }
 8217:     foreach my $lonhost (@toshow) {
 8218:         if ($balnum == scalar(@toshow)-1) {
 8219:             $islast = 1;
 8220:         } else {
 8221:             $islast = 0;
 8222:         }
 8223:         my $cssidx = $balnum%2;
 8224:         my $targets_div_style = 'display: none';
 8225:         my $disabled_div_style = 'display: block';
 8226:         my $homedom_div_style = 'display: none';
 8227:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 8228:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8229:                       '<p>';
 8230:         if ($lonhost eq '') {
 8231:             $datatable .= '<span class="LC_nobreak">';
 8232:             if (keys(%currbalancer) > 0) {
 8233:                 $datatable .= &mt('Add balancer:');
 8234:             } else {
 8235:                 $datatable .= &mt('Enable balancer:');
 8236:             }
 8237:             $datatable .= '&nbsp;'.
 8238:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 8239:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 8240:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 8241:                           '<option value="" selected="selected">'.&mt('None').
 8242:                           '</option>'."\n";
 8243:             foreach my $server (sort(keys(%servers))) {
 8244:                 next if ($currbalancer{$server});
 8245:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 8246:             }
 8247:             $datatable .=
 8248:                 '</select>'."\n".
 8249:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 8250:         } else {
 8251:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 8252:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 8253:                            &mt('Stop balancing').'</label>'.
 8254:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 8255:             $targets_div_style = 'display: block';
 8256:             $disabled_div_style = 'display: none';
 8257:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 8258:                 $homedom_div_style = 'display: block';
 8259:             }
 8260:         }
 8261:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 8262:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 8263:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 8264:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 8265:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 8266:         my @sparestypes = ('primary','default');
 8267:         my %typetitles = &sparestype_titles();
 8268:         my %hostherechecked = (
 8269:                                   no => ' checked="checked"',
 8270:                               );
 8271:         my %balcookiechecked = (
 8272:                                   no => ' checked="checked"', 
 8273:                                );
 8274:         foreach my $sparetype (@sparestypes) {
 8275:             my $targettable;
 8276:             for (my $i=0; $i<$numspares; $i++) {
 8277:                 my $checked;
 8278:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 8279:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8280:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8281:                             $checked = ' checked="checked"';
 8282:                         }
 8283:                     }
 8284:                 }
 8285:                 my ($chkboxval,$disabled);
 8286:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 8287:                     $chkboxval = $spares[$i];
 8288:                 }
 8289:                 if (exists($currbalancer{$spares[$i]})) {
 8290:                     $disabled = ' disabled="disabled"';
 8291:                 }
 8292:                 $targettable .=
 8293:                     '<td><span class="LC_nobreak"><label>'.
 8294:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 8295:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 8296:                     '</span></label></span></td>';
 8297:                 my $rem = $i%($numinrow);
 8298:                 if ($rem == 0) {
 8299:                     if (($i > 0) && ($i < $numspares-1)) {
 8300:                         $targettable .= '</tr>';
 8301:                     }
 8302:                     if ($i < $numspares-1) {
 8303:                         $targettable .= '<tr>';
 8304:                     }
 8305:                 }
 8306:             }
 8307:             if ($targettable ne '') {
 8308:                 my $rem = $numspares%($numinrow);
 8309:                 my $colsleft = $numinrow - $rem;
 8310:                 if ($colsleft > 1 ) {
 8311:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8312:                                     '&nbsp;</td>';
 8313:                 } elsif ($colsleft == 1) {
 8314:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 8315:                 }
 8316:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 8317:                                '<table><tr>'.$targettable.'</tr></table><br />';
 8318:             }
 8319:             $hostherechecked{$sparetype} = '';
 8320:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 8321:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 8322:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 8323:                         $hostherechecked{$sparetype} = ' checked="checked"';
 8324:                         $hostherechecked{'no'} = '';
 8325:                     }
 8326:                 }
 8327:             }
 8328:         }
 8329:         if ($currcookies{$lonhost}) {
 8330:             %balcookiechecked = (
 8331:                                     yes => ' checked="checked"',
 8332:                                 );
 8333:         }
 8334:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 8335:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 8336:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 8337:         foreach my $sparetype (@sparestypes) {
 8338:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 8339:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 8340:                           '</i></label><br />';
 8341:         }
 8342:         $datatable .= &mt('Use balancer cookie').'<br />'.
 8343:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 8344:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 8345:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 8346:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 8347:                       '</div></td></tr>'.
 8348:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 8349:                                            $othertitle,$usertypes,$types,\%servers,
 8350:                                            \%currbalancer,$lonhost,
 8351:                                            $targets_div_style,$homedom_div_style,
 8352:                                            $css_class[$cssidx],$balnum,$islast);
 8353:         $$rowtotal += $rownum;
 8354:         $balnum ++;
 8355:     }
 8356:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 8357:     return $datatable;
 8358: }
 8359: 
 8360: sub get_loadbalancers_config {
 8361:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 8362:     return unless ((ref($servers) eq 'HASH') &&
 8363:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 8364:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 8365:                    (ref($currcookies) eq 'HASH'));
 8366:     if (keys(%{$existing}) > 0) {
 8367:         my $oldlonhost;
 8368:         foreach my $key (sort(keys(%{$existing}))) {
 8369:             if ($key eq 'lonhost') {
 8370:                 $oldlonhost = $existing->{'lonhost'};
 8371:                 $currbalancer->{$oldlonhost} = 1;
 8372:             } elsif ($key eq 'targets') {
 8373:                 if ($oldlonhost) {
 8374:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 8375:                 }
 8376:             } elsif ($key eq 'rules') {
 8377:                 if ($oldlonhost) {
 8378:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 8379:                 }
 8380:             } elsif (ref($existing->{$key}) eq 'HASH') {
 8381:                 $currbalancer->{$key} = 1;
 8382:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 8383:                 $currrules->{$key} = $existing->{$key}{'rules'};
 8384:                 if ($existing->{$key}{'cookie'}) {
 8385:                     $currcookies->{$key} = 1;
 8386:                 }
 8387:             }
 8388:         }
 8389:     } else {
 8390:         my ($balancerref,$targetsref) =
 8391:                 &Apache::lonnet::get_lonbalancer_config($servers);
 8392:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 8393:             foreach my $server (sort(keys(%{$balancerref}))) {
 8394:                 $currbalancer->{$server} = 1;
 8395:                 $currtargets->{$server} = $targetsref->{$server};
 8396:             }
 8397:         }
 8398:     }
 8399:     return;
 8400: }
 8401: 
 8402: sub loadbalancing_rules {
 8403:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 8404:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 8405:         $css_class,$balnum,$islast) = @_;
 8406:     my $output;
 8407:     my $num = 0;
 8408:     my ($alltypes,$othertypes,$titles) =
 8409:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 8410:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 8411:         foreach my $type (@{$alltypes}) {
 8412:             $num ++;
 8413:             my $current;
 8414:             if (ref($currrules) eq 'HASH') {
 8415:                 $current = $currrules->{$type};
 8416:             }
 8417:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8418:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 8419:                     $current = '';
 8420:                 }
 8421:             }
 8422:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 8423:                                              $servers,$currbalancer,$lonhost,$dom,
 8424:                                              $targets_div_style,$homedom_div_style,
 8425:                                              $css_class,$balnum,$num,$islast);
 8426:         }
 8427:     }
 8428:     return $output;
 8429: }
 8430: 
 8431: sub loadbalancing_titles {
 8432:     my ($dom,$intdom,$usertypes,$types) = @_;
 8433:     my %othertypes = (
 8434:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 8435:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 8436:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 8437:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 8438:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 8439:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 8440:                      );
 8441:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 8442:     my @available;
 8443:     if (ref($types) eq 'ARRAY') {
 8444:         @available = @{$types};
 8445:     }
 8446:     unless (grep(/^default$/,@available)) {
 8447:         push(@available,'default');
 8448:     }
 8449:     unshift(@alltypes,@available);
 8450:     my %titles;
 8451:     foreach my $type (@alltypes) {
 8452:         if ($type =~ /^_LC_/) {
 8453:             $titles{$type} = $othertypes{$type};
 8454:         } elsif ($type eq 'default') {
 8455:             $titles{$type} = &mt('All users from [_1]',$dom);
 8456:             if (ref($types) eq 'ARRAY') {
 8457:                 if (@{$types} > 0) {
 8458:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 8459:                 }
 8460:             }
 8461:         } elsif (ref($usertypes) eq 'HASH') {
 8462:             $titles{$type} = $usertypes->{$type};
 8463:         }
 8464:     }
 8465:     return (\@alltypes,\%othertypes,\%titles);
 8466: }
 8467: 
 8468: sub loadbalance_rule_row {
 8469:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 8470:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 8471:     my @rulenames;
 8472:     my %ruletitles = &offloadtype_text();
 8473:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 8474:         @rulenames = ('balancer','offloadedto','specific');
 8475:     } else {
 8476:         @rulenames = ('default','homeserver');
 8477:         if ($type eq '_LC_external') {
 8478:             push(@rulenames,'externalbalancer');
 8479:         } else {
 8480:             push(@rulenames,'specific');
 8481:         }
 8482:         push(@rulenames,'none');
 8483:     }
 8484:     my $style = $targets_div_style;
 8485:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 8486:         $style = $homedom_div_style;
 8487:     }
 8488:     my $space;
 8489:     if ($islast && $num == 1) {
 8490:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 8491:     }
 8492:     my $output =
 8493:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 8494:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 8495:         '<td valaign="top">'.$space.
 8496:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 8497:     for (my $i=0; $i<@rulenames; $i++) {
 8498:         my $rule = $rulenames[$i];
 8499:         my ($checked,$extra);
 8500:         if ($rulenames[$i] eq 'default') {
 8501:             $rule = '';
 8502:         }
 8503:         if ($rulenames[$i] eq 'specific') {
 8504:             if (ref($servers) eq 'HASH') {
 8505:                 my $default;
 8506:                 if (($current ne '') && (exists($servers->{$current}))) {
 8507:                     $checked = ' checked="checked"';
 8508:                 }
 8509:                 unless ($checked) {
 8510:                     $default = ' selected="selected"';
 8511:                 }
 8512:                 $extra =
 8513:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8514:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 8515:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 8516:                     '<option value=""'.$default.'></option>'."\n";
 8517:                 foreach my $server (sort(keys(%{$servers}))) {
 8518:                     if (ref($currbalancer) eq 'HASH') {
 8519:                         next if (exists($currbalancer->{$server}));
 8520:                     }
 8521:                     my $selected;
 8522:                     if ($server eq $current) {
 8523:                         $selected = ' selected="selected"';
 8524:                     }
 8525:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 8526:                 }
 8527:                 $extra .= '</select>';
 8528:             }
 8529:         } elsif ($rule eq $current) {
 8530:             $checked = ' checked="checked"';
 8531:         }
 8532:         $output .= '<span class="LC_nobreak"><label>'.
 8533:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 8534:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 8535:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 8536:                    ')"'.$checked.' />&nbsp;';
 8537:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 8538:             $output .= $ruletitles{'particular'};
 8539:         } else {
 8540:             $output .= $ruletitles{$rulenames[$i]};
 8541:         }
 8542:         $output .= '</label>'.$extra.'</span><br />'."\n";
 8543:     }
 8544:     $output .= '</div></td></tr>'."\n";
 8545:     return $output;
 8546: }
 8547: 
 8548: sub offloadtype_text {
 8549:     my %ruletitles = &Apache::lonlocal::texthash (
 8550:            'default'          => 'Offloads to default destinations',
 8551:            'homeserver'       => "Offloads to user's home server",
 8552:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 8553:            'specific'         => 'Offloads to specific server',
 8554:            'none'             => 'No offload',
 8555:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 8556:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 8557:            'particular'       => 'Session hosted (after re-auth) on server:',
 8558:     );
 8559:     return %ruletitles;
 8560: }
 8561: 
 8562: sub sparestype_titles {
 8563:     my %typestitles = &Apache::lonlocal::texthash (
 8564:                           'primary' => 'primary',
 8565:                           'default' => 'default',
 8566:                       );
 8567:     return %typestitles;
 8568: }
 8569: 
 8570: sub contact_titles {
 8571:     my %titles = &Apache::lonlocal::texthash (
 8572:                    'supportemail'    => 'Support E-mail address',
 8573:                    'adminemail'      => 'Default Server Admin E-mail address',
 8574:                    'errormail'       => 'Error reports to be e-mailed to',
 8575:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 8576:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 8577:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 8578:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 8579:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 8580:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 8581:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 8582:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 8583:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 8584:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 8585:                    'errorweights'    => 'Weights used to compute error count',
 8586:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 8587:                  );
 8588:     my %short_titles = &Apache::lonlocal::texthash (
 8589:                            adminemail   => 'Admin E-mail address',
 8590:                            supportemail => 'Support E-mail',
 8591:                        );   
 8592:     return (\%titles,\%short_titles);
 8593: }
 8594: 
 8595: sub helpform_fields {
 8596:     my %titles =  &Apache::lonlocal::texthash (
 8597:                        'username'   => 'Name',
 8598:                        'user'       => 'Username/domain',
 8599:                        'phone'      => 'Phone',
 8600:                        'cc'         => 'Cc e-mail',
 8601:                        'course'     => 'Course Details',
 8602:                        'section'    => 'Sections',
 8603:                        'screenshot' => 'File upload',
 8604:     );
 8605:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 8606:     my %possoptions = (
 8607:                         username     => ['yes','no','req'],
 8608:                         phone        => ['yes','no','req'],
 8609:                         user         => ['yes','no'],
 8610:                         cc           => ['yes','no'],
 8611:                         course       => ['yes','no'],
 8612:                         section      => ['yes','no'],
 8613:                         screenshot   => ['yes','no'],
 8614:                       );
 8615:     my %fieldoptions = &Apache::lonlocal::texthash (
 8616:                          'yes'  => 'Optional',
 8617:                          'req'  => 'Required',
 8618:                          'no'   => "Not shown",
 8619:     );
 8620:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 8621: }
 8622: 
 8623: sub tool_titles {
 8624:     my %titles = &Apache::lonlocal::texthash (
 8625:                      aboutme    => 'Personal web page',
 8626:                      blog       => 'Blog',
 8627:                      webdav     => 'WebDAV',
 8628:                      portfolio  => 'Portfolio',
 8629:                      official   => 'Official courses (with institutional codes)',
 8630:                      unofficial => 'Unofficial courses',
 8631:                      community  => 'Communities',
 8632:                      textbook   => 'Textbook courses',
 8633:                      placement  => 'Placement tests',
 8634:                  );
 8635:     return %titles;
 8636: }
 8637: 
 8638: sub courserequest_titles {
 8639:     my %titles = &Apache::lonlocal::texthash (
 8640:                                    official   => 'Official',
 8641:                                    unofficial => 'Unofficial',
 8642:                                    community  => 'Communities',
 8643:                                    textbook   => 'Textbook',
 8644:                                    placement  => 'Placement tests',
 8645:                                    lti        => 'LTI Provider',
 8646:                                    norequest  => 'Not allowed',
 8647:                                    approval   => 'Approval by DC',
 8648:                                    validate   => 'With validation',
 8649:                                    autolimit  => 'Numerical limit',
 8650:                                    unlimited  => '(blank for unlimited)',
 8651:                  );
 8652:     return %titles;
 8653: }
 8654: 
 8655: sub authorrequest_titles {
 8656:     my %titles = &Apache::lonlocal::texthash (
 8657:                                    norequest  => 'Not allowed',
 8658:                                    approval   => 'Approval by Dom. Coord.',
 8659:                                    automatic  => 'Automatic approval',
 8660:                  );
 8661:     return %titles;
 8662: }
 8663: 
 8664: sub courserequest_conditions {
 8665:     my %conditions = &Apache::lonlocal::texthash (
 8666:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 8667:        validate   => '(Processing of request subject to institutional validation).',
 8668:                  );
 8669:     return %conditions;
 8670: }
 8671: 
 8672: 
 8673: sub print_usercreation {
 8674:     my ($position,$dom,$settings,$rowtotal) = @_;
 8675:     my $numinrow = 4;
 8676:     my $datatable;
 8677:     if ($position eq 'top') {
 8678:         $$rowtotal ++;
 8679:         my $rowcount = 0;
 8680:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 8681:         if (ref($rules) eq 'HASH') {
 8682:             if (keys(%{$rules}) > 0) {
 8683:                 $datatable .= &user_formats_row('username',$settings,$rules,
 8684:                                                 $ruleorder,$numinrow,$rowcount);
 8685:                 $$rowtotal ++;
 8686:                 $rowcount ++;
 8687:             }
 8688:         }
 8689:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 8690:         if (ref($idrules) eq 'HASH') {
 8691:             if (keys(%{$idrules}) > 0) {
 8692:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 8693:                                                 $idruleorder,$numinrow,$rowcount);
 8694:                 $$rowtotal ++;
 8695:                 $rowcount ++;
 8696:             }
 8697:         }
 8698:         if ($rowcount == 0) {
 8699:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 8700:             $$rowtotal ++;
 8701:             $rowcount ++;
 8702:         }
 8703:     } elsif ($position eq 'middle') {
 8704:         my @creators = ('author','course','requestcrs');
 8705:         my ($rules,$ruleorder) =
 8706:             &Apache::lonnet::inst_userrules($dom,'username');
 8707:         my %lt = &usercreation_types();
 8708:         my %checked;
 8709:         if (ref($settings) eq 'HASH') {
 8710:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 8711:                 foreach my $item (@creators) {
 8712:                     $checked{$item} = $settings->{'cancreate'}{$item};
 8713:                 }
 8714:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 8715:                 foreach my $item (@creators) {
 8716:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 8717:                         $checked{$item} = 'none';
 8718:                     }
 8719:                 }
 8720:             }
 8721:         }
 8722:         my $rownum = 0;
 8723:         foreach my $item (@creators) {
 8724:             $rownum ++;
 8725:             if ($checked{$item} eq '') {
 8726:                 $checked{$item} = 'any';
 8727:             }
 8728:             my $css_class;
 8729:             if ($rownum%2) {
 8730:                 $css_class = '';
 8731:             } else {
 8732:                 $css_class = ' class="LC_odd_row" ';
 8733:             }
 8734:             $datatable .= '<tr'.$css_class.'>'.
 8735:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 8736:                          '</span></td><td style="text-align: right">';
 8737:             my @options = ('any');
 8738:             if (ref($rules) eq 'HASH') {
 8739:                 if (keys(%{$rules}) > 0) {
 8740:                     push(@options,('official','unofficial'));
 8741:                 }
 8742:             }
 8743:             push(@options,'none');
 8744:             foreach my $option (@options) {
 8745:                 my $type = 'radio';
 8746:                 my $check = ' ';
 8747:                 if ($checked{$item} eq $option) {
 8748:                     $check = ' checked="checked" ';
 8749:                 } 
 8750:                 $datatable .= '<span class="LC_nobreak"><label>'.
 8751:                               '<input type="'.$type.'" name="can_createuser_'.
 8752:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 8753:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 8754:             }
 8755:             $datatable .= '</td></tr>';
 8756:         }
 8757:     } else {
 8758:         my @contexts = ('author','course','domain');
 8759:         my @authtypes = ('int','krb4','krb5','loc','lti');
 8760:         my %checked;
 8761:         if (ref($settings) eq 'HASH') {
 8762:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 8763:                 foreach my $item (@contexts) {
 8764:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 8765:                         foreach my $auth (@authtypes) {
 8766:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 8767:                                 $checked{$item}{$auth} = ' checked="checked" ';
 8768:                             }
 8769:                         }
 8770:                     }
 8771:                 }
 8772:             }
 8773:         } else {
 8774:             foreach my $item (@contexts) {
 8775:                 foreach my $auth (@authtypes) {
 8776:                     $checked{$item}{$auth} = ' checked="checked" ';
 8777:                 }
 8778:             }
 8779:         }
 8780:         my %title = &context_names();
 8781:         my %authname = &authtype_names();
 8782:         my $rownum = 0;
 8783:         my $css_class; 
 8784:         foreach my $item (@contexts) {
 8785:             if ($rownum%2) {
 8786:                 $css_class = '';
 8787:             } else {
 8788:                 $css_class = ' class="LC_odd_row" ';
 8789:             }
 8790:             $datatable .=   '<tr'.$css_class.'>'.
 8791:                             '<td>'.$title{$item}.
 8792:                             '</td><td class="LC_left_item">'.
 8793:                             '<span class="LC_nobreak">';
 8794:             foreach my $auth (@authtypes) {
 8795:                 $datatable .= '<label>'. 
 8796:                               '<input type="checkbox" name="'.$item.'_auth" '.
 8797:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 8798:                               $authname{$auth}.'</label>&nbsp;';
 8799:             }
 8800:             $datatable .= '</span></td></tr>';
 8801:             $rownum ++;
 8802:         }
 8803:         $$rowtotal += $rownum;
 8804:     }
 8805:     return $datatable;
 8806: }
 8807: 
 8808: sub print_selfcreation {
 8809:     my ($position,$dom,$settings,$rowtotal) = @_;
 8810:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 8811:         $emaildomain,$datatable);
 8812:     if (ref($settings) eq 'HASH') {
 8813:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 8814:             $createsettings = $settings->{'cancreate'};
 8815:             if (ref($createsettings) eq 'HASH') {
 8816:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 8817:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 8818:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 8819:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 8820:                         @selfcreate = ('email','login','sso');
 8821:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 8822:                         @selfcreate = ($createsettings->{'selfcreate'});
 8823:                     }
 8824:                 }
 8825:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 8826:                     $processing = $createsettings->{'selfcreateprocessing'};
 8827:                 }
 8828:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 8829:                     $emailoptions = $createsettings->{'emailoptions'};
 8830:                 }
 8831:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 8832:                     $emailverified = $createsettings->{'emailverified'};
 8833:                 }
 8834:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 8835:                     $emaildomain = $createsettings->{'emaildomain'};
 8836:                 }
 8837:             }
 8838:         }
 8839:     }
 8840:     my %radiohash;
 8841:     my $numinrow = 4;
 8842:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 8843:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8844:     if ($position eq 'top') {
 8845:         my %choices = &Apache::lonlocal::texthash (
 8846:                                                       cancreate_login      => 'Institutional Login',
 8847:                                                       cancreate_sso        => 'Institutional Single Sign On',
 8848:                                                   );
 8849:         my @toggles = sort(keys(%choices));
 8850:         my %defaultchecked = (
 8851:                                'cancreate_login' => 'off',
 8852:                                'cancreate_sso'   => 'off',
 8853:                              );
 8854:         my ($onclick,$itemcount);
 8855:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 8856:                                                      \%choices,$itemcount,$onclick);
 8857:         $$rowtotal += $itemcount;
 8858:         
 8859:         if (ref($usertypes) eq 'HASH') {
 8860:             if (keys(%{$usertypes}) > 0) {
 8861:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 8862:                                              $dom,$numinrow,$othertitle,
 8863:                                              'statustocreate',$rowtotal);
 8864:                 $$rowtotal ++;
 8865:             }
 8866:         }
 8867:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 8868:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 8869:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 8870:         my $rem;
 8871:         my $numperrow = 2;
 8872:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 8873:         $datatable .= '<tr'.$css_class.'>'.
 8874:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 8875:                      '<td class="LC_left_item">'."\n".
 8876:                      '<table>'."\n";
 8877:         for (my $i=0; $i<@fields; $i++) {
 8878:             $rem = $i%($numperrow);
 8879:             if ($rem == 0) {
 8880:                 if ($i > 0) {
 8881:                     $datatable .= '</tr>';
 8882:                 }
 8883:                 $datatable .= '<tr>';
 8884:             }
 8885:             my $currval;
 8886:             if (ref($createsettings) eq 'HASH') {
 8887:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 8888:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 8889:                 }
 8890:             }
 8891:             $datatable .= '<td class="LC_left_item">'.
 8892:                           '<span class="LC_nobreak">'.
 8893:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 8894:                           'value="'.$currval.'" size="10" />&nbsp;'.
 8895:                           $fieldtitles{$fields[$i]}.'</span></td>';
 8896:         }
 8897:         my $colsleft = $numperrow - $rem;
 8898:         if ($colsleft > 1 ) {
 8899:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8900:                          '&nbsp;</td>';
 8901:         } elsif ($colsleft == 1) {
 8902:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8903:         }
 8904:         $datatable .= '</tr></table></td></tr>';
 8905:         $$rowtotal ++;
 8906:     } elsif ($position eq 'middle') {
 8907:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 8908:         my @posstypes;
 8909:         if (ref($types) eq 'ARRAY') {
 8910:             @posstypes = @{$types};
 8911:         }
 8912:         unless (grep(/^default$/,@posstypes)) {
 8913:             push(@posstypes,'default');
 8914:         }
 8915:         my %usertypeshash;
 8916:         if (ref($usertypes) eq 'HASH') {
 8917:             %usertypeshash = %{$usertypes};
 8918:         }
 8919:         $usertypeshash{'default'} = $othertitle;
 8920:         foreach my $status (@posstypes) {
 8921:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 8922:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 8923:             $$rowtotal ++;
 8924:         }
 8925:     } else {
 8926:         my %choices = &Apache::lonlocal::texthash (
 8927:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 8928:                                                   );
 8929:         my @toggles = sort(keys(%choices));
 8930:         my %defaultchecked = (
 8931:                                'cancreate_email' => 'off',
 8932:                              );
 8933:         my $customclass = 'LC_selfcreate_email';
 8934:         my $classprefix = 'LC_canmodify_emailusername_';
 8935:         my $optionsprefix = 'LC_options_emailusername_';
 8936:         my $display = 'none';
 8937:         my $rowstyle = 'display:none';
 8938:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 8939:             $display = 'block';
 8940:             $rowstyle = 'display:table-row';
 8941:         }
 8942:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 8943:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 8944:                                                      \%choices,$$rowtotal,$onclick);
 8945:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 8946:                                          $rowstyle);
 8947:         $$rowtotal ++;
 8948:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 8949:                                       $rowstyle);
 8950:         $$rowtotal ++;
 8951:         my (@ordered,@posstypes,%usertypeshash);
 8952:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
 8953:         my ($emailrules,$emailruleorder) =
 8954:             &Apache::lonnet::inst_userrules($dom,'email');
 8955:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8956:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8957:         if (ref($types) eq 'ARRAY') {
 8958:             @posstypes = @{$types};
 8959:         }
 8960:         if (@posstypes) {
 8961:             unless (grep(/^default$/,@posstypes)) {
 8962:                 push(@posstypes,'default');
 8963:             }
 8964:             if (ref($usertypes) eq 'HASH') {
 8965:                 %usertypeshash = %{$usertypes};
 8966:             }
 8967:             my $currassign;
 8968:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
 8969:                 $currassign = {
 8970:                                   selfassign => $domdefaults{'inststatusguest'},
 8971:                               };
 8972:                 @ordered = @{$domdefaults{'inststatusguest'}};
 8973:             } else {
 8974:                 $currassign = { selfassign => [] };
 8975:             }
 8976:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
 8977:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
 8978:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
 8979:                                          $numinrow,$othertitle,'selfassign',
 8980:                                          $rowtotal,$onclicktypes,$customclass,
 8981:                                          $rowstyle);
 8982:             $$rowtotal ++;
 8983:             $usertypeshash{'default'} = $othertitle;
 8984:             foreach my $status (@posstypes) {
 8985:                 my $css_class;
 8986:                 if ($$rowtotal%2) {
 8987:                     $css_class = 'LC_odd_row ';
 8988:                 }
 8989:                 $css_class .= $customclass;
 8990:                 my $rowid = $optionsprefix.$status;
 8991:                 my $hidden = 1;
 8992:                 my $currstyle = 'display:none';
 8993:                 if (grep(/^\Q$status\E$/,@ordered)) {
 8994:                     $currstyle = $rowstyle;
 8995:                     $hidden = 0; 
 8996:                 }
 8997:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 8998:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
 8999:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
 9000:                 unless ($hidden) {
 9001:                     $$rowtotal ++;
 9002:                 }
 9003:             }
 9004:         } else {
 9005:             my $css_class;
 9006:             if ($$rowtotal%2) {
 9007:                 $css_class = 'LC_odd_row ';
 9008:             }
 9009:             $css_class .= $customclass;
 9010:             $usertypeshash{'default'} = $othertitle;
 9011:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
 9012:                                          $emailrules,$emailruleorder,$settings,'default','',
 9013:                                          $othertitle,$css_class,$rowstyle,$intdom);
 9014:             $$rowtotal ++;
 9015:         }
 9016:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
 9017:         $numinrow = 1;
 9018:         if (@posstypes) {
 9019:             foreach my $status (@posstypes) {
 9020:                 my $rowid = $classprefix.$status;
 9021:                 my $datarowstyle = 'display:none';
 9022:                 if (grep(/^\Q$status\E$/,@ordered)) { 
 9023:                     $datarowstyle = $rowstyle; 
 9024:                 }
 9025:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
 9026:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9027:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
 9028:                 unless ($datarowstyle eq 'display:none') {
 9029:                     $$rowtotal ++;
 9030:                 }
 9031:             }
 9032:         } else {
 9033:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
 9034:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
 9035:                                                    $infotitles,'',$customclass,$rowstyle);
 9036:         }
 9037:     }
 9038:     return $datatable;
 9039: }
 9040: 
 9041: sub selfcreate_javascript {
 9042:     return <<"ENDSCRIPT";
 9043: 
 9044: <script type="text/javascript">
 9045: // <![CDATA[
 9046: 
 9047: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
 9048:     var x = document.getElementsByClassName(target);
 9049:     var insttypes = 0;
 9050:     var insttypeRegExp = new RegExp(prefix);
 9051:     if ((x.length != undefined) && (x.length > 0)) {
 9052:         if (form.elements[radio].length != undefined) {
 9053:             for (var i=0; i<form.elements[radio].length; i++) {
 9054:                 if (form.elements[radio][i].checked) {
 9055:                     if (form.elements[radio][i].value == 1) {
 9056:                         for (var j=0; j<x.length; j++) {
 9057:                             if (x[j].id == 'undefined') {
 9058:                                 x[j].style.display = 'table-row';
 9059:                             } else if (insttypeRegExp.test(x[j].id)) {
 9060:                                 insttypes ++;
 9061:                             } else {
 9062:                                 x[j].style.display = 'table-row';
 9063:                             }
 9064:                         }
 9065:                     } else {
 9066:                         for (var j=0; j<x.length; j++) {
 9067:                             x[j].style.display = 'none';
 9068:                         }
 9069:                     }
 9070:                     break;
 9071:                 }
 9072:             }
 9073:             if (insttypes > 0) {
 9074:                 toggleDataRow(form,checkbox,target,altprefix);
 9075:                 toggleDataRow(form,checkbox,target,prefix,1);
 9076:             }
 9077:         }
 9078:     }
 9079:     return;
 9080: }
 9081: 
 9082: function toggleDataRow(form,checkbox,target,prefix,docount) {
 9083:     if (form.elements[checkbox].length != undefined) {
 9084:         var count = 0;
 9085:         if (docount) {
 9086:             for (var i=0; i<form.elements[checkbox].length; i++) {
 9087:                 if (form.elements[checkbox][i].checked) {
 9088:                     count ++;
 9089:                 }
 9090:             }
 9091:         }
 9092:         for (var i=0; i<form.elements[checkbox].length; i++) {
 9093:             var type = form.elements[checkbox][i].value;
 9094:             if (document.getElementById(prefix+type)) {
 9095:                 if (form.elements[checkbox][i].checked) {
 9096:                     document.getElementById(prefix+type).style.display = 'table-row';
 9097:                     if (count % 2 == 1) {
 9098:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 9099:                     } else {
 9100:                         document.getElementById(prefix+type).className = target;
 9101:                     }
 9102:                     count ++;
 9103:                 } else {
 9104:                     document.getElementById(prefix+type).style.display = 'none';
 9105:                 }
 9106:             }
 9107:         }
 9108:     }
 9109:     return;
 9110: }
 9111: 
 9112: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
 9113:     var caller = radio+'_'+status;
 9114:     if (form.elements[caller].length != undefined) {
 9115:         for (var i=0; i<form.elements[caller].length; i++) {
 9116:             if (form.elements[caller][i].checked) {
 9117:                 if (document.getElementById(altprefix+'_inst_'+status)) {
 9118:                     var curr = form.elements[caller][i].value;
 9119:                     if (prefix) {
 9120:                         document.getElementById(prefix+'_'+status).style.display = 'none';
 9121:                     }
 9122:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
 9123:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
 9124:                     if (curr == 'custom') {
 9125:                         if (prefix) { 
 9126:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
 9127:                         }
 9128:                     } else if (curr == 'inst') {
 9129:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
 9130:                     } else if (curr == 'noninst') {
 9131:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
 9132:                     }
 9133:                     break;
 9134:                 }
 9135:             }
 9136:         }
 9137:     }
 9138: }
 9139: 
 9140: // ]]>
 9141: </script>
 9142: 
 9143: ENDSCRIPT
 9144: }
 9145: 
 9146: sub noninst_users {
 9147:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
 9148:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
 9149:     my $class = 'LC_left_item';
 9150:     if ($css_class) {
 9151:         $css_class = ' class="'.$css_class.'"'; 
 9152:     }
 9153:     if ($rowid) {
 9154:         $rowid = ' id="'.$rowid.'"';
 9155:     }
 9156:     if ($rowstyle) {
 9157:         $rowstyle = ' style="'.$rowstyle.'"';
 9158:     }
 9159:     my ($output,$description);
 9160:     if ($type eq 'default') {
 9161:         $description = &mt('Requests for: [_1]',$typetitle);
 9162:     } else {
 9163:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
 9164:     }
 9165:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 9166:               "<td>$description</td>\n".           
 9167:               '<td class="'.$class.'" colspan="2">'.
 9168:               '<table><tr>';
 9169:     my %headers = &Apache::lonlocal::texthash( 
 9170:               approve  => 'Processing',
 9171:               email    => 'E-mail',
 9172:               username => 'Username',
 9173:     );
 9174:     foreach my $item ('approve','email','username') {
 9175:         $output .= '<th>'.$headers{$item}.'</th>';
 9176:     }
 9177:     $output .= '</tr><tr>';
 9178:     foreach my $item ('approve','email','username') {
 9179:         $output .= '<td style="vertical-align: top">';
 9180:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
 9181:         if ($item eq 'approve') {
 9182:             %choices = &Apache::lonlocal::texthash (
 9183:                                                      automatic => 'Automatically approved',
 9184:                                                      approval  => 'Queued for approval',
 9185:                                                    );
 9186:             @options = ('automatic','approval');
 9187:             $hashref = $processing;
 9188:             $defoption = 'automatic';
 9189:             $name = 'cancreate_emailprocess_'.$type;
 9190:         } elsif ($item eq 'email') {
 9191:             %choices = &Apache::lonlocal::texthash (
 9192:                                                      any     => 'Any e-mail',
 9193:                                                      inst    => 'Institutional only',
 9194:                                                      noninst => 'Non-institutional only',
 9195:                                                      custom  => 'Custom restrictions',
 9196:                                                    );
 9197:             @options = ('any','inst','noninst');
 9198:             my $showcustom;
 9199:             if (ref($emailrules) eq 'HASH') {
 9200:                 if (keys(%{$emailrules}) > 0) {
 9201:                     push(@options,'custom');
 9202:                     $showcustom = 'cancreate_emailrule';
 9203:                     if (ref($settings) eq 'HASH') {
 9204:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 9205:                             foreach my $rule (@{$settings->{'email_rule'}}) {
 9206:                                 if (exists($emailrules->{$rule})) {
 9207:                                     $hascustom ++;
 9208:                                 }
 9209:                             }
 9210:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
 9211:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
 9212:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
 9213:                                     if (exists($emailrules->{$rule})) {
 9214:                                         $hascustom ++;
 9215:                                     }
 9216:                                 }
 9217:                             }
 9218:                         }
 9219:                     }
 9220:                 }
 9221:             }
 9222:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
 9223:                                                      "'cancreate_emaildomain','$type'".');"';
 9224:             $hashref = $emailoptions;
 9225:             $defoption = 'any';
 9226:             $name = 'cancreate_emailoptions_'.$type;
 9227:         } elsif ($item eq 'username') {
 9228:             %choices = &Apache::lonlocal::texthash (
 9229:                                                      all    => 'Same as e-mail',
 9230:                                                      first  => 'Omit @domain',
 9231:                                                      free   => 'Free to choose',
 9232:                                                    );
 9233:             @options = ('all','first','free');
 9234:             $hashref = $emailverified;
 9235:             $defoption = 'all';
 9236:             $name = 'cancreate_usernameoptions_'.$type;
 9237:         }
 9238:         foreach my $option (@options) {
 9239:             my $checked;
 9240:             if (ref($hashref) eq 'HASH') {
 9241:                 if ($type eq '') {
 9242:                     if (!exists($hashref->{'default'})) {
 9243:                         if ($option eq $defoption) {
 9244:                             $checked = ' checked="checked"';
 9245:                         }
 9246:                     } else {
 9247:                         if ($hashref->{'default'} eq $option) {
 9248:                             $checked = ' checked="checked"';
 9249:                         }
 9250:                     }
 9251:                 } else {
 9252:                     if (!exists($hashref->{$type})) {
 9253:                         if ($option eq $defoption) {
 9254:                             $checked = ' checked="checked"';
 9255:                         }
 9256:                     } else {
 9257:                         if ($hashref->{$type} eq $option) {
 9258:                             $checked = ' checked="checked"';
 9259:                         }
 9260:                     }
 9261:                 }
 9262:             } elsif (($item eq 'email') && ($hascustom)) {
 9263:                 if ($option eq 'custom') {
 9264:                     $checked = ' checked="checked"';
 9265:                 }
 9266:             } elsif ($option eq $defoption) {
 9267:                 $checked = ' checked="checked"';
 9268:             }
 9269:             $output .= '<span class="LC_nobreak"><label>'.
 9270:                        '<input type="radio" name="'.$name.'"'.
 9271:                        $checked.' value="'.$option.'"'.$onclick.' />'.
 9272:                        $choices{$option}.'</label></span><br />';
 9273:             if ($item eq 'email') {
 9274:                 if ($option eq 'custom') {
 9275:                     my $id = 'cancreate_emailrule_'.$type;
 9276:                     my $display = 'none';
 9277:                     if ($checked) {
 9278:                         $display = 'inline';
 9279:                     }
 9280:                     my $numinrow = 2;
 9281:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
 9282:                                '<legend>'.&mt('Disallow').'</legend><table>'.
 9283:                                &user_formats_row('email',$settings,$emailrules,
 9284:                                                  $emailruleorder,$numinrow,'',$type);
 9285:                               '</table></fieldset>';
 9286:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
 9287:                     my %text = &Apache::lonlocal::texthash (
 9288:                                                              inst    => 'must end:',
 9289:                                                              noninst => 'cannot end:',
 9290:                                                            );
 9291:                     my $value;
 9292:                     if (ref($emaildomain) eq 'HASH') {
 9293:                         if (ref($emaildomain->{$type}) eq 'HASH') {
 9294:                             $value = $emaildomain->{$type}->{$option}; 
 9295:                         }
 9296:                     }
 9297:                     if ($value eq '') {
 9298:                         $value = '@'.$intdom;
 9299:                     }
 9300:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
 9301:                     my $display = 'none';
 9302:                     if ($checked) {
 9303:                         $display = 'inline';
 9304:                     }
 9305:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
 9306:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
 9307:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
 9308:                                '</div>';
 9309:                 }
 9310:             }
 9311:         }
 9312:         $output .= '</td>'."\n";
 9313:     }
 9314:     $output .= "</tr></table></td></tr>\n";
 9315:     return $output;
 9316: }
 9317: 
 9318: sub captcha_choice {
 9319:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
 9320:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
 9321:         $vertext,$currver);
 9322:     my %lt = &captcha_phrases();
 9323:     $keyentry = 'hidden';
 9324:     my $colspan=2;
 9325:     if ($context eq 'cancreate') {
 9326:         $rowname = &mt('CAPTCHA validation');
 9327:     } elsif ($context eq 'login') {
 9328:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
 9329:     } elsif ($context eq 'passwords') {
 9330:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
 9331:         $colspan=1;
 9332:     }
 9333:     if (ref($settings) eq 'HASH') {
 9334:         if ($settings->{'captcha'}) {
 9335:             $checked{$settings->{'captcha'}} = ' checked="checked"';
 9336:         } else {
 9337:             $checked{'original'} = ' checked="checked"';
 9338:         }
 9339:         if ($settings->{'captcha'} eq 'recaptcha') {
 9340:             $pubtext = $lt{'pub'};
 9341:             $privtext = $lt{'priv'};
 9342:             $keyentry = 'text';
 9343:             $vertext = $lt{'ver'};
 9344:             $currver = $settings->{'recaptchaversion'};
 9345:             if ($currver ne '2') {
 9346:                 $currver = 1;
 9347:             }
 9348:         }
 9349:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
 9350:             $currpub = $settings->{'recaptchakeys'}{'public'};
 9351:             $currpriv = $settings->{'recaptchakeys'}{'private'};
 9352:         }
 9353:     } else {
 9354:         $checked{'original'} = ' checked="checked"';
 9355:     }
 9356:     my $css_class;
 9357:     if ($itemcount%2) {
 9358:         $css_class = 'LC_odd_row';
 9359:     }
 9360:     if ($customcss) {
 9361:         $css_class .= " $customcss";
 9362:     }
 9363:     $css_class =~ s/^\s+//;
 9364:     if ($css_class) {
 9365:         $css_class = ' class="'.$css_class.'"';
 9366:     }
 9367:     if ($rowstyle) {
 9368:         $css_class .= ' style="'.$rowstyle.'"';
 9369:     }
 9370:     my $output = '<tr'.$css_class.'>'.
 9371:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
 9372:                  '<table><tr><td>'."\n";
 9373:     foreach my $option ('original','recaptcha','notused') {
 9374:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
 9375:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
 9376:                    $lt{$option}.'</label></span>';
 9377:         unless ($option eq 'notused') {
 9378:             $output .= ('&nbsp;'x2)."\n";
 9379:         }
 9380:     }
 9381: #
 9382: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
 9383: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
 9384: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
 9385: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
 9386: #
 9387:     $output .= '</td></tr>'."\n".
 9388:                '<tr><td class="LC_zero_height">'."\n".
 9389:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
 9390:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
 9391:                $currpub.'" size="40" /></span><br />'."\n".
 9392:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
 9393:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
 9394:                $currpriv.'" size="40" /></span><br />'.
 9395:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
 9396:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
 9397:                $currver.'" size="3" /></span><br />'.
 9398:                '</td></tr></table>'."\n".
 9399:                '</td></tr>';
 9400:     return $output;
 9401: }
 9402: 
 9403: sub user_formats_row {
 9404:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
 9405:     my $output;
 9406:     my %text = (
 9407:                    'username' => 'new usernames',
 9408:                    'id'       => 'IDs',
 9409:                );
 9410:     unless ($type eq 'email') {
 9411:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
 9412:         $output = '<tr '.$css_class.'>'.
 9413:                   '<td><span class="LC_nobreak">'.
 9414:                   &mt("Format rules to check for $text{$type}: ").
 9415:                   '</td><td class="LC_left_item" colspan="2"><table>';
 9416:     }
 9417:     my $rem;
 9418:     if (ref($ruleorder) eq 'ARRAY') {
 9419:         for (my $i=0; $i<@{$ruleorder}; $i++) {
 9420:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
 9421:                 my $rem = $i%($numinrow);
 9422:                 if ($rem == 0) {
 9423:                     if ($i > 0) {
 9424:                         $output .= '</tr>';
 9425:                     }
 9426:                     $output .= '<tr>';
 9427:                 }
 9428:                 my $check = ' ';
 9429:                 if (ref($settings) eq 'HASH') {
 9430:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
 9431:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
 9432:                             $check = ' checked="checked" ';
 9433:                         }
 9434:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
 9435:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
 9436:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
 9437:                                 $check = ' checked="checked" ';
 9438:                             }
 9439:                         }
 9440:                     }
 9441:                 }
 9442:                 my $name = $type.'_rule';
 9443:                 if ($type eq 'email') {
 9444:                     $name .= '_'.$status;
 9445:                 }
 9446:                 $output .= '<td class="LC_left_item">'.
 9447:                            '<span class="LC_nobreak"><label>'.
 9448:                            '<input type="checkbox" name="'.$name.'" '.
 9449:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
 9450:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
 9451:             }
 9452:         }
 9453:         $rem = @{$ruleorder}%($numinrow);
 9454:     }
 9455:     my $colsleft;
 9456:     if ($rem) {
 9457:         $colsleft = $numinrow - $rem;
 9458:     }
 9459:     if ($colsleft > 1 ) {
 9460:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9461:                    '&nbsp;</td>';
 9462:     } elsif ($colsleft == 1) {
 9463:         $output .= '<td class="LC_left_item">&nbsp;</td>';
 9464:     }
 9465:     $output .= '</tr></table>';
 9466:     unless ($type eq 'email') {
 9467:         $output .= '</td></tr>';
 9468:     }
 9469:     return $output;
 9470: }
 9471: 
 9472: sub usercreation_types {
 9473:     my %lt = &Apache::lonlocal::texthash (
 9474:                     author     => 'When adding a co-author',
 9475:                     course     => 'When adding a user to a course',
 9476:                     requestcrs => 'When requesting a course',
 9477:                     any        => 'Any',
 9478:                     official   => 'Institutional only ',
 9479:                     unofficial => 'Non-institutional only',
 9480:                     none       => 'None',
 9481:     );
 9482:     return %lt;
 9483: }
 9484: 
 9485: sub selfcreation_types {
 9486:     my %lt = &Apache::lonlocal::texthash (
 9487:                     selfcreate => 'User creates own account',
 9488:                     any        => 'Any',
 9489:                     official   => 'Institutional only ',
 9490:                     unofficial => 'Non-institutional only',
 9491:                     email      => 'E-mail address',
 9492:                     login      => 'Institutional Login',
 9493:                     sso        => 'SSO',
 9494:              );
 9495: }
 9496: 
 9497: sub authtype_names {
 9498:     my %lt = &Apache::lonlocal::texthash(
 9499:                       int    => 'Internal',
 9500:                       krb4   => 'Kerberos 4',
 9501:                       krb5   => 'Kerberos 5',
 9502:                       loc    => 'Local',
 9503:                       lti    => 'LTI',
 9504:                   );
 9505:     return %lt;
 9506: }
 9507: 
 9508: sub context_names {
 9509:     my %context_title = &Apache::lonlocal::texthash(
 9510:        author => 'Creating users when an Author',
 9511:        course => 'Creating users when in a course',
 9512:        domain => 'Creating users when a Domain Coordinator',
 9513:     );
 9514:     return %context_title;
 9515: }
 9516: 
 9517: sub print_usermodification {
 9518:     my ($position,$dom,$settings,$rowtotal) = @_;
 9519:     my $numinrow = 4;
 9520:     my ($context,$datatable,$rowcount);
 9521:     if ($position eq 'top') {
 9522:         $rowcount = 0;
 9523:         $context = 'author'; 
 9524:         foreach my $role ('ca','aa') {
 9525:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9526:                                                    $numinrow,$rowcount);
 9527:             $$rowtotal ++;
 9528:             $rowcount ++;
 9529:         }
 9530:     } elsif ($position eq 'bottom') {
 9531:         $context = 'course';
 9532:         $rowcount = 0;
 9533:         foreach my $role ('st','ep','ta','in','cr') {
 9534:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
 9535:                                                    $numinrow,$rowcount);
 9536:             $$rowtotal ++;
 9537:             $rowcount ++;
 9538:         }
 9539:     }
 9540:     return $datatable;
 9541: }
 9542: 
 9543: sub print_defaults {
 9544:     my ($position,$dom,$settings,$rowtotal) = @_;
 9545:     my $rownum = 0;
 9546:     my ($datatable,$css_class,$titles);
 9547:     unless ($position eq 'bottom') {
 9548:         $titles = &defaults_titles($dom);
 9549:     }
 9550:     if ($position eq 'top') {
 9551:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
 9552:                      'datelocale_def','portal_def');
 9553:         my %defaults;
 9554:         if (ref($settings) eq 'HASH') {
 9555:             %defaults = %{$settings};
 9556:         } else {
 9557:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
 9558:             foreach my $item (@items) {
 9559:                 $defaults{$item} = $domdefaults{$item};
 9560:             }
 9561:         }
 9562:         foreach my $item (@items) {
 9563:             if ($rownum%2) {
 9564:                 $css_class = '';
 9565:             } else {
 9566:                 $css_class = ' class="LC_odd_row" ';
 9567:             }
 9568:             $datatable .= '<tr'.$css_class.'>'.
 9569:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 9570:                           '</span></td><td class="LC_right_item" colspan="3">';
 9571:             if ($item eq 'auth_def') {
 9572:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
 9573:                 my %shortauth = (
 9574:                                  internal => 'int',
 9575:                                  krb4 => 'krb4',
 9576:                                  krb5 => 'krb5',
 9577:                                  localauth  => 'loc',
 9578:                                  lti => 'lti',
 9579:                                 );
 9580:                 my %authnames = &authtype_names();
 9581:                 foreach my $auth (@authtypes) {
 9582:                     my $checked = ' ';
 9583:                     if ($defaults{$item} eq $auth) {
 9584:                         $checked = ' checked="checked" ';
 9585:                     }
 9586:                     $datatable .= '<label><input type="radio" name="'.$item.
 9587:                                   '" value="'.$auth.'"'.$checked.'/>'.
 9588:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
 9589:                 }
 9590:             } elsif ($item eq 'timezone_def') {
 9591:                 my $includeempty = 1;
 9592:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
 9593:             } elsif ($item eq 'datelocale_def') {
 9594:                 my $includeempty = 1;
 9595:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
 9596:             } elsif ($item eq 'lang_def') {
 9597:                 my $includeempty = 1;
 9598:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
 9599:             } else {
 9600:                 my $size;
 9601:                 if ($item eq 'portal_def') {
 9602:                     $size = ' size="25"';
 9603:                 }
 9604:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 9605:                               $defaults{$item}.'"'.$size.' />';
 9606:             }
 9607:             $datatable .= '</td></tr>';
 9608:             $rownum ++;
 9609:         }
 9610:     } else {
 9611:         my %defaults;
 9612:         if (ref($settings) eq 'HASH') {
 9613:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
 9614:                 my $maxnum = @{$settings->{'inststatusorder'}};
 9615:                 for (my $i=0; $i<$maxnum; $i++) {
 9616:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
 9617:                     my $item = $settings->{'inststatusorder'}->[$i];
 9618:                     my $title = $settings->{'inststatustypes'}->{$item};
 9619:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
 9620:                     $datatable .= '<tr'.$css_class.'>'.
 9621:                                   '<td><span class="LC_nobreak">'.
 9622:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
 9623:                     for (my $k=0; $k<=$maxnum; $k++) {
 9624:                         my $vpos = $k+1;
 9625:                         my $selstr;
 9626:                         if ($k == $i) {
 9627:                             $selstr = ' selected="selected" ';
 9628:                         }
 9629:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9630:                     }
 9631:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
 9632:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
 9633:                                   &mt('delete').'</span></td>'.
 9634:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
 9635:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
 9636:                                   '</span></td></tr>';
 9637:                 }
 9638:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
 9639:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
 9640:                 $datatable .= '<tr '.$css_class.'>'.
 9641:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
 9642:                 for (my $k=0; $k<=$maxnum; $k++) {
 9643:                     my $vpos = $k+1;
 9644:                     my $selstr;
 9645:                     if ($k == $maxnum) {
 9646:                         $selstr = ' selected="selected" ';
 9647:                     }
 9648:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 9649:                 }
 9650:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
 9651:                               '<input type="text" size="10" name="addinststatus" value="" />'.
 9652:                               '&nbsp;'.&mt('(new)').
 9653:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
 9654:                               &mt('Name displayed').':'.
 9655:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
 9656:                               '</tr>'."\n";
 9657:                 $rownum ++;
 9658:             }
 9659:         }
 9660:     }
 9661:     $$rowtotal += $rownum;
 9662:     return $datatable;
 9663: }
 9664: 
 9665: sub get_languages_hash {
 9666:     my %langchoices;
 9667:     foreach my $id (&Apache::loncommon::languageids()) {
 9668:         my $code = &Apache::loncommon::supportedlanguagecode($id);
 9669:         if ($code ne '') {
 9670:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
 9671:         }
 9672:     }
 9673:     return %langchoices;
 9674: }
 9675: 
 9676: sub defaults_titles {
 9677:     my ($dom) = @_;
 9678:     my %titles = &Apache::lonlocal::texthash (
 9679:                    'auth_def'      => 'Default authentication type',
 9680:                    'auth_arg_def'  => 'Default authentication argument',
 9681:                    'lang_def'      => 'Default language',
 9682:                    'timezone_def'  => 'Default timezone',
 9683:                    'datelocale_def' => 'Default locale for dates',
 9684:                    'portal_def'     => 'Portal/Default URL',
 9685:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
 9686:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
 9687:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
 9688:                  );
 9689:     if ($dom) {
 9690:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
 9691:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 9692:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
 9693:         $protocol = 'http' if ($protocol ne 'https');
 9694:         if ($uint_dom) {
 9695:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
 9696:                                          $uint_dom);
 9697:         }
 9698:     }
 9699:     return (\%titles);
 9700: }
 9701: 
 9702: sub print_scantron {
 9703:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
 9704:     if ($position eq 'top') {
 9705:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
 9706:     } else {
 9707:         return &print_scantronconfig($dom,$settings,\$rowtotal);
 9708:     }
 9709: }
 9710: 
 9711: sub scantron_javascript {
 9712:     return <<"ENDSCRIPT";
 9713: 
 9714: <script type="text/javascript">
 9715: // <![CDATA[
 9716: 
 9717: function toggleScantron(form) {
 9718:     var csvfieldset = new Array();
 9719:     if (document.getElementById('scantroncsv_cols')) {
 9720:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
 9721:     }
 9722:     if (document.getElementById('scantroncsv_options')) {
 9723:         csvfieldset.push(document.getElementById('scantroncsv_options'));
 9724:     }
 9725:     if (csvfieldset.length) {
 9726:         if (document.getElementById('scantronconfcsv')) {
 9727:             var scantroncsv = document.getElementById('scantronconfcsv');
 9728:             if (scantroncsv.checked) {
 9729:                 for (var i=0; i<csvfieldset.length; i++) {
 9730:                     csvfieldset[i].style.display = 'block';
 9731:                 }
 9732:             } else {
 9733:                 for (var i=0; i<csvfieldset.length; i++) {
 9734:                     csvfieldset[i].style.display = 'none';
 9735:                 }
 9736:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
 9737:                 if (csvselects.length) {
 9738:                     for (var j=0; j<csvselects.length; j++) {
 9739:                         csvselects[j].selectedIndex = 0;
 9740:                     }
 9741:                 }
 9742:             }
 9743:         }
 9744:     }
 9745:     return;
 9746: }
 9747: // ]]>
 9748: </script>
 9749: 
 9750: ENDSCRIPT
 9751: 
 9752: }
 9753: 
 9754: sub print_scantronformat {
 9755:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
 9756:     my $itemcount = 1;
 9757:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
 9758:         %confhash);
 9759:     my $switchserver = &check_switchserver($dom,$confname);
 9760:     my %lt = &Apache::lonlocal::texthash (
 9761:                 default => 'Default bubblesheet format file error',
 9762:                 custom  => 'Custom bubblesheet format file error',
 9763:              );
 9764:     my %scantronfiles = (
 9765:         default => 'default.tab',
 9766:         custom => 'custom.tab',
 9767:     );
 9768:     foreach my $key (keys(%scantronfiles)) {
 9769:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
 9770:                               .$scantronfiles{$key};
 9771:     }
 9772:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
 9773:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
 9774:         if (!$switchserver) {
 9775:             my $servadm = $r->dir_config('lonAdmEMail');
 9776:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
 9777:             if ($configuserok eq 'ok') {
 9778:                 if ($author_ok eq 'ok') {
 9779:                     my %legacyfile = (
 9780:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
 9781:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
 9782:                     );
 9783:                     my %md5chk;
 9784:                     foreach my $type (keys(%legacyfile)) {
 9785:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
 9786:                         chomp($md5chk{$type});
 9787:                     }
 9788:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
 9789:                         foreach my $type (keys(%legacyfile)) {
 9790:                             ($scantronurls{$type},my $error) =
 9791:                                 &legacy_scantronformat($r,$dom,$confname,
 9792:                                                  $type,$legacyfile{$type},
 9793:                                                  $scantronurls{$type},
 9794:                                                  $scantronfiles{$type});
 9795:                             if ($error ne '') {
 9796:                                 $error{$type} = $error;
 9797:                             }
 9798:                         }
 9799:                         if (keys(%error) == 0) {
 9800:                             $is_custom = 1;
 9801:                             $confhash{'scantron'}{'scantronformat'} =
 9802:                                 $scantronurls{'custom'};
 9803:                             my $putresult =
 9804:                                 &Apache::lonnet::put_dom('configuration',
 9805:                                                          \%confhash,$dom);
 9806:                             if ($putresult ne 'ok') {
 9807:                                 $error{'custom'} =
 9808:                                     '<span class="LC_error">'.
 9809:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 9810:                             }
 9811:                         }
 9812:                     } else {
 9813:                         ($scantronurls{'default'},my $error) =
 9814:                             &legacy_scantronformat($r,$dom,$confname,
 9815:                                           'default',$legacyfile{'default'},
 9816:                                           $scantronurls{'default'},
 9817:                                           $scantronfiles{'default'});
 9818:                         if ($error eq '') {
 9819:                             $confhash{'scantron'}{'scantronformat'} = ''; 
 9820:                             my $putresult =
 9821:                                 &Apache::lonnet::put_dom('configuration',
 9822:                                                          \%confhash,$dom);
 9823:                             if ($putresult ne 'ok') {
 9824:                                 $error{'default'} =
 9825:                                     '<span class="LC_error">'.
 9826:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
 9827:                             }
 9828:                         } else {
 9829:                             $error{'default'} = $error;
 9830:                         }
 9831:                     }
 9832:                 }
 9833:             }
 9834:         } else {
 9835:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
 9836:         }
 9837:     }
 9838:     if (ref($settings) eq 'HASH') {
 9839:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
 9840:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
 9841:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
 9842:                 $scantronurl = '';
 9843:             } else {
 9844:                 $scantronurl = $settings->{'scantronformat'};
 9845:             }
 9846:             $is_custom = 1;
 9847:         } else {
 9848:             $scantronurl = $scantronurls{'default'};
 9849:         }
 9850:     } else {
 9851:         if ($is_custom) {
 9852:             $scantronurl = $scantronurls{'custom'};
 9853:         } else {
 9854:             $scantronurl = $scantronurls{'default'};
 9855:         }
 9856:     }
 9857:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 9858:     $datatable .= '<tr'.$css_class.'>';
 9859:     if (!$is_custom) {
 9860:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
 9861:                       '<span class="LC_nobreak">';
 9862:         if ($scantronurl) {
 9863:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
 9864:                                                          undef,undef,undef,undef,'background-color:#ffffff');
 9865:         } else {
 9866:             $datatable = &mt('File unavailable for display');
 9867:         }
 9868:         $datatable .= '</span></td>';
 9869:         if (keys(%error) == 0) { 
 9870:             $datatable .= '<td style="vertical-align: bottom">';
 9871:             if (!$switchserver) {
 9872:                 $datatable .= &mt('Upload:').'<br />';
 9873:             }
 9874:         } else {
 9875:             my $errorstr;
 9876:             foreach my $key (sort(keys(%error))) {
 9877:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 9878:             }
 9879:             $datatable .= '<td>'.$errorstr;
 9880:         }
 9881:     } else {
 9882:         if (keys(%error) > 0) {
 9883:             my $errorstr;
 9884:             foreach my $key (sort(keys(%error))) {
 9885:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
 9886:             } 
 9887:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
 9888:         } elsif ($scantronurl) {
 9889:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
 9890:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 9891:             $datatable .= '<td><span class="LC_nobreak">'.
 9892:                           $link.
 9893:                           '<label><input type="checkbox" name="scantronformat_del"'.
 9894:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
 9895:                           '<td><span class="LC_nobreak">&nbsp;'.
 9896:                           &mt('Replace:').'</span><br />';
 9897:         }
 9898:     }
 9899:     if (keys(%error) == 0) {
 9900:         if ($switchserver) {
 9901:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 9902:         } else {
 9903:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 9904:                          '<input type="file" name="scantronformat" /></span>';
 9905:         }
 9906:     }
 9907:     $datatable .= '</td></tr>';
 9908:     $$rowtotal ++;
 9909:     return $datatable;
 9910: }
 9911: 
 9912: sub legacy_scantronformat {
 9913:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
 9914:     my ($url,$error);
 9915:     my @statinfo = &Apache::lonnet::stat_file($newurl);
 9916:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
 9917:         (my $result,$url) =
 9918:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
 9919:                          '','',$newfile);
 9920:         if ($result ne 'ok') {
 9921:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
 9922:         }
 9923:     }
 9924:     return ($url,$error);
 9925: }
 9926: 
 9927: sub print_scantronconfig {
 9928:     my ($dom,$settings,$rowtotal) = @_;
 9929:     my $itemcount = 2;
 9930:     my $is_checked = ' checked="checked"';
 9931:     my %optionson = (
 9932:                      hdr => ' checked="checked"',
 9933:                      pad => ' checked="checked"',
 9934:                      rem => ' checked="checked"',
 9935:                     );
 9936:     my %optionsoff = (
 9937:                       hdr => '',
 9938:                       pad => '',
 9939:                       rem => '',
 9940:                      );
 9941:     my $currcsvsty = 'none';
 9942:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
 9943:     my @fields = &scantroncsv_fields();
 9944:     my %titles = &scantronconfig_titles();
 9945:     if (ref($settings) eq 'HASH') {
 9946:         if (ref($settings->{config}) eq 'HASH') {
 9947:             if ($settings->{config}->{dat}) {
 9948:                 $checked{'dat'} = $is_checked;
 9949:             }
 9950:             if (ref($settings->{config}->{csv}) eq 'HASH') {
 9951:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
 9952:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
 9953:                     if (keys(%csvfields) > 0) {
 9954:                         $checked{'csv'} = $is_checked;
 9955:                         $currcsvsty = 'block';
 9956:                     }
 9957:                 }
 9958:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
 9959:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
 9960:                     foreach my $option (keys(%optionson)) {
 9961:                         unless ($csvoptions{$option}) {
 9962:                             $optionsoff{$option} = $optionson{$option};
 9963:                             $optionson{$option} = '';
 9964:                         }
 9965:                     }
 9966:                 }
 9967:             }
 9968:         } else {
 9969:             $checked{'dat'} = $is_checked;
 9970:         }
 9971:     } else {
 9972:         $checked{'dat'} = $is_checked;
 9973:     }
 9974:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
 9975:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
 9976:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
 9977:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
 9978:     foreach my $item ('dat','csv') {
 9979:         my $id;
 9980:         if ($item eq 'csv') {
 9981:             $id = 'id="scantronconfcsv" ';
 9982:         }
 9983:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
 9984:                       $titles{$item}.'</label>'.('&nbsp;'x3);
 9985:         if ($item eq 'csv') {
 9986:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
 9987:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
 9988:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
 9989:             foreach my $col (@fields) {
 9990:                 my $selnone;
 9991:                 if ($csvfields{$col} eq '') {
 9992:                     $selnone = ' selected="selected"';
 9993:                 }
 9994:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
 9995:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
 9996:                               '<option value=""'.$selnone.'></option>';
 9997:                 for (my $i=0; $i<20; $i++) {
 9998:                     my $shown = $i+1;
 9999:                     my $sel;
10000:                     unless ($selnone) {
10001:                         if (exists($csvfields{$col})) {
10002:                             if ($csvfields{$col} == $i) {
10003:                                 $sel = ' selected="selected"';
10004:                             }
10005:                         }
10006:                     }
10007:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
10008:                 }
10009:                 $datatable .= '</select></td></tr>';
10010:            }
10011:            $datatable .= '</table></fieldset>'.
10012:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
10013:                          '<legend>'.&mt('CSV Options').'</legend>';
10014:            foreach my $option ('hdr','pad','rem') {
10015:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
10016:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
10017:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
10018:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
10019:            }
10020:            $datatable .= '</fieldset>';
10021:            $itemcount ++;
10022:         }
10023:     }
10024:     $datatable .= '</td></tr>';
10025:     $$rowtotal ++;
10026:     return $datatable;
10027: }
10028: 
10029: sub scantronconfig_titles {
10030:     return &Apache::lonlocal::texthash(
10031:                                           dat => 'Standard format (.dat)',
10032:                                           csv => 'Comma separated values (.csv)',
10033:                                           hdr => 'Remove first line in file (contains column titles)',
10034:                                           pad => 'Prepend 0s to PaperID',
10035:                                           rem => 'Remove leading spaces (except Question Response columns)',
10036:                                           CODE => 'CODE',
10037:                                           ID   => 'Student ID',
10038:                                           PaperID => 'Paper ID',
10039:                                           FirstName => 'First Name',
10040:                                           LastName => 'Last Name',
10041:                                           FirstQuestion => 'First Question Response',
10042:                                           Section => 'Section',
10043:     );
10044: }
10045: 
10046: sub scantroncsv_fields {
10047:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
10048: }
10049: 
10050: sub print_coursecategories {
10051:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
10052:     my $datatable;
10053:     if ($position eq 'top') {
10054:         my (%checked);
10055:         my @catitems = ('unauth','auth');
10056:         my @cattypes = ('std','domonly','codesrch','none');
10057:         $checked{'unauth'} = 'std';
10058:         $checked{'auth'} = 'std';
10059:         if (ref($settings) eq 'HASH') {
10060:             foreach my $type (@cattypes) {
10061:                 if ($type eq $settings->{'unauth'}) {
10062:                     $checked{'unauth'} = $type;
10063:                 }
10064:                 if ($type eq $settings->{'auth'}) {
10065:                     $checked{'auth'} = $type;
10066:                 }
10067:             }
10068:         }
10069:         my %lt = &Apache::lonlocal::texthash (
10070:                                                unauth   => 'Catalog type for unauthenticated users',
10071:                                                auth     => 'Catalog type for authenticated users',
10072:                                                none     => 'No catalog',
10073:                                                std      => 'Standard catalog',
10074:                                                domonly  => 'Domain-only catalog',
10075:                                                codesrch => "Code search form",
10076:                                              );
10077:        my $itemcount = 0;
10078:        foreach my $item (@catitems) {
10079:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
10080:            $datatable .= '<tr '.$css_class.'>'.
10081:                          '<td>'.$lt{$item}.'</td>'.
10082:                          '<td class="LC_right_item"><span class="LC_nobreak">';
10083:            foreach my $type (@cattypes) {
10084:                my $ischecked;
10085:                if ($checked{$item} eq $type) {
10086:                    $ischecked=' checked="checked"';
10087:                }
10088:                $datatable .= '<label>'.
10089:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
10090:                              ' />'.$lt{$type}.'</label>&nbsp;';
10091:            }
10092:            $datatable .= '</span></td></tr>';
10093:            $itemcount ++;
10094:         }
10095:         $$rowtotal += $itemcount;
10096:     } elsif ($position eq 'middle') {
10097:         my $toggle_cats_crs = ' ';
10098:         my $toggle_cats_dom = ' checked="checked" ';
10099:         my $can_cat_crs = ' ';
10100:         my $can_cat_dom = ' checked="checked" ';
10101:         my $toggle_catscomm_comm = ' ';
10102:         my $toggle_catscomm_dom = ' checked="checked" ';
10103:         my $can_catcomm_comm = ' ';
10104:         my $can_catcomm_dom = ' checked="checked" ';
10105:         my $toggle_catsplace_place = ' ';
10106:         my $toggle_catsplace_dom = ' checked="checked" ';
10107:         my $can_catplace_place = ' ';
10108:         my $can_catplace_dom = ' checked="checked" ';
10109: 
10110:         if (ref($settings) eq 'HASH') {
10111:             if ($settings->{'togglecats'} eq 'crs') {
10112:                 $toggle_cats_crs = $toggle_cats_dom;
10113:                 $toggle_cats_dom = ' ';
10114:             }
10115:             if ($settings->{'categorize'} eq 'crs') {
10116:                 $can_cat_crs = $can_cat_dom;
10117:                 $can_cat_dom = ' ';
10118:             }
10119:             if ($settings->{'togglecatscomm'} eq 'comm') {
10120:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
10121:                 $toggle_catscomm_dom = ' ';
10122:             }
10123:             if ($settings->{'categorizecomm'} eq 'comm') {
10124:                 $can_catcomm_comm = $can_catcomm_dom;
10125:                 $can_catcomm_dom = ' ';
10126:             }
10127:             if ($settings->{'togglecatsplace'} eq 'place') {
10128:                 $toggle_catsplace_place = $toggle_catsplace_dom;
10129:                 $toggle_catsplace_dom = ' ';
10130:             }
10131:             if ($settings->{'categorizeplace'} eq 'place') {
10132:                 $can_catplace_place = $can_catplace_dom;
10133:                 $can_catplace_dom = ' ';
10134:             }
10135:         }
10136:         my %title = &Apache::lonlocal::texthash (
10137:                      togglecats      => 'Show/Hide a course in catalog',
10138:                      togglecatscomm  => 'Show/Hide a community in catalog',
10139:                      togglecatsplace => 'Show/Hide a placement test in catalog',
10140:                      categorize      => 'Assign a category to a course',
10141:                      categorizecomm  => 'Assign a category to a community',
10142:                      categorizeplace => 'Assign a category to a placement test',
10143:                     );
10144:         my %level = &Apache::lonlocal::texthash (
10145:                      dom   => 'Set in Domain',
10146:                      crs   => 'Set in Course',
10147:                      comm  => 'Set in Community',
10148:                      place => 'Set in Placement Test',
10149:                     );
10150:         $datatable = '<tr class="LC_odd_row">'.
10151:                   '<td>'.$title{'togglecats'}.'</td>'.
10152:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10153:                   '<input type="radio" name="togglecats"'.
10154:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10155:                   '<label><input type="radio" name="togglecats"'.
10156:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
10157:                   '</tr><tr>'.
10158:                   '<td>'.$title{'categorize'}.'</td>'.
10159:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10160:                   '<label><input type="radio" name="categorize"'.
10161:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10162:                   '<label><input type="radio" name="categorize"'.
10163:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
10164:                   '</tr><tr class="LC_odd_row">'.
10165:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
10166:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10167:                   '<input type="radio" name="togglecatscomm"'.
10168:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10169:                   '<label><input type="radio" name="togglecatscomm"'.
10170:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
10171:                   '</tr><tr>'.
10172:                   '<td>'.$title{'categorizecomm'}.'</td>'.
10173:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10174:                   '<label><input type="radio" name="categorizecomm"'.
10175:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10176:                   '<label><input type="radio" name="categorizecomm"'.
10177:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
10178:                   '</tr><tr class="LC_odd_row">'.
10179:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
10180:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
10181:                   '<input type="radio" name="togglecatsplace"'.
10182:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10183:                   '<label><input type="radio" name="togglecatscomm"'.
10184:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
10185:                   '</tr><tr>'.
10186:                   '<td>'.$title{'categorizeplace'}.'</td>'.
10187:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
10188:                   '<label><input type="radio" name="categorizeplace"'.
10189:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
10190:                   '<label><input type="radio" name="categorizeplace"'.
10191:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
10192:                   '</tr>';
10193:         $$rowtotal += 6;
10194:     } else {
10195:         my $css_class;
10196:         my $itemcount = 1;
10197:         my $cathash; 
10198:         if (ref($settings) eq 'HASH') {
10199:             $cathash = $settings->{'cats'};
10200:         }
10201:         if (ref($cathash) eq 'HASH') {
10202:             my (@cats,@trails,%allitems,%idx,@jsarray);
10203:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
10204:                                                    \%allitems,\%idx,\@jsarray);
10205:             my $maxdepth = scalar(@cats);
10206:             my $colattrib = '';
10207:             if ($maxdepth > 2) {
10208:                 $colattrib = ' colspan="2" ';
10209:             }
10210:             my @path;
10211:             if (@cats > 0) {
10212:                 if (ref($cats[0]) eq 'ARRAY') {
10213:                     my $numtop = @{$cats[0]};
10214:                     my $maxnum = $numtop;
10215:                     my %default_names = (
10216:                           instcode    => &mt('Official courses'),
10217:                           communities => &mt('Communities'),
10218:                           placement   => &mt('Placement Tests'),
10219:                     );
10220: 
10221:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
10222:                         ($cathash->{'instcode::0'} eq '') ||
10223:                         (!grep(/^communities$/,@{$cats[0]})) || 
10224:                         ($cathash->{'communities::0'} eq '') ||
10225:                         (!grep(/^placement$/,@{$cats[0]})) ||
10226:                         ($cathash->{'placement::0'} eq '')) {
10227:                         $maxnum ++;
10228:                     }
10229:                     my $lastidx;
10230:                     for (my $i=0; $i<$numtop; $i++) {
10231:                         my $parent = $cats[0][$i];
10232:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10233:                         my $item = &escape($parent).'::0';
10234:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
10235:                         $lastidx = $idx{$item};
10236:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10237:                                       .'<select name="'.$item.'"'.$chgstr.'>';
10238:                         for (my $k=0; $k<=$maxnum; $k++) {
10239:                             my $vpos = $k+1;
10240:                             my $selstr;
10241:                             if ($k == $i) {
10242:                                 $selstr = ' selected="selected" ';
10243:                             }
10244:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10245:                         }
10246:                         $datatable .= '</select></span></td><td>';
10247:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
10248:                             $datatable .=  '<span class="LC_nobreak">'
10249:                                            .$default_names{$parent}.'</span>';
10250:                             if ($parent eq 'instcode') {
10251:                                 $datatable .= '<br /><span class="LC_nobreak">('
10252:                                               .&mt('with institutional codes')
10253:                                               .')</span></td><td'.$colattrib.'>';
10254:                             } else {
10255:                                 $datatable .= '<table><tr><td>';
10256:                             }
10257:                             $datatable .= '<span class="LC_nobreak">'
10258:                                           .'<label><input type="radio" name="'
10259:                                           .$parent.'" value="1" checked="checked" />'
10260:                                           .&mt('Display').'</label>';
10261:                             if ($parent eq 'instcode') {
10262:                                 $datatable .= '&nbsp;';
10263:                             } else {
10264:                                 $datatable .= '</span></td></tr><tr><td>'
10265:                                               .'<span class="LC_nobreak">';
10266:                             }
10267:                             $datatable .= '<label><input type="radio" name="'
10268:                                           .$parent.'" value="0" />'
10269:                                           .&mt('Do not display').'</label></span>';
10270:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
10271:                                 $datatable .= '</td></tr></table>';
10272:                             }
10273:                             $datatable .= '</td>';
10274:                         } else {
10275:                             $datatable .= $parent
10276:                                           .'&nbsp;<span class="LC_nobreak"><label>'
10277:                                           .'<input type="checkbox" name="deletecategory" '
10278:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
10279:                         }
10280:                         my $depth = 1;
10281:                         push(@path,$parent);
10282:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
10283:                         pop(@path);
10284:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
10285:                         $itemcount ++;
10286:                     }
10287:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10288:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
10289:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
10290:                     for (my $k=0; $k<=$maxnum; $k++) {
10291:                         my $vpos = $k+1;
10292:                         my $selstr;
10293:                         if ($k == $numtop) {
10294:                             $selstr = ' selected="selected" ';
10295:                         }
10296:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10297:                     }
10298:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
10299:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
10300:                                   .'</tr>'."\n";
10301:                     $itemcount ++;
10302:                     foreach my $default ('instcode','communities','placement') {
10303:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
10304:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
10305:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
10306:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
10307:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
10308:                             for (my $k=0; $k<=$maxnum; $k++) {
10309:                                 my $vpos = $k+1;
10310:                                 my $selstr;
10311:                                 if ($k == $maxnum) {
10312:                                     $selstr = ' selected="selected" ';
10313:                                 }
10314:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10315:                             }
10316:                             $datatable .= '</select></span></td>'.
10317:                                           '<td><span class="LC_nobreak">'.
10318:                                           $default_names{$default}.'</span>';
10319:                             if ($default eq 'instcode') {
10320:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
10321:                                               .&mt('with institutional codes').')</span>';
10322:                             }
10323:                             $datatable .= '</td>'
10324:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
10325:                                           .&mt('Display').'</label>&nbsp;'
10326:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
10327:                                           .&mt('Do not display').'</label></span></td></tr>';
10328:                         }
10329:                     }
10330:                 }
10331:             } else {
10332:                 $datatable .= &initialize_categories($itemcount);
10333:             }
10334:         } else {
10335:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
10336:                           .&initialize_categories($itemcount);
10337:         }
10338:         $$rowtotal += $itemcount;
10339:     }
10340:     return $datatable;
10341: }
10342: 
10343: sub print_serverstatuses {
10344:     my ($dom,$settings,$rowtotal) = @_;
10345:     my $datatable;
10346:     my @pages = &serverstatus_pages();
10347:     my (%namedaccess,%machineaccess);
10348:     foreach my $type (@pages) {
10349:         $namedaccess{$type} = '';
10350:         $machineaccess{$type}= '';
10351:     }
10352:     if (ref($settings) eq 'HASH') {
10353:         foreach my $type (@pages) {
10354:             if (exists($settings->{$type})) {
10355:                 if (ref($settings->{$type}) eq 'HASH') {
10356:                     foreach my $key (keys(%{$settings->{$type}})) {
10357:                         if ($key eq 'namedusers') {
10358:                             $namedaccess{$type} = $settings->{$type}->{$key};
10359:                         } elsif ($key eq 'machines') {
10360:                             $machineaccess{$type} = $settings->{$type}->{$key};
10361:                         }
10362:                     }
10363:                 }
10364:             }
10365:         }
10366:     }
10367:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
10368:     my $rownum = 0;
10369:     my $css_class;
10370:     foreach my $type (@pages) {
10371:         $rownum ++;
10372:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10373:         $datatable .= '<tr'.$css_class.'>'.
10374:                       '<td><span class="LC_nobreak">'.
10375:                       $titles->{$type}.'</span></td>'.
10376:                       '<td class="LC_left_item">'.
10377:                       '<input type="text" name="'.$type.'_namedusers" '.
10378:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
10379:                       '<td class="LC_right_item">'.
10380:                       '<span class="LC_nobreak">'.
10381:                       '<input type="text" name="'.$type.'_machines" '.
10382:                       'value="'.$machineaccess{$type}.'" size="10" />'.
10383:                       '</span></td></tr>'."\n";
10384:     }
10385:     $$rowtotal += $rownum;
10386:     return $datatable;
10387: }
10388: 
10389: sub serverstatus_pages {
10390:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
10391:             'checksums','clusterstatus','certstatus','metadata_keywords',
10392:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
10393:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
10394: }
10395: 
10396: sub defaults_javascript {
10397:     my ($settings) = @_;
10398:     return unless (ref($settings) eq 'HASH');
10399:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10400:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
10401:         if ($maxnum eq '') {
10402:             $maxnum = 0;
10403:         }
10404:         $maxnum ++;
10405:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
10406:         return <<"ENDSCRIPT";
10407: <script type="text/javascript">
10408: // <![CDATA[
10409: function reorderTypes(form,caller) {
10410:     var changedVal;
10411: $jstext 
10412:     var newpos = 'addinststatus_pos';
10413:     var current = new Array;
10414:     var maxh = $maxnum;
10415:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10416:     var oldVal;
10417:     if (caller == newpos) {
10418:         changedVal = newitemVal;
10419:     } else {
10420:         var curritem = 'inststatus_pos_'+caller;
10421:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
10422:         current[newitemVal] = newpos;
10423:     }
10424:     for (var i=0; i<inststatuses.length; i++) {
10425:         if (inststatuses[i] != caller) {
10426:             var elementName = 'inststatus_pos_'+inststatuses[i];
10427:             if (form.elements[elementName]) {
10428:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10429:                 current[currVal] = elementName;
10430:             }
10431:         }
10432:     }
10433:     for (var j=0; j<maxh; j++) {
10434:         if (current[j] == undefined) {
10435:             oldVal = j;
10436:         }
10437:     }
10438:     if (oldVal < changedVal) {
10439:         for (var k=oldVal+1; k<=changedVal ; k++) {
10440:            var elementName = current[k];
10441:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10442:         }
10443:     } else {
10444:         for (var k=changedVal; k<oldVal; k++) {
10445:             var elementName = current[k];
10446:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10447:         }
10448:     }
10449:     return;
10450: }
10451: 
10452: // ]]>
10453: </script>
10454: 
10455: ENDSCRIPT
10456:     }
10457:     return;
10458: }
10459: 
10460: sub passwords_javascript {
10461:     my %intalert = &Apache::lonlocal::texthash (
10462:         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.',
10463:         authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
10464:         passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
10465:         passmax => 'Warning: maximum password length must be a positive integer (or blank).',
10466:         passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
10467:         passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
10468:     );
10469:     &js_escape(\%intalert);
10470:     my $defmin = $Apache::lonnet::passwdmin;
10471:     my $intauthjs = <<"ENDSCRIPT";
10472: 
10473: function warnIntAuth(field) {
10474:     if (field.name == 'intauth_check') {
10475:         if (field.value == '2') {
10476:             alert('$intalert{authcheck}');
10477:         }
10478:     }
10479:     if (field.name == 'intauth_cost') {
10480:         field.value.replace(/\s/g,'');
10481:         if (field.value != '') {
10482:             var regexdigit=/^\\d+\$/;
10483:             if (!regexdigit.test(field.value)) {
10484:                 alert('$intalert{authcost}');
10485:             }
10486:         }
10487:     }
10488:     return;
10489: }
10490: 
10491: function warnIntPass(field) {
10492:     field.value.replace(/^\s+/,'');
10493:     field.value.replace(/\s+\$/,'');
10494:     var regexdigit=/^\\d+\$/;
10495:     if (field.name == 'passwords_min') {
10496:         if (field.value == '') {
10497:             alert('$intalert{passmin}');
10498:             field.value = '$defmin';
10499:         } else {
10500:             if (!regexdigit.test(field.value)) {
10501:                 alert('$intalert{passmin}');
10502:                 field.value = '$defmin';
10503:             }
10504:             var minval = parseInt(field.value,10);
10505:             if (minval < $defmin) {
10506:                 alert('$intalert{passmin}');
10507:                 field.value = '$defmin';
10508:             }
10509:         }
10510:     } else {
10511:         if (field.value == '0') {
10512:             field.value = '';
10513:         }
10514:         if (field.value != '') {
10515:             if (field.name == 'passwords_expire') {
10516:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
10517:                 if (!regexpposnum.test(field.value)) {
10518:                     alert('$intalert{passexp}');
10519:                     field.value = '';
10520:                 } else {
10521:                     var expval = parseFloat(field.value);
10522:                     if (expval == 0) {
10523:                         alert('$intalert{passexp}');
10524:                         field.value = '';
10525:                     }
10526:                 }
10527:             } else {
10528:                 if (!regexdigit.test(field.value)) {
10529:                     if (field.name == 'passwords_max') {
10530:                         alert('$intalert{passmax}');
10531:                     } else {
10532:                         if (field.name == 'passwords_numsaved') {
10533:                             alert('$intalert{passnum}');
10534:                         }
10535:                     }
10536:                     field.value = '';
10537:                 }
10538:             }
10539:         }
10540:     }
10541:     return;
10542: }
10543: 
10544: ENDSCRIPT
10545:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
10546: }
10547: 
10548: sub coursecategories_javascript {
10549:     my ($settings) = @_;
10550:     my ($output,$jstext,$cathash);
10551:     if (ref($settings) eq 'HASH') {
10552:         $cathash = $settings->{'cats'};
10553:     }
10554:     if (ref($cathash) eq 'HASH') {
10555:         my (@cats,@jsarray,%idx);
10556:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
10557:         if (@jsarray > 0) {
10558:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
10559:             for (my $i=0; $i<@jsarray; $i++) {
10560:                 if (ref($jsarray[$i]) eq 'ARRAY') {
10561:                     my $catstr = join('","',@{$jsarray[$i]});
10562:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
10563:                 }
10564:             }
10565:         }
10566:     } else {
10567:         $jstext  = '    var categories = Array(1);'."\n".
10568:                    '    categories[0] = Array("instcode_pos");'."\n"; 
10569:     }
10570:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
10571:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
10572:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
10573:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
10574:     &js_escape(\$instcode_reserved);
10575:     &js_escape(\$communities_reserved);
10576:     &js_escape(\$placement_reserved);
10577:     &js_escape(\$choose_again);
10578:     $output = <<"ENDSCRIPT";
10579: <script type="text/javascript">
10580: // <![CDATA[
10581: function reorderCats(form,parent,item,idx) {
10582:     var changedVal;
10583: $jstext
10584:     var newpos = 'addcategory_pos';
10585:     if (parent == '') {
10586:         var has_instcode = 0;
10587:         var maxtop = categories[idx].length;
10588:         for (var j=0; j<maxtop; j++) {
10589:             if (categories[idx][j] == 'instcode::0') {
10590:                 has_instcode == 1;
10591:             }
10592:         }
10593:         if (has_instcode == 0) {
10594:             categories[idx][maxtop] = 'instcode_pos';
10595:         }
10596:     } else {
10597:         newpos += '_'+parent;
10598:     }
10599:     var maxh = 1 + categories[idx].length;
10600:     var current = new Array;
10601:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
10602:     if (item == newpos) {
10603:         changedVal = newitemVal;
10604:     } else {
10605:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
10606:         current[newitemVal] = newpos;
10607:     }
10608:     for (var i=0; i<categories[idx].length; i++) {
10609:         var elementName = categories[idx][i];
10610:         if (elementName != item) {
10611:             if (form.elements[elementName]) {
10612:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
10613:                 current[currVal] = elementName;
10614:             }
10615:         }
10616:     }
10617:     var oldVal;
10618:     for (var j=0; j<maxh; j++) {
10619:         if (current[j] == undefined) {
10620:             oldVal = j;
10621:         }
10622:     }
10623:     if (oldVal < changedVal) {
10624:         for (var k=oldVal+1; k<=changedVal ; k++) {
10625:            var elementName = current[k];
10626:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
10627:         }
10628:     } else {
10629:         for (var k=changedVal; k<oldVal; k++) {
10630:             var elementName = current[k];
10631:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
10632:         }
10633:     }
10634:     return;
10635: }
10636: 
10637: function categoryCheck(form) {
10638:     if (form.elements['addcategory_name'].value == 'instcode') {
10639:         alert('$instcode_reserved\\n$choose_again');
10640:         return false;
10641:     }
10642:     if (form.elements['addcategory_name'].value == 'communities') {
10643:         alert('$communities_reserved\\n$choose_again');
10644:         return false;
10645:     }
10646:     if (form.elements['addcategory_name'].value == 'placement') {
10647:         alert('$placement_reserved\\n$choose_again');
10648:         return false;
10649:     }
10650:     return true;
10651: }
10652: 
10653: // ]]>
10654: </script>
10655: 
10656: ENDSCRIPT
10657:     return $output;
10658: }
10659: 
10660: sub initialize_categories {
10661:     my ($itemcount) = @_;
10662:     my ($datatable,$css_class,$chgstr);
10663:     my %default_names = &Apache::lonlocal::texthash (
10664:                       instcode    => 'Official courses (with institutional codes)',
10665:                       communities => 'Communities',
10666:                       placement   => 'Placement Tests',
10667:                         );
10668:     my %selnum = (
10669:                    instcode    => '0',
10670:                    communities => '1',
10671:                    placement   => '2',
10672:                  );
10673:     my %selected;
10674:     foreach my $default ('instcode','communities','placement') {
10675:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
10676:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
10677:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
10678:         $selected{$selnum{$default}} = ' selected="selected"';
10679:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10680:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
10681:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
10682:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
10683:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
10684:                      .'<option value="3">4</option></select>&nbsp;'
10685:                      .$default_names{$default}
10686:                      .'</span></td><td><span class="LC_nobreak">'
10687:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
10688:                      .&mt('Display').'</label>&nbsp;<label>'
10689:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
10690:                  .'</label></span></td></tr>';
10691:         $itemcount ++;
10692:     }
10693:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10694:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
10695:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
10696:                   .'<select name="addcategory_pos"'.$chgstr.'>'
10697:                   .'<option value="0">1</option>'
10698:                   .'<option value="1">2</option>'
10699:                   .'<option value="2">3</option>'
10700:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
10701:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
10702:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
10703:                   .'</td></tr>';
10704:     return $datatable;
10705: }
10706: 
10707: sub build_category_rows {
10708:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
10709:     my ($text,$name,$item,$chgstr);
10710:     if (ref($cats) eq 'ARRAY') {
10711:         my $maxdepth = scalar(@{$cats});
10712:         if (ref($cats->[$depth]) eq 'HASH') {
10713:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
10714:                 my $numchildren = @{$cats->[$depth]{$parent}};
10715:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
10716:                 $text .= '<td><table class="LC_data_table">';
10717:                 my ($idxnum,$parent_name,$parent_item);
10718:                 my $higher = $depth - 1;
10719:                 if ($higher == 0) {
10720:                     $parent_name = &escape($parent).'::'.$higher;
10721:                 } else {
10722:                     if (ref($path) eq 'ARRAY') {
10723:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10724:                     }
10725:                 }
10726:                 $parent_item = 'addcategory_pos_'.$parent_name;
10727:                 for (my $j=0; $j<=$numchildren; $j++) {
10728:                     if ($j < $numchildren) {
10729:                         $name = $cats->[$depth]{$parent}[$j];
10730:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
10731:                         $idxnum = $idx->{$item};
10732:                     } else {
10733:                         $name = $parent_name;
10734:                         $item = $parent_item;
10735:                     }
10736:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
10737:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
10738:                     for (my $i=0; $i<=$numchildren; $i++) {
10739:                         my $vpos = $i+1;
10740:                         my $selstr;
10741:                         if ($j == $i) {
10742:                             $selstr = ' selected="selected" ';
10743:                         }
10744:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
10745:                     }
10746:                     $text .= '</select>&nbsp;';
10747:                     if ($j < $numchildren) {
10748:                         my $deeper = $depth+1;
10749:                         $text .= $name.'&nbsp;'
10750:                                  .'<label><input type="checkbox" name="deletecategory" value="'
10751:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
10752:                         if(ref($path) eq 'ARRAY') {
10753:                             push(@{$path},$name);
10754:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
10755:                             pop(@{$path});
10756:                         }
10757:                     } else {
10758:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
10759:                         if ($j == $numchildren) {
10760:                             $text .= $name;
10761:                         } else {
10762:                             $text .= $item;
10763:                         }
10764:                         $text .= '" value="" />';
10765:                     }
10766:                     $text .= '</td></tr>';
10767:                 }
10768:                 $text .= '</table></td>';
10769:             } else {
10770:                 my $higher = $depth-1;
10771:                 if ($higher == 0) {
10772:                     $name = &escape($parent).'::'.$higher;
10773:                 } else {
10774:                     if (ref($path) eq 'ARRAY') {
10775:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
10776:                     }
10777:                 }
10778:                 my $colspan;
10779:                 if ($parent ne 'instcode') {
10780:                     $colspan = $maxdepth - $depth - 1;
10781:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
10782:                 }
10783:             }
10784:         }
10785:     }
10786:     return $text;
10787: }
10788: 
10789: sub modifiable_userdata_row {
10790:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
10791:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
10792:     my ($role,$rolename,$statustype);
10793:     $role = $item;
10794:     if ($context eq 'cancreate') {
10795:         if ($item =~ /^(emailusername)_(.+)$/) {
10796:             $role = $1;
10797:             $statustype = $2;
10798:             if (ref($usertypes) eq 'HASH') {
10799:                 if ($usertypes->{$statustype}) {
10800:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
10801:                 } else {
10802:                     $rolename = &mt('Data provided by user');
10803:                 }
10804:             }
10805:         }
10806:     } elsif ($context eq 'selfcreate') {
10807:         if (ref($usertypes) eq 'HASH') {
10808:             $rolename = $usertypes->{$role};
10809:         } else {
10810:             $rolename = $role;
10811:         }
10812:     } elsif ($context eq 'lti') {
10813:         $rolename = &mt('Institutional data used (if available)');
10814:     } elsif ($context eq 'privacy') {
10815:         $rolename = $itemdesc;
10816:     } else {
10817:         if ($role eq 'cr') {
10818:             $rolename = &mt('Custom role');
10819:         } else {
10820:             $rolename = &Apache::lonnet::plaintext($role);
10821:         }
10822:     }
10823:     my (@fields,%fieldtitles);
10824:     if (ref($fieldsref) eq 'ARRAY') {
10825:         @fields = @{$fieldsref};
10826:     } else {
10827:         @fields = ('lastname','firstname','middlename','generation',
10828:                    'permanentemail','id');
10829:     }
10830:     if ((ref($titlesref) eq 'HASH')) {
10831:         %fieldtitles = %{$titlesref};
10832:     } else {
10833:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
10834:     }
10835:     my $output;
10836:     my $css_class;
10837:     if ($rowcount%2) {
10838:         $css_class = 'LC_odd_row';
10839:     }
10840:     if ($customcss) {
10841:         $css_class .= " $customcss";
10842:     }
10843:     $css_class =~ s/^\s+//;
10844:     if ($css_class) {
10845:         $css_class = ' class="'.$css_class.'"';
10846:     }
10847:     if ($rowstyle) {
10848:         $css_class .= ' style="'.$rowstyle.'"';
10849:     }
10850:     if ($rowid) {
10851:         $rowid = ' id="'.$rowid.'"';
10852:     }
10853:     $output = '<tr '.$css_class.$rowid.'>'.
10854:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
10855:               '<td class="LC_left_item" colspan="2"><table>';
10856:     my $rem;
10857:     my %checks;
10858:     my %current;
10859:     if (ref($settings) eq 'HASH') {
10860:         my $hashref;
10861:         if ($context eq 'lti') {
10862:             if (ref($settings) eq 'HASH') {
10863:                 $hashref = $settings->{'instdata'};
10864:             }
10865:         } elsif ($context eq 'privacy') {
10866:             my ($key,$inner) = split(/_/,$role);
10867:             if (ref($settings) eq 'HASH') {
10868:                 if (ref($settings->{$key}) eq 'HASH') {
10869:                     $hashref = $settings->{$key}->{$inner};
10870:                 }
10871:             }
10872:         } elsif (ref($settings->{$context}) eq 'HASH') {
10873:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
10874:                 $hashref = $settings->{'lti_instdata'};
10875:             }
10876:             if ($role eq 'emailusername') {
10877:                 if ($statustype) {
10878:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
10879:                         $hashref = $settings->{$context}->{$role}->{$statustype};
10880:                     }
10881:                 }
10882:             }
10883:         }
10884:         if (ref($hashref) eq 'HASH') { 
10885:             foreach my $field (@fields) {
10886:                 if ($hashref->{$field}) {
10887:                     if ($role eq 'emailusername') {
10888:                         $checks{$field} = $hashref->{$field};
10889:                     } else {
10890:                         $checks{$field} = ' checked="checked" ';
10891:                     }
10892:                 }
10893:             }
10894:         }
10895:     }
10896:  
10897:     my $total = scalar(@fields);
10898:     for (my $i=0; $i<$total; $i++) {
10899:         $rem = $i%($numinrow);
10900:         if ($rem == 0) {
10901:             if ($i > 0) {
10902:                 $output .= '</tr>';
10903:             }
10904:             $output .= '<tr>';
10905:         }
10906:         my $check = ' ';
10907:         unless ($role eq 'emailusername') {
10908:             if (exists($checks{$fields[$i]})) {
10909:                 $check = $checks{$fields[$i]};
10910:             } elsif ($context eq 'privacy') {
10911:                 if ($role =~ /^priv_(domain|course)$/) {
10912:                     if (ref($settings) ne 'HASH') {
10913:                         $check = ' checked="checked" ';
10914:                     }
10915:                 } elsif ($role =~ /^priv_(author|community)$/) {
10916:                     if (ref($settings) ne 'HASH') {
10917:                         unless ($fields[$i] eq 'id') {
10918:                             $check = ' checked="checked" ';
10919:                         }
10920:                     }
10921:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
10922:                     if (ref($settings) ne 'HASH') {
10923:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
10924:                             $check = ' checked="checked" ';
10925:                         }
10926:                     }
10927:                 }
10928:             } elsif ($context ne 'lti') {
10929:                 if ($role eq 'st') {
10930:                     if (ref($settings) ne 'HASH') {
10931:                         $check = ' checked="checked" '; 
10932:                     }
10933:                 }
10934:             }
10935:         }
10936:         $output .= '<td class="LC_left_item">'.
10937:                    '<span class="LC_nobreak">';
10938:         my $prefix = 'canmodify';
10939:         if ($role eq 'emailusername') {
10940:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
10941:                 $checks{$fields[$i]} = 'omit';
10942:             }
10943:             foreach my $option ('required','optional','omit') {
10944:                 my $checked='';
10945:                 if ($checks{$fields[$i]} eq $option) {
10946:                     $checked='checked="checked" ';
10947:                 }
10948:                 $output .= '<label>'.
10949:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
10950:                            &mt($option).'</label>'.('&nbsp;' x2);
10951:             }
10952:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
10953:         } else {
10954:             if ($context eq 'lti') {
10955:                 $prefix = 'lti';
10956:             } elsif ($context eq 'privacy') {
10957:                 $prefix = 'privacy';
10958:             }
10959:             $output .= '<label>'.
10960:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
10961:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
10962:                        '</label>';
10963:         }
10964:         $output .= '</span></td>';
10965:     }
10966:     $rem = $total%$numinrow;
10967:     my $colsleft;
10968:     if ($rem) {
10969:         $colsleft = $numinrow - $rem;
10970:     }
10971:     if ($colsleft > 1) {
10972:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10973:                    '&nbsp;</td>';
10974:     } elsif ($colsleft == 1) {
10975:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10976:     }
10977:     $output .= '</tr></table></td></tr>';
10978:     return $output;
10979: }
10980: 
10981: sub insttypes_row {
10982:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
10983:         $customcss,$rowstyle) = @_;
10984:     my %lt = &Apache::lonlocal::texthash (
10985:                       cansearch => 'Users allowed to search',
10986:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
10987:                       lockablenames => 'User preference to lock name',
10988:                       selfassign    => 'Self-reportable affiliations',
10989:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
10990:              );
10991:     my $showdom;
10992:     if ($context eq 'cansearch') {
10993:         $showdom = ' ('.$dom.')';
10994:     }
10995:     my $class = 'LC_left_item';
10996:     if ($context eq 'statustocreate') {
10997:         $class = 'LC_right_item';
10998:     }
10999:     my $css_class;
11000:     if ($$rowtotal%2) {
11001:         $css_class = 'LC_odd_row';
11002:     }
11003:     if ($customcss) {
11004:         $css_class .= ' '.$customcss;
11005:     }
11006:     $css_class =~ s/^\s+//;
11007:     if ($css_class) {
11008:         $css_class = ' class="'.$css_class.'"';
11009:     }
11010:     if ($rowstyle) {
11011:         $css_class .= ' style="'.$rowstyle.'"';
11012:     }
11013:     if ($onclick) {
11014:         $onclick = 'onclick="'.$onclick.'" ';
11015:     }
11016:     my $output = '<tr'.$css_class.'>'.
11017:                  '<td>'.$lt{$context}.$showdom.
11018:                  '</td><td class="'.$class.'" colspan="2"><table>';
11019:     my $rem;
11020:     if (ref($types) eq 'ARRAY') {
11021:         for (my $i=0; $i<@{$types}; $i++) {
11022:             if (defined($usertypes->{$types->[$i]})) {
11023:                 my $rem = $i%($numinrow);
11024:                 if ($rem == 0) {
11025:                     if ($i > 0) {
11026:                         $output .= '</tr>';
11027:                     }
11028:                     $output .= '<tr>';
11029:                 }
11030:                 my $check = ' ';
11031:                 if (ref($settings) eq 'HASH') {
11032:                     if (ref($settings->{$context}) eq 'ARRAY') {
11033:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
11034:                             $check = ' checked="checked" ';
11035:                         }
11036:                     } elsif (ref($settings->{$context}) eq 'HASH') {
11037:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
11038:                             $check = ' checked="checked" ';
11039:                         }
11040:                     } elsif ($context eq 'statustocreate') {
11041:                         $check = ' checked="checked" ';
11042:                     }
11043:                 }
11044:                 $output .= '<td class="LC_left_item">'.
11045:                            '<span class="LC_nobreak"><label>'.
11046:                            '<input type="checkbox" name="'.$context.'" '.
11047:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
11048:                            $usertypes->{$types->[$i]}.'</label></span></td>';
11049:             }
11050:         }
11051:         $rem = @{$types}%($numinrow);
11052:     }
11053:     my $colsleft = $numinrow - $rem;
11054:     if ($context eq 'overrides') {
11055:         if ($colsleft > 1) {
11056:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11057:         } else {
11058:             $output .= '<td class="LC_left_item">';
11059:         }
11060:         $output .= '&nbsp;';  
11061:     } else {
11062:         if ($rem == 0) {
11063:             $output .= '<tr>';
11064:         }
11065:         if ($colsleft > 1) {
11066:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
11067:         } else {
11068:             $output .= '<td class="LC_left_item">';
11069:         }
11070:         my $defcheck = ' ';
11071:         if (ref($settings) eq 'HASH') {  
11072:             if (ref($settings->{$context}) eq 'ARRAY') {
11073:                 if (grep(/^default$/,@{$settings->{$context}})) {
11074:                     $defcheck = ' checked="checked" ';
11075:                 }
11076:             } elsif ($context eq 'statustocreate') {
11077:                 $defcheck = ' checked="checked" ';
11078:             }
11079:         }
11080:         $output .= '<span class="LC_nobreak"><label>'.
11081:                    '<input type="checkbox" name="'.$context.'" '.
11082:                    'value="default"'.$defcheck.$onclick.' />'.
11083:                    $othertitle.'</label></span>';
11084:     }
11085:     $output .= '</td></tr></table></td></tr>';
11086:     return $output;
11087: }
11088: 
11089: sub sorted_searchtitles {
11090:     my %searchtitles = &Apache::lonlocal::texthash(
11091:                          'uname' => 'username',
11092:                          'lastname' => 'last name',
11093:                          'lastfirst' => 'last name, first name',
11094:                      );
11095:     my @titleorder = ('uname','lastname','lastfirst');
11096:     return (\%searchtitles,\@titleorder);
11097: }
11098: 
11099: sub sorted_searchtypes {
11100:     my %srchtypes_desc = (
11101:                            exact    => 'is exact match',
11102:                            contains => 'contains ..',
11103:                            begins   => 'begins with ..',
11104:                          );
11105:     my @srchtypeorder = ('exact','begins','contains');
11106:     return (\%srchtypes_desc,\@srchtypeorder);
11107: }
11108: 
11109: sub usertype_update_row {
11110:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
11111:     my $datatable;
11112:     my $numinrow = 4;
11113:     foreach my $type (@{$types}) {
11114:         if (defined($usertypes->{$type})) {
11115:             $$rownums ++;
11116:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
11117:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
11118:                           '</td><td class="LC_left_item"><table>';
11119:             for (my $i=0; $i<@{$fields}; $i++) {
11120:                 my $rem = $i%($numinrow);
11121:                 if ($rem == 0) {
11122:                     if ($i > 0) {
11123:                         $datatable .= '</tr>';
11124:                     }
11125:                     $datatable .= '<tr>';
11126:                 }
11127:                 my $check = ' ';
11128:                 if (ref($settings) eq 'HASH') {
11129:                     if (ref($settings->{'fields'}) eq 'HASH') {
11130:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
11131:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
11132:                                 $check = ' checked="checked" ';
11133:                             }
11134:                         }
11135:                     }
11136:                 }
11137: 
11138:                 if ($i == @{$fields}-1) {
11139:                     my $colsleft = $numinrow - $rem;
11140:                     if ($colsleft > 1) {
11141:                         $datatable .= '<td colspan="'.$colsleft.'">';
11142:                     } else {
11143:                         $datatable .= '<td>';
11144:                     }
11145:                 } else {
11146:                     $datatable .= '<td>';
11147:                 }
11148:                 $datatable .= '<span class="LC_nobreak"><label>'.
11149:                               '<input type="checkbox" name="updateable_'.$type.
11150:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
11151:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
11152:             }
11153:             $datatable .= '</tr></table></td></tr>';
11154:         }
11155:     }
11156:     return $datatable;
11157: }
11158: 
11159: sub modify_login {
11160:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
11161:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
11162:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon);
11163:     %title = ( coursecatalog => 'Display course catalog',
11164:                adminmail => 'Display administrator E-mail address',
11165:                helpdesk  => 'Display "Contact Helpdesk" link',
11166:                newuser => 'Link for visitors to create a user account',
11167:                loginheader => 'Log-in box header');
11168:     @offon = ('off','on');
11169:     if (ref($domconfig{login}) eq 'HASH') {
11170:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
11171:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
11172:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
11173:             }
11174:         }
11175:     }
11176:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
11177:                                            \%domconfig,\%loginhash);
11178:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11179:     foreach my $item (@toggles) {
11180:         $loginhash{login}{$item} = $env{'form.'.$item};
11181:     }
11182:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
11183:     if (ref($colchanges{'login'}) eq 'HASH') {  
11184:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
11185:                                          \%loginhash);
11186:     }
11187: 
11188:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
11189:     my %domservers = &Apache::lonnet::get_servers($dom);
11190:     my @loginvia_attribs = ('serverpath','custompath','exempt');
11191:     if (keys(%servers) > 1) {
11192:         foreach my $lonhost (keys(%servers)) {
11193:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
11194:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
11195:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
11196:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
11197:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
11198:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11199:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11200:                         $changes{'loginvia'}{$lonhost} = 1;
11201:                     } else {
11202:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
11203:                         $changes{'loginvia'}{$lonhost} = 1;
11204:                     }
11205:                 } else {
11206:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11207:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11208:                         $changes{'loginvia'}{$lonhost} = 1;
11209:                     }
11210:                 }
11211:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
11212:                     foreach my $item (@loginvia_attribs) {
11213:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
11214:                     }
11215:                 } else {
11216:                     foreach my $item (@loginvia_attribs) {
11217:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11218:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11219:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
11220:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11221:                                 $new = '/';
11222:                             }
11223:                         }
11224:                         if (($item eq 'custompath') && 
11225:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11226:                             $new = '';
11227:                         }
11228:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
11229:                             $changes{'loginvia'}{$lonhost} = 1;
11230:                         }
11231:                         if ($item eq 'exempt') {
11232:                             $new = &check_exempt_addresses($new);
11233:                         }
11234:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11235:                     }
11236:                 }
11237:             } else {
11238:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
11239:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
11240:                     $changes{'loginvia'}{$lonhost} = 1;
11241:                     foreach my $item (@loginvia_attribs) {
11242:                         my $new = $env{'form.'.$lonhost.'_'.$item};
11243:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
11244:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
11245:                                 $new = '/';
11246:                             }
11247:                         }
11248:                         if (($item eq 'custompath') && 
11249:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
11250:                             $new = '';
11251:                         }
11252:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
11253:                     }
11254:                 }
11255:             }
11256:         }
11257:     }
11258: 
11259:     my $servadm = $r->dir_config('lonAdmEMail');
11260:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
11261:     if (ref($domconfig{'login'}) eq 'HASH') {
11262:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
11263:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
11264:                 if ($lang eq 'nolang') {
11265:                     push(@currlangs,$lang);
11266:                 } elsif (defined($langchoices{$lang})) {
11267:                     push(@currlangs,$lang);
11268:                 } else {
11269:                     next;
11270:                 }
11271:             }
11272:         }
11273:     }
11274:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
11275:     if (@currlangs > 0) {
11276:         foreach my $lang (@currlangs) {
11277:             if (grep(/^\Q$lang\E$/,@delurls)) {
11278:                 $changes{'helpurl'}{$lang} = 1;
11279:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
11280:                 $changes{'helpurl'}{$lang} = 1;
11281:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
11282:                 push(@newlangs,$lang);
11283:             } else {
11284:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11285:             }
11286:         }
11287:     }
11288:     unless (grep(/^nolang$/,@currlangs)) {
11289:         if ($env{'form.loginhelpurl_nolang.filename'}) {
11290:             $changes{'helpurl'}{'nolang'} = 1;
11291:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
11292:             push(@newlangs,'nolang');
11293:         }
11294:     }
11295:     if ($env{'form.loginhelpurl_add_lang'}) {
11296:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
11297:             ($env{'form.loginhelpurl_add_file.filename'})) {
11298:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
11299:             $addedfile = $env{'form.loginhelpurl_add_lang'};
11300:         }
11301:     }
11302:     if ((@newlangs > 0) || ($addedfile)) {
11303:         my $error;
11304:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11305:         if ($configuserok eq 'ok') {
11306:             if ($switchserver) {
11307:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
11308:             } elsif ($author_ok eq 'ok') {
11309:                 my @allnew = @newlangs;
11310:                 if ($addedfile ne '') {
11311:                     push(@allnew,$addedfile);
11312:                 }
11313:                 foreach my $lang (@allnew) {
11314:                     my $formelem = 'loginhelpurl_'.$lang;
11315:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
11316:                         $formelem = 'loginhelpurl_add_file';
11317:                     }
11318:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11319:                                                                "help/$lang",'','',$newfile{$lang});
11320:                     if ($result eq 'ok') {
11321:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
11322:                         $changes{'helpurl'}{$lang} = 1;
11323:                     } else {
11324:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
11325:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11326:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
11327:                             (!grep(/^\Q$lang\E$/,@delurls))) {
11328:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
11329:                         }
11330:                     }
11331:                 }
11332:             } else {
11333:                 $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);
11334:             }
11335:         } else {
11336:             $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);
11337:         }
11338:         if ($error) {
11339:             &Apache::lonnet::logthis($error);
11340:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11341:         }
11342:     }
11343: 
11344:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
11345:     if (ref($domconfig{'login'}) eq 'HASH') {
11346:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
11347:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
11348:                 if ($domservers{$lonhost}) {
11349:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11350:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
11351:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
11352:                     }
11353:                 }
11354:             }
11355:         }
11356:     }
11357:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
11358:     foreach my $lonhost (sort(keys(%domservers))) {
11359:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11360:             $changes{'headtag'}{$lonhost} = 1;
11361:         } else {
11362:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
11363:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
11364:             }
11365:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
11366:                 push(@newhosts,$lonhost);
11367:             } elsif ($currheadtagurls{$lonhost}) {
11368:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
11369:                 if ($currexempt{$lonhost}) {
11370:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
11371:                         $changes{'headtag'}{$lonhost} = 1;
11372:                     }
11373:                 } elsif ($possexempt{$lonhost}) {
11374:                     $changes{'headtag'}{$lonhost} = 1;
11375:                 }
11376:                 if ($possexempt{$lonhost}) {
11377:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11378:                 }
11379:             }
11380:         }
11381:     }
11382:     if (@newhosts) {
11383:         my $error;
11384:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
11385:         if ($configuserok eq 'ok') {
11386:             if ($switchserver) {
11387:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
11388:             } elsif ($author_ok eq 'ok') {
11389:                 foreach my $lonhost (@newhosts) {
11390:                     my $formelem = 'loginheadtag_'.$lonhost;
11391:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
11392:                                                                           "login/headtag/$lonhost",'','',
11393:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
11394:                     if ($result eq 'ok') {
11395:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
11396:                         $changes{'headtag'}{$lonhost} = 1;
11397:                         if ($possexempt{$lonhost}) {
11398:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
11399:                         }
11400:                     } else {
11401:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
11402:                                            $newheadtagurls{$lonhost},$result);
11403:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
11404:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
11405:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
11406:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
11407:                         }
11408:                     }
11409:                 }
11410:             } else {
11411:                 $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);
11412:             }
11413:         } else {
11414:             $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);
11415:         }
11416:         if ($error) {
11417:             &Apache::lonnet::logthis($error);
11418:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11419:         }
11420:     }
11421:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
11422: 
11423:     my $defaulthelpfile = '/adm/loginproblems.html';
11424:     my $defaulttext = &mt('Default in use');
11425: 
11426:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
11427:                                              $dom);
11428:     if ($putresult eq 'ok') {
11429:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
11430:         my %defaultchecked = (
11431:                     'coursecatalog' => 'on',
11432:                     'helpdesk'      => 'on',
11433:                     'adminmail'     => 'off',
11434:                     'newuser'       => 'off',
11435:         );
11436:         if (ref($domconfig{'login'}) eq 'HASH') {
11437:             foreach my $item (@toggles) {
11438:                 if ($defaultchecked{$item} eq 'on') { 
11439:                     if (($domconfig{'login'}{$item} eq '0') &&
11440:                         ($env{'form.'.$item} eq '1')) {
11441:                         $changes{$item} = 1;
11442:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11443:                               $domconfig{'login'}{$item} eq '1') &&
11444:                              ($env{'form.'.$item} eq '0')) {
11445:                         $changes{$item} = 1;
11446:                     }
11447:                 } elsif ($defaultchecked{$item} eq 'off') {
11448:                     if (($domconfig{'login'}{$item} eq '1') &&
11449:                         ($env{'form.'.$item} eq '0')) {
11450:                         $changes{$item} = 1;
11451:                     } elsif (($domconfig{'login'}{$item} eq '' ||
11452:                               $domconfig{'login'}{$item} eq '0') &&
11453:                              ($env{'form.'.$item} eq '1')) {
11454:                         $changes{$item} = 1;
11455:                     }
11456:                 }
11457:             }
11458:         }
11459:         if (keys(%changes) > 0 || $colchgtext) {
11460:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11461:             if (ref($lastactref) eq 'HASH') {
11462:                 $lastactref->{'domainconfig'} = 1;
11463:             }
11464:             $resulttext = &mt('Changes made:').'<ul>';
11465:             foreach my $item (sort(keys(%changes))) {
11466:                 if ($item eq 'loginvia') {
11467:                     if (ref($changes{$item}) eq 'HASH') {
11468:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
11469:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11470:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
11471:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
11472:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
11473:                                     $protocol = 'http' if ($protocol ne 'https');
11474:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
11475: 
11476:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
11477:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
11478:                                     } else {
11479:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
11480:                                     }
11481:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
11482:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
11483:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
11484:                                     }
11485:                                     $resulttext .= '</li>';
11486:                                 } else {
11487:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
11488:                                 }
11489:                             } else {
11490:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
11491:                             }
11492:                         }
11493:                         $resulttext .= '</ul></li>';
11494:                     }
11495:                 } elsif ($item eq 'helpurl') {
11496:                     if (ref($changes{$item}) eq 'HASH') {
11497:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
11498:                             if (grep(/^\Q$lang\E$/,@delurls)) {
11499:                                 my ($chg,$link);
11500:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
11501:                                 if ($lang eq 'nolang') {
11502:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
11503:                                 } else {
11504:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
11505:                                 }
11506:                                 $resulttext .= '<li>'.$chg.'</li>';
11507:                             } else {
11508:                                 my $chg;
11509:                                 if ($lang eq 'nolang') {
11510:                                     $chg = &mt('custom log-in help file for no preferred language');
11511:                                 } else {
11512:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
11513:                                 }
11514:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
11515:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
11516:                                                       '?inhibitmenu=yes',$chg,600,500).
11517:                                                '</li>';
11518:                             }
11519:                         }
11520:                     }
11521:                 } elsif ($item eq 'headtag') {
11522:                     if (ref($changes{$item}) eq 'HASH') {
11523:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
11524:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
11525:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
11526:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
11527:                                 $resulttext .= '<li><a href="'.
11528:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
11529:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
11530:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
11531:                                 if ($possexempt{$lonhost}) {
11532:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
11533:                                 } else {
11534:                                     $resulttext .= &mt('included for any client IP');
11535:                                 }
11536:                                 $resulttext .= '</li>';
11537:                             }
11538:                         }
11539:                     }
11540:                 } elsif ($item eq 'captcha') {
11541:                     if (ref($loginhash{'login'}) eq 'HASH') {
11542:                         my $chgtxt;
11543:                         if ($loginhash{'login'}{$item} eq 'notused') {
11544:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
11545:                         } else {
11546:                             my %captchas = &captcha_phrases();
11547:                             if ($captchas{$loginhash{'login'}{$item}}) {
11548:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
11549:                             } else {
11550:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
11551:                             }
11552:                         }
11553:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11554:                     }
11555:                 } elsif ($item eq 'recaptchakeys') {
11556:                     if (ref($loginhash{'login'}) eq 'HASH') {
11557:                         my ($privkey,$pubkey);
11558:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
11559:                             $pubkey = $loginhash{'login'}{$item}{'public'};
11560:                             $privkey = $loginhash{'login'}{$item}{'private'};
11561:                         }
11562:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
11563:                         if (!$pubkey) {
11564:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
11565:                         } else {
11566:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
11567:                         }
11568:                         if (!$privkey) {
11569:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
11570:                         } else {
11571:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
11572:                         }
11573:                         $chgtxt .= '</ul>';
11574:                         $resulttext .= '<li>'.$chgtxt.'</li>';
11575:                     }
11576:                 } elsif ($item eq 'recaptchaversion') {
11577:                     if (ref($loginhash{'login'}) eq 'HASH') {
11578:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
11579:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
11580:                                            '</li>';
11581:                         }
11582:                     }
11583:                 } else {
11584:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
11585:                 }
11586:             }
11587:             $resulttext .= $colchgtext.'</ul>';
11588:         } else {
11589:             $resulttext = &mt('No changes made to log-in page settings');
11590:         }
11591:     } else {
11592:         $resulttext = '<span class="LC_error">'.
11593: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11594:     }
11595:     if ($errors) {
11596:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
11597:                        $errors.'</ul>';
11598:     }
11599:     return $resulttext;
11600: }
11601: 
11602: sub check_exempt_addresses {
11603:     my ($iplist) = @_;
11604:     $iplist =~ s/^\s+//;
11605:     $iplist =~ s/\s+$//;
11606:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
11607:     my (@okips,$new);
11608:     foreach my $ip (@poss_ips) {
11609:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
11610:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
11611:                 push(@okips,$ip);
11612:             }
11613:         }
11614:     }
11615:     if (@okips > 0) {
11616:         $new = join(',',@okips);
11617:     } else {
11618:         $new = '';
11619:     }
11620:     return $new;
11621: }
11622: 
11623: sub color_font_choices {
11624:     my %choices =
11625:         &Apache::lonlocal::texthash (
11626:             img => "Header",
11627:             bgs => "Background colors",
11628:             links => "Link colors",
11629:             images => "Images",
11630:             font => "Font color",
11631:             fontmenu => "Font menu",
11632:             pgbg => "Page",
11633:             tabbg => "Header",
11634:             sidebg => "Border",
11635:             link => "Link",
11636:             alink => "Active link",
11637:             vlink => "Visited link",
11638:         );
11639:     return %choices;
11640: }
11641: 
11642: sub modify_rolecolors {
11643:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
11644:     my ($resulttext,%rolehash);
11645:     $rolehash{'rolecolors'} = {};
11646:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
11647:         if ($domconfig{'rolecolors'} eq '') {
11648:             $domconfig{'rolecolors'} = {};
11649:         }
11650:     }
11651:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
11652:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
11653:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
11654:                                              $dom);
11655:     if ($putresult eq 'ok') {
11656:         if (keys(%changes) > 0) {
11657:             &Apache::loncommon::devalidate_domconfig_cache($dom);
11658:             if (ref($lastactref) eq 'HASH') {
11659:                 $lastactref->{'domainconfig'} = 1;
11660:             }
11661:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
11662:                                              $rolehash{'rolecolors'});
11663:         } else {
11664:             $resulttext = &mt('No changes made to default color schemes');
11665:         }
11666:     } else {
11667:         $resulttext = '<span class="LC_error">'.
11668: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
11669:     }
11670:     if ($errors) {
11671:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
11672:                        $errors.'</ul>';
11673:     }
11674:     return $resulttext;
11675: }
11676: 
11677: sub modify_colors {
11678:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
11679:     my (%changes,%choices);
11680:     my @bgs;
11681:     my @links = ('link','alink','vlink');
11682:     my @logintext;
11683:     my @images;
11684:     my $servadm = $r->dir_config('lonAdmEMail');
11685:     my $errors;
11686:     my %defaults;
11687:     foreach my $role (@{$roles}) {
11688:         if ($role eq 'login') {
11689:             %choices = &login_choices();
11690:             @logintext = ('textcol','bgcol');
11691:         } else {
11692:             %choices = &color_font_choices();
11693:         }
11694:         if ($role eq 'login') {
11695:             @images = ('img','logo','domlogo','login');
11696:             @bgs = ('pgbg','mainbg','sidebg');
11697:         } else {
11698:             @images = ('img');
11699:             @bgs = ('pgbg','tabbg','sidebg');
11700:         }
11701:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
11702:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
11703:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
11704:         }
11705:         if ($role eq 'login') {
11706:             foreach my $item (@logintext) {
11707:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11708:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11709:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11710:                 }
11711:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
11712:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11713:                 }
11714:             }
11715:         } else {
11716:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
11717:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
11718:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
11719:             }
11720:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
11721:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
11722:             }
11723:         }
11724:         foreach my $item (@bgs) {
11725:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11726:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11727:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11728:             }
11729:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
11730:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11731:             }
11732:         }
11733:         foreach my $item (@links) {
11734:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
11735:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
11736:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
11737:             }
11738:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
11739:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
11740:             }
11741:         }
11742:         my ($configuserok,$author_ok,$switchserver) = 
11743:             &config_check($dom,$confname,$servadm);
11744:         my ($width,$height) = &thumb_dimensions();
11745:         if (ref($domconfig->{$role}) ne 'HASH') {
11746:             $domconfig->{$role} = {};
11747:         }
11748:         foreach my $img (@images) {
11749:             if (($role eq 'login') && (($img eq 'img') || ($img eq 'logo'))) {  
11750:                 if (defined($env{'form.login_showlogo_'.$img})) {
11751:                     $confhash->{$role}{'showlogo'}{$img} = 1;
11752:                 } else { 
11753:                     $confhash->{$role}{'showlogo'}{$img} = 0;
11754:                 }
11755:             } 
11756: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
11757: 		 && !defined($domconfig->{$role}{$img})
11758: 		 && !$env{'form.'.$role.'_del_'.$img}
11759: 		 && $env{'form.'.$role.'_import_'.$img}) {
11760: 		# import the old configured image from the .tab setting
11761: 		# if they haven't provided a new one 
11762: 		$domconfig->{$role}{$img} = 
11763: 		    $env{'form.'.$role.'_import_'.$img};
11764: 	    }
11765:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
11766:                 my $error;
11767:                 if ($configuserok eq 'ok') {
11768:                     if ($switchserver) {
11769:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
11770:                     } else {
11771:                         if ($author_ok eq 'ok') {
11772:                             my ($result,$logourl) = 
11773:                                 &publishlogo($r,'upload',$role.'_'.$img,
11774:                                            $dom,$confname,$img,$width,$height);
11775:                             if ($result eq 'ok') {
11776:                                 $confhash->{$role}{$img} = $logourl;
11777:                                 $changes{$role}{'images'}{$img} = 1;
11778:                             } else {
11779:                                 $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);
11780:                             }
11781:                         } else {
11782:                             $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);
11783:                         }
11784:                     }
11785:                 } else {
11786:                     $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);
11787:                 }
11788:                 if ($error) {
11789:                     &Apache::lonnet::logthis($error);
11790:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
11791:                 }
11792:             } elsif ($domconfig->{$role}{$img} ne '') {
11793:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
11794:                     my $error;
11795:                     if ($configuserok eq 'ok') {
11796: # is confname an author?
11797:                         if ($switchserver eq '') {
11798:                             if ($author_ok eq 'ok') {
11799:                                 my ($result,$logourl) = 
11800:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
11801:                                             $dom,$confname,$img,$width,$height);
11802:                                 if ($result eq 'ok') {
11803:                                     $confhash->{$role}{$img} = $logourl;
11804: 				    $changes{$role}{'images'}{$img} = 1;
11805:                                 }
11806:                             }
11807:                         }
11808:                     }
11809:                 }
11810:             }
11811:         }
11812:         if (ref($domconfig) eq 'HASH') {
11813:             if (ref($domconfig->{$role}) eq 'HASH') {
11814:                 foreach my $img (@images) {
11815:                     if ($domconfig->{$role}{$img} ne '') {
11816:                         if ($env{'form.'.$role.'_del_'.$img}) {
11817:                             $confhash->{$role}{$img} = '';
11818:                             $changes{$role}{'images'}{$img} = 1;
11819:                         } else {
11820:                             if ($confhash->{$role}{$img} eq '') {
11821:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
11822:                             }
11823:                         }
11824:                     } else {
11825:                         if ($env{'form.'.$role.'_del_'.$img}) {
11826:                             $confhash->{$role}{$img} = '';
11827:                             $changes{$role}{'images'}{$img} = 1;
11828:                         } 
11829:                     }
11830:                     if (($role eq 'login') && (($img eq 'logo') || ($img eq 'img'))) {
11831:                         if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
11832:                             if ($confhash->{$role}{'showlogo'}{$img} ne 
11833:                                 $domconfig->{$role}{'showlogo'}{$img}) {
11834:                                 $changes{$role}{'showlogo'}{$img} = 1; 
11835:                             }
11836:                         } else {
11837:                             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11838:                                 $changes{$role}{'showlogo'}{$img} = 1;
11839:                             }
11840:                         }
11841:                     }
11842:                 }
11843:                 if ($domconfig->{$role}{'font'} ne '') {
11844:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
11845:                         $changes{$role}{'font'} = 1;
11846:                     }
11847:                 } else {
11848:                     if ($confhash->{$role}{'font'}) {
11849:                         $changes{$role}{'font'} = 1;
11850:                     }
11851:                 }
11852:                 if ($role ne 'login') {
11853:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
11854:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
11855:                             $changes{$role}{'fontmenu'} = 1;
11856:                         }
11857:                     } else {
11858:                         if ($confhash->{$role}{'fontmenu'}) {
11859:                             $changes{$role}{'fontmenu'} = 1;
11860:                         }
11861:                     }
11862:                 }
11863:                 foreach my $item (@bgs) {
11864:                     if ($domconfig->{$role}{$item} ne '') {
11865:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11866:                             $changes{$role}{'bgs'}{$item} = 1;
11867:                         } 
11868:                     } else {
11869:                         if ($confhash->{$role}{$item}) {
11870:                             $changes{$role}{'bgs'}{$item} = 1;
11871:                         }
11872:                     }
11873:                 }
11874:                 foreach my $item (@links) {
11875:                     if ($domconfig->{$role}{$item} ne '') {
11876:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11877:                             $changes{$role}{'links'}{$item} = 1;
11878:                         }
11879:                     } else {
11880:                         if ($confhash->{$role}{$item}) {
11881:                             $changes{$role}{'links'}{$item} = 1;
11882:                         }
11883:                     }
11884:                 }
11885:                 foreach my $item (@logintext) {
11886:                     if ($domconfig->{$role}{$item} ne '') {
11887:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
11888:                             $changes{$role}{'logintext'}{$item} = 1;
11889:                         }
11890:                     } else {
11891:                         if ($confhash->{$role}{$item}) {
11892:                             $changes{$role}{'logintext'}{$item} = 1;
11893:                         }
11894:                     }
11895:                 }
11896:             } else {
11897:                 &default_change_checker($role,\@images,\@links,\@bgs,
11898:                                         \@logintext,$confhash,\%changes); 
11899:             }
11900:         } else {
11901:             &default_change_checker($role,\@images,\@links,\@bgs,
11902:                                     \@logintext,$confhash,\%changes); 
11903:         }
11904:     }
11905:     return ($errors,%changes);
11906: }
11907: 
11908: sub config_check {
11909:     my ($dom,$confname,$servadm) = @_;
11910:     my ($configuserok,$author_ok,$switchserver,%currroles);
11911:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
11912:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
11913:                                                    $confname,$servadm);
11914:     if ($configuserok eq 'ok') {
11915:         $switchserver = &check_switchserver($dom,$confname);
11916:         if ($switchserver eq '') {
11917:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
11918:         }
11919:     }
11920:     return ($configuserok,$author_ok,$switchserver);
11921: }
11922: 
11923: sub default_change_checker {
11924:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
11925:     foreach my $item (@{$links}) {
11926:         if ($confhash->{$role}{$item}) {
11927:             $changes->{$role}{'links'}{$item} = 1;
11928:         }
11929:     }
11930:     foreach my $item (@{$bgs}) {
11931:         if ($confhash->{$role}{$item}) {
11932:             $changes->{$role}{'bgs'}{$item} = 1;
11933:         }
11934:     }
11935:     foreach my $item (@{$logintext}) {
11936:         if ($confhash->{$role}{$item}) {
11937:             $changes->{$role}{'logintext'}{$item} = 1;
11938:         }
11939:     }
11940:     foreach my $img (@{$images}) {
11941:         if ($env{'form.'.$role.'_del_'.$img}) {
11942:             $confhash->{$role}{$img} = '';
11943:             $changes->{$role}{'images'}{$img} = 1;
11944:         }
11945:         if ($role eq 'login') {
11946:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
11947:                 $changes->{$role}{'showlogo'}{$img} = 1;
11948:             }
11949:         }
11950:     }
11951:     if ($confhash->{$role}{'font'}) {
11952:         $changes->{$role}{'font'} = 1;
11953:     }
11954: }
11955: 
11956: sub display_colorchgs {
11957:     my ($dom,$changes,$roles,$confhash) = @_;
11958:     my (%choices,$resulttext);
11959:     if (!grep(/^login$/,@{$roles})) {
11960:         $resulttext = &mt('Changes made:').'<br />';
11961:     }
11962:     foreach my $role (@{$roles}) {
11963:         if ($role eq 'login') {
11964:             %choices = &login_choices();
11965:         } else {
11966:             %choices = &color_font_choices();
11967:         }
11968:         if (ref($changes->{$role}) eq 'HASH') {
11969:             if ($role ne 'login') {
11970:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
11971:             }
11972:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
11973:                 if ($role ne 'login') {
11974:                     $resulttext .= '<ul>';
11975:                 }
11976:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
11977:                     if ($role ne 'login') {
11978:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
11979:                     }
11980:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
11981:                         if (($role eq 'login') && ($key eq 'showlogo')) {
11982:                             if ($confhash->{$role}{$key}{$item}) {
11983:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
11984:                             } else {
11985:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
11986:                             }
11987:                         } elsif ($confhash->{$role}{$item} eq '') {
11988:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
11989:                         } else {
11990:                             my $newitem = $confhash->{$role}{$item};
11991:                             if ($key eq 'images') {
11992:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
11993:                             }
11994:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
11995:                         }
11996:                     }
11997:                     if ($role ne 'login') {
11998:                         $resulttext .= '</ul></li>';
11999:                     }
12000:                 } else {
12001:                     if ($confhash->{$role}{$key} eq '') {
12002:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
12003:                     } else {
12004:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
12005:                     }
12006:                 }
12007:                 if ($role ne 'login') {
12008:                     $resulttext .= '</ul>';
12009:                 }
12010:             }
12011:         }
12012:     }
12013:     return $resulttext;
12014: }
12015: 
12016: sub thumb_dimensions {
12017:     return ('200','50');
12018: }
12019: 
12020: sub check_dimensions {
12021:     my ($inputfile) = @_;
12022:     my ($fullwidth,$fullheight);
12023:     if ($inputfile =~ m|^[/\w.\-]+$|) {
12024:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
12025:             my $imageinfo = <PIPE>;
12026:             if (!close(PIPE)) {
12027:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
12028:             }
12029:             chomp($imageinfo);
12030:             my ($fullsize) = 
12031:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
12032:             if ($fullsize) {
12033:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
12034:             }
12035:         }
12036:     }
12037:     return ($fullwidth,$fullheight);
12038: }
12039: 
12040: sub check_configuser {
12041:     my ($uhome,$dom,$confname,$servadm) = @_;
12042:     my ($configuserok,%currroles);
12043:     if ($uhome eq 'no_host') {
12044:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
12045:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
12046:         $configuserok = 
12047:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
12048:                              $configpass,'','','','','',undef,$servadm);
12049:     } else {
12050:         $configuserok = 'ok';
12051:         %currroles = 
12052:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
12053:     }
12054:     return ($configuserok,%currroles);
12055: }
12056: 
12057: sub check_authorstatus {
12058:     my ($dom,$confname,%currroles) = @_;
12059:     my $author_ok;
12060:     if (!$currroles{':'.$dom.':au'}) {
12061:         my $start = time;
12062:         my $end = 0;
12063:         $author_ok = 
12064:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
12065:                                         'au',$end,$start,'','','domconfig');
12066:     } else {
12067:         $author_ok = 'ok';
12068:     }
12069:     return $author_ok;
12070: }
12071: 
12072: sub publishlogo {
12073:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
12074:     my ($output,$fname,$logourl,$madethumb);
12075:     if ($action eq 'upload') {
12076:         $fname=$env{'form.'.$formname.'.filename'};
12077:         chop($env{'form.'.$formname});
12078:     } else {
12079:         ($fname) = ($formname =~ /([^\/]+)$/);
12080:     }
12081:     if ($savefileas ne '') {
12082:         $fname = $savefileas;
12083:     }
12084:     $fname=&Apache::lonnet::clean_filename($fname);
12085: # See if there is anything left
12086:     unless ($fname) { return ('error: no uploaded file'); }
12087:     $fname="$subdir/$fname";
12088:     my $docroot=$r->dir_config('lonDocRoot');
12089:     my $filepath="$docroot/priv";
12090:     my $relpath = "$dom/$confname";
12091:     my ($fnamepath,$file,$fetchthumb);
12092:     $file=$fname;
12093:     if ($fname=~m|/|) {
12094:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
12095:     }
12096:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
12097:     my $count;
12098:     for ($count=5;$count<=$#parts;$count++) {
12099:         $filepath.="/$parts[$count]";
12100:         if ((-e $filepath)!=1) {
12101:             mkdir($filepath,02770);
12102:         }
12103:     }
12104:     # Check for bad extension and disallow upload
12105:     if ($file=~/\.(\w+)$/ &&
12106:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
12107:         $output = 
12108:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
12109:     } elsif ($file=~/\.(\w+)$/ &&
12110:         !defined(&Apache::loncommon::fileembstyle($1))) {
12111:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
12112:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
12113:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
12114:     } elsif (-d "$filepath/$file") {
12115:         $output = &mt('Filename is a directory name - rename the file and re-upload');
12116:     } else {
12117:         my $source = $filepath.'/'.$file;
12118:         my $logfile;
12119:         if (!open($logfile,">>",$source.'.log')) {
12120:             return (&mt('No write permission to Authoring Space'));
12121:         }
12122:         print $logfile
12123: "\n================= Publish ".localtime()." ================\n".
12124: $env{'user.name'}.':'.$env{'user.domain'}."\n";
12125: # Save the file
12126:         if (!open(FH,">",$source)) {
12127:             &Apache::lonnet::logthis('Failed to create '.$source);
12128:             return (&mt('Failed to create file'));
12129:         }
12130:         if ($action eq 'upload') {
12131:             if (!print FH ($env{'form.'.$formname})) {
12132:                 &Apache::lonnet::logthis('Failed to write to '.$source);
12133:                 return (&mt('Failed to write file'));
12134:             }
12135:         } else {
12136:             my $original = &Apache::lonnet::filelocation('',$formname);
12137:             if(!copy($original,$source)) {
12138:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
12139:                 return (&mt('Failed to write file'));
12140:             }
12141:         }
12142:         close(FH);
12143:         chmod(0660, $source); # Permissions to rw-rw---.
12144: 
12145:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
12146:         my $copyfile=$targetdir.'/'.$file;
12147: 
12148:         my @parts=split(/\//,$targetdir);
12149:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
12150:         for (my $count=5;$count<=$#parts;$count++) {
12151:             $path.="/$parts[$count]";
12152:             if (!-e $path) {
12153:                 print $logfile "\nCreating directory ".$path;
12154:                 mkdir($path,02770);
12155:             }
12156:         }
12157:         my $versionresult;
12158:         if (-e $copyfile) {
12159:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
12160:         } else {
12161:             $versionresult = 'ok';
12162:         }
12163:         if ($versionresult eq 'ok') {
12164:             if (copy($source,$copyfile)) {
12165:                 print $logfile "\nCopied original source to ".$copyfile."\n";
12166:                 $output = 'ok';
12167:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
12168:                 push(@{$modified_urls},[$copyfile,$source]);
12169:                 my $metaoutput = 
12170:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
12171:                 unless ($registered_cleanup) {
12172:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12173:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12174:                     $registered_cleanup=1;
12175:                 }
12176:             } else {
12177:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
12178:                 $output = &mt('Failed to copy file to RES space').", $!";
12179:             }
12180:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
12181:                 my $inputfile = $filepath.'/'.$file;
12182:                 my $outfile = $filepath.'/'.'tn-'.$file;
12183:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
12184:                 if ($fullwidth ne '' && $fullheight ne '') { 
12185:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
12186:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
12187:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
12188:                         system({$args[0]} @args);
12189:                         chmod(0660, $filepath.'/tn-'.$file);
12190:                         if (-e $outfile) {
12191:                             my $copyfile=$targetdir.'/tn-'.$file;
12192:                             if (copy($outfile,$copyfile)) {
12193:                                 print $logfile "\nCopied source to ".$copyfile."\n";
12194:                                 my $thumb_metaoutput = 
12195:                                     &write_metadata($dom,$confname,$formname,
12196:                                                     $targetdir,'tn-'.$file,$logfile);
12197:                                 push(@{$modified_urls},[$copyfile,$outfile]);
12198:                                 unless ($registered_cleanup) {
12199:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
12200:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
12201:                                     $registered_cleanup=1;
12202:                                 }
12203:                                 $madethumb = 1;
12204:                             } else {
12205:                                 print $logfile "\nUnable to write ".$copyfile.
12206:                                                ':'.$!."\n";
12207:                             }
12208:                         }
12209:                     }
12210:                 }
12211:             }
12212:         } else {
12213:             $output = $versionresult;
12214:         }
12215:     }
12216:     return ($output,$logourl,$madethumb);
12217: }
12218: 
12219: sub logo_versioning {
12220:     my ($targetdir,$file,$logfile) = @_;
12221:     my $target = $targetdir.'/'.$file;
12222:     my ($maxversion,$fn,$extn,$output);
12223:     $maxversion = 0;
12224:     if ($file =~ /^(.+)\.(\w+)$/) {
12225:         $fn=$1;
12226:         $extn=$2;
12227:     }
12228:     opendir(DIR,$targetdir);
12229:     while (my $filename=readdir(DIR)) {
12230:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
12231:             $maxversion=($1>$maxversion)?$1:$maxversion;
12232:         }
12233:     }
12234:     $maxversion++;
12235:     print $logfile "\nCreating old version ".$maxversion."\n";
12236:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
12237:     if (copy($target,$copyfile)) {
12238:         print $logfile "Copied old target to ".$copyfile."\n";
12239:         $copyfile=$copyfile.'.meta';
12240:         if (copy($target.'.meta',$copyfile)) {
12241:             print $logfile "Copied old target metadata to ".$copyfile."\n";
12242:             $output = 'ok';
12243:         } else {
12244:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
12245:             $output = &mt('Failed to copy old meta').", $!, ";
12246:         }
12247:     } else {
12248:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
12249:         $output = &mt('Failed to copy old target').", $!, ";
12250:     }
12251:     return $output;
12252: }
12253: 
12254: sub write_metadata {
12255:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
12256:     my (%metadatafields,%metadatakeys,$output);
12257:     $metadatafields{'title'}=$formname;
12258:     $metadatafields{'creationdate'}=time;
12259:     $metadatafields{'lastrevisiondate'}=time;
12260:     $metadatafields{'copyright'}='public';
12261:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
12262:                                          $env{'user.domain'};
12263:     $metadatafields{'authorspace'}=$confname.':'.$dom;
12264:     $metadatafields{'domain'}=$dom;
12265:     {
12266:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
12267:         my $mfh;
12268:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
12269:             foreach (sort(keys(%metadatafields))) {
12270:                 unless ($_=~/\./) {
12271:                     my $unikey=$_;
12272:                     $unikey=~/^([A-Za-z]+)/;
12273:                     my $tag=$1;
12274:                     $tag=~tr/A-Z/a-z/;
12275:                     print $mfh "\n\<$tag";
12276:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
12277:                         my $value=$metadatafields{$unikey.'.'.$_};
12278:                         $value=~s/\"/\'\'/g;
12279:                         print $mfh ' '.$_.'="'.$value.'"';
12280:                     }
12281:                     print $mfh '>'.
12282:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
12283:                             .'</'.$tag.'>';
12284:                 }
12285:             }
12286:             $output = 'ok';
12287:             print $logfile "\nWrote metadata";
12288:             close($mfh);
12289:         } else {
12290:             print $logfile "\nFailed to open metadata file";
12291:             $output = &mt('Could not write metadata');
12292:         }
12293:     }
12294:     return $output;
12295: }
12296: 
12297: sub notifysubscribed {
12298:     foreach my $targetsource (@{$modified_urls}){
12299:         next unless (ref($targetsource) eq 'ARRAY');
12300:         my ($target,$source)=@{$targetsource};
12301:         if ($source ne '') {
12302:             if (open(my $logfh,">>",$source.'.log')) {
12303:                 print $logfh "\nCleanup phase: Notifications\n";
12304:                 my @subscribed=&subscribed_hosts($target);
12305:                 foreach my $subhost (@subscribed) {
12306:                     print $logfh "\nNotifying host ".$subhost.':';
12307:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
12308:                     print $logfh $reply;
12309:                 }
12310:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
12311:                 foreach my $subhost (@subscribedmeta) {
12312:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
12313:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
12314:                                                         $subhost);
12315:                     print $logfh $reply;
12316:                 }
12317:                 print $logfh "\n============ Done ============\n";
12318:                 close($logfh);
12319:             }
12320:         }
12321:     }
12322:     return OK;
12323: }
12324: 
12325: sub subscribed_hosts {
12326:     my ($target) = @_;
12327:     my @subscribed;
12328:     if (open(my $fh,"<","$target.subscription")) {
12329:         while (my $subline=<$fh>) {
12330:             if ($subline =~ /^($match_lonid):/) {
12331:                 my $host = $1;
12332:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
12333:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
12334:                         push(@subscribed,$host);
12335:                     }
12336:                 }
12337:             }
12338:         }
12339:     }
12340:     return @subscribed;
12341: }
12342: 
12343: sub check_switchserver {
12344:     my ($dom,$confname) = @_;
12345:     my ($allowed,$switchserver);
12346:     my $home = &Apache::lonnet::homeserver($confname,$dom);
12347:     if ($home eq 'no_host') {
12348:         $home = &Apache::lonnet::domain($dom,'primary');
12349:     }
12350:     my @ids=&Apache::lonnet::current_machine_ids();
12351:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
12352:     if (!$allowed) {
12353: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
12354:     }
12355:     return $switchserver;
12356: }
12357: 
12358: sub modify_quotas {
12359:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
12360:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
12361:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
12362:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
12363:         $validationfieldsref);
12364:     if ($action eq 'quotas') {
12365:         $context = 'tools'; 
12366:     } else {
12367:         $context = $action;
12368:     }
12369:     if ($context eq 'requestcourses') {
12370:         @usertools = ('official','unofficial','community','textbook','placement','lti');
12371:         @options =('norequest','approval','validate','autolimit');
12372:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
12373:         %titles = &courserequest_titles();
12374:         $toolregexp = join('|',@usertools);
12375:         %conditions = &courserequest_conditions();
12376:         $confname = $dom.'-domainconfig';
12377:         my $servadm = $r->dir_config('lonAdmEMail');
12378:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12379:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
12380:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
12381:     } elsif ($context eq 'requestauthor') {
12382:         @usertools = ('author');
12383:         %titles = &authorrequest_titles();
12384:     } else {
12385:         @usertools = ('aboutme','blog','webdav','portfolio');
12386:         %titles = &tool_titles();
12387:     }
12388:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
12389:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
12390:     foreach my $key (keys(%env)) {
12391:         if ($context eq 'requestcourses') {
12392:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
12393:                 my $item = $1;
12394:                 my $type = $2;
12395:                 if ($type =~ /^limit_(.+)/) {
12396:                     $limithash{$item}{$1} = $env{$key};
12397:                 } else {
12398:                     $confhash{$item}{$type} = $env{$key};
12399:                 }
12400:             }
12401:         } elsif ($context eq 'requestauthor') {
12402:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
12403:                 $confhash{$1} = $env{$key};
12404:             }
12405:         } else {
12406:             if ($key =~ /^form\.quota_(.+)$/) {
12407:                 $confhash{'defaultquota'}{$1} = $env{$key};
12408:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
12409:                 $confhash{'authorquota'}{$1} = $env{$key};
12410:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
12411:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
12412:             }
12413:         }
12414:     }
12415:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12416:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
12417:         @approvalnotify = sort(@approvalnotify);
12418:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
12419:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
12420:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
12421:         foreach my $type (@hasuniquecode) {
12422:             if (grep(/^\Q$type\E$/,@crstypes)) {
12423:                 $confhash{'uniquecode'}{$type} = 1;
12424:             }
12425:         }
12426:         my (%newbook,%allpos);
12427:         if ($context eq 'requestcourses') {
12428:             foreach my $type ('textbooks','templates') {
12429:                 @{$allpos{$type}} = (); 
12430:                 my $invalid;
12431:                 if ($type eq 'textbooks') {
12432:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
12433:                 } else {
12434:                     $invalid = &mt('Invalid LON-CAPA course for template');
12435:                 }
12436:                 if ($env{'form.'.$type.'_addbook'}) {
12437:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
12438:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
12439:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
12440:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
12441:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12442:                         } else {
12443:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
12444:                             my $position = $env{'form.'.$type.'_addbook_pos'};
12445:                             $position =~ s/\D+//g;
12446:                             if ($position ne '') {
12447:                                 $allpos{$type}[$position] = $newbook{$type};
12448:                             }
12449:                         }
12450:                     } else {
12451:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
12452:                     }
12453:                 }
12454:             } 
12455:         }
12456:         if (ref($domconfig{$action}) eq 'HASH') {
12457:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
12458:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
12459:                     $changes{'notify'}{'approval'} = 1;
12460:                 }
12461:             } else {
12462:                 if ($confhash{'notify'}{'approval'}) {
12463:                     $changes{'notify'}{'approval'} = 1;
12464:                 }
12465:             }
12466:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
12467:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
12468:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
12469:                         unless ($confhash{'uniquecode'}{$crstype}) {
12470:                             $changes{'uniquecode'} = 1;
12471:                         }
12472:                     }
12473:                     unless ($changes{'uniquecode'}) {
12474:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
12475:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
12476:                                 $changes{'uniquecode'} = 1;
12477:                             }
12478:                         }
12479:                     }
12480:                } else {
12481:                    $changes{'uniquecode'} = 1;
12482:                }
12483:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
12484:                 $changes{'uniquecode'} = 1;
12485:             }
12486:             if ($context eq 'requestcourses') {
12487:                 foreach my $type ('textbooks','templates') {
12488:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
12489:                         my %deletions;
12490:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
12491:                         if (@todelete) {
12492:                             map { $deletions{$_} = 1; } @todelete;
12493:                         }
12494:                         my %imgdeletions;
12495:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
12496:                         if (@todeleteimages) {
12497:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
12498:                         }
12499:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
12500:                         for (my $i=0; $i<=$maxnum; $i++) {
12501:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
12502:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
12503:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
12504:                                 if ($deletions{$key}) {
12505:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
12506:                                         #FIXME need to obsolete item in RES space
12507:                                     }
12508:                                     next;
12509:                                 } else {
12510:                                     my $newpos = $env{'form.'.$itemid};
12511:                                     $newpos =~ s/\D+//g;
12512:                                     foreach my $item ('subject','title','publisher','author') {
12513:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12514:                                                  ($type eq 'templates'));
12515:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
12516:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
12517:                                             $changes{$type}{$key} = 1;
12518:                                         }
12519:                                     }
12520:                                     $allpos{$type}[$newpos] = $key;
12521:                                 }
12522:                                 if ($imgdeletions{$key}) {
12523:                                     $changes{$type}{$key} = 1;
12524:                                     #FIXME need to obsolete item in RES space
12525:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
12526:                                     my ($cdom,$cnum) = split(/_/,$key);
12527:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12528:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12529:                                     } else {
12530:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
12531:                                                                                       $cdom,$cnum,$type,$configuserok,
12532:                                                                                       $switchserver,$author_ok);
12533:                                         if ($imgurl) {
12534:                                             $confhash{$type}{$key}{'image'} = $imgurl;
12535:                                             $changes{$type}{$key} = 1; 
12536:                                         }
12537:                                         if ($error) {
12538:                                             &Apache::lonnet::logthis($error);
12539:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12540:                                         }
12541:                                     }
12542:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
12543:                                     $confhash{$type}{$key}{'image'} = 
12544:                                         $domconfig{$action}{$type}{$key}{'image'};
12545:                                 }
12546:                             }
12547:                         }
12548:                     }
12549:                 }
12550:             }
12551:         } else {
12552:             if ($confhash{'notify'}{'approval'}) {
12553:                 $changes{'notify'}{'approval'} = 1;
12554:             }
12555:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
12556:                 $changes{'uniquecode'} = 1;
12557:             }
12558:         }
12559:         if ($context eq 'requestcourses') {
12560:             foreach my $type ('textbooks','templates') {
12561:                 if ($newbook{$type}) {
12562:                     $changes{$type}{$newbook{$type}} = 1;
12563:                     foreach my $item ('subject','title','publisher','author') {
12564:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
12565:                                  ($type eq 'template'));
12566:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
12567:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
12568:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
12569:                         }
12570:                     }
12571:                     if ($type eq 'textbooks') {
12572:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
12573:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
12574:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
12575:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
12576:                             } else {
12577:                                 my ($imageurl,$error) =
12578:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
12579:                                                             $configuserok,$switchserver,$author_ok);
12580:                                 if ($imageurl) {
12581:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
12582:                                 }
12583:                                 if ($error) {
12584:                                     &Apache::lonnet::logthis($error);
12585:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12586:                                 }
12587:                             }
12588:                         }
12589:                     }
12590:                 }
12591:                 if (@{$allpos{$type}} > 0) {
12592:                     my $idx = 0;
12593:                     foreach my $item (@{$allpos{$type}}) {
12594:                         if ($item ne '') {
12595:                             $confhash{$type}{$item}{'order'} = $idx;
12596:                             if (ref($domconfig{$action}) eq 'HASH') {
12597:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
12598:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
12599:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
12600:                                             $changes{$type}{$item} = 1;
12601:                                         }
12602:                                     }
12603:                                 }
12604:                             }
12605:                             $idx ++;
12606:                         }
12607:                     }
12608:                 }
12609:             }
12610:             if (ref($validationitemsref) eq 'ARRAY') {
12611:                 foreach my $item (@{$validationitemsref}) {
12612:                     if ($item eq 'fields') {
12613:                         my @changed;
12614:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
12615:                         if (@{$confhash{'validation'}{$item}} > 0) {
12616:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
12617:                         }
12618:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12619:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12620:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
12621:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
12622:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
12623:                                 } else {
12624:                                     @changed = @{$confhash{'validation'}{$item}};
12625:                                 }
12626:                             } else {
12627:                                 @changed = @{$confhash{'validation'}{$item}};
12628:                             }
12629:                         } else {
12630:                             @changed = @{$confhash{'validation'}{$item}};
12631:                         }
12632:                         if (@changed) {
12633:                             if ($confhash{'validation'}{$item}) {
12634:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
12635:                             } else {
12636:                                 $changes{'validation'}{$item} = &mt('None');
12637:                             }
12638:                         }
12639:                     } else {
12640:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
12641:                         if ($item eq 'markup') {
12642:                             if ($env{'form.requestcourses_validation_'.$item}) {
12643:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
12644:                             }
12645:                         }
12646:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12647:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12648:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
12649:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12650:                                 }
12651:                             } else {
12652:                                 if ($confhash{'validation'}{$item} ne '') {
12653:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12654:                                 }
12655:                             }
12656:                         } else {
12657:                             if ($confhash{'validation'}{$item} ne '') {
12658:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
12659:                             }
12660:                         }
12661:                     }
12662:                 }
12663:             }
12664:             if ($env{'form.validationdc'}) {
12665:                 my $newval = $env{'form.validationdc'};
12666:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
12667:                 if (exists($domcoords{$newval})) {
12668:                     $confhash{'validation'}{'dc'} = $newval;
12669:                 }
12670:             }
12671:             if (ref($confhash{'validation'}) eq 'HASH') {
12672:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12673:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12674:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
12675:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
12676:                                 if ($confhash{'validation'}{'dc'} eq '') {
12677:                                     $changes{'validation'}{'dc'} = &mt('None');
12678:                                 } else {
12679:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12680:                                 }
12681:                             }
12682:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
12683:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12684:                         }
12685:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
12686:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12687:                     }
12688:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
12689:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
12690:                 }
12691:             } else {
12692:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
12693:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
12694:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
12695:                             $changes{'validation'}{'dc'} = &mt('None');
12696:                         }
12697:                     }
12698:                 }
12699:             }
12700:         }
12701:     } else {
12702:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
12703:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
12704:     }
12705:     foreach my $item (@usertools) {
12706:         foreach my $type (@{$types},'default','_LC_adv') {
12707:             my $unset; 
12708:             if ($context eq 'requestcourses') {
12709:                 $unset = '0';
12710:                 if ($type eq '_LC_adv') {
12711:                     $unset = '';
12712:                 }
12713:                 if ($confhash{$item}{$type} eq 'autolimit') {
12714:                     $confhash{$item}{$type} .= '=';
12715:                     unless ($limithash{$item}{$type} =~ /\D/) {
12716:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
12717:                     }
12718:                 }
12719:             } elsif ($context eq 'requestauthor') {
12720:                 $unset = '0';
12721:                 if ($type eq '_LC_adv') {
12722:                     $unset = '';
12723:                 }
12724:             } else {
12725:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
12726:                     $confhash{$item}{$type} = 1;
12727:                 } else {
12728:                     $confhash{$item}{$type} = 0;
12729:                 }
12730:             }
12731:             if (ref($domconfig{$action}) eq 'HASH') {
12732:                 if ($action eq 'requestauthor') {
12733:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
12734:                         $changes{$type} = 1;
12735:                     }
12736:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
12737:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
12738:                         $changes{$item}{$type} = 1;
12739:                     }
12740:                 } else {
12741:                     if ($context eq 'requestcourses') {
12742:                         if ($confhash{$item}{$type} ne $unset) {
12743:                             $changes{$item}{$type} = 1;
12744:                         }
12745:                     } else {
12746:                         if (!$confhash{$item}{$type}) {
12747:                             $changes{$item}{$type} = 1;
12748:                         }
12749:                     }
12750:                 }
12751:             } else {
12752:                 if ($context eq 'requestcourses') {
12753:                     if ($confhash{$item}{$type} ne $unset) {
12754:                         $changes{$item}{$type} = 1;
12755:                     }
12756:                 } elsif ($context eq 'requestauthor') {
12757:                     if ($confhash{$type} ne $unset) {
12758:                         $changes{$type} = 1;
12759:                     }
12760:                 } else {
12761:                     if (!$confhash{$item}{$type}) {
12762:                         $changes{$item}{$type} = 1;
12763:                     }
12764:                 }
12765:             }
12766:         }
12767:     }
12768:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
12769:         if (ref($domconfig{'quotas'}) eq 'HASH') {
12770:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12771:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
12772:                     if (exists($confhash{'defaultquota'}{$key})) {
12773:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
12774:                             $changes{'defaultquota'}{$key} = 1;
12775:                         }
12776:                     } else {
12777:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
12778:                     }
12779:                 }
12780:             } else {
12781:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
12782:                     if (exists($confhash{'defaultquota'}{$key})) {
12783:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
12784:                             $changes{'defaultquota'}{$key} = 1;
12785:                         }
12786:                     } else {
12787:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
12788:                     }
12789:                 }
12790:             }
12791:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12792:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
12793:                     if (exists($confhash{'authorquota'}{$key})) {
12794:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
12795:                             $changes{'authorquota'}{$key} = 1;
12796:                         }
12797:                     } else {
12798:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
12799:                     }
12800:                 }
12801:             }
12802:         }
12803:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
12804:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
12805:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12806:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
12807:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
12808:                             $changes{'defaultquota'}{$key} = 1;
12809:                         }
12810:                     } else {
12811:                         if (!exists($domconfig{'quotas'}{$key})) {
12812:                             $changes{'defaultquota'}{$key} = 1;
12813:                         }
12814:                     }
12815:                 } else {
12816:                     $changes{'defaultquota'}{$key} = 1;
12817:                 }
12818:             }
12819:         }
12820:         if (ref($confhash{'authorquota'}) eq 'HASH') {
12821:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
12822:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
12823:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
12824:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
12825:                             $changes{'authorquota'}{$key} = 1;
12826:                         }
12827:                     } else {
12828:                         $changes{'authorquota'}{$key} = 1;
12829:                     }
12830:                 } else {
12831:                     $changes{'authorquota'}{$key} = 1;
12832:                 }
12833:             }
12834:         }
12835:     }
12836: 
12837:     if ($context eq 'requestauthor') {
12838:         $domdefaults{'requestauthor'} = \%confhash;
12839:     } else {
12840:         foreach my $key (keys(%confhash)) {
12841:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
12842:                 $domdefaults{$key} = $confhash{$key};
12843:             }
12844:         }
12845:     }
12846: 
12847:     my %quotahash = (
12848:                       $action => { %confhash }
12849:                     );
12850:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
12851:                                              $dom);
12852:     if ($putresult eq 'ok') {
12853:         if (keys(%changes) > 0) {
12854:             my $cachetime = 24*60*60;
12855:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
12856:             if (ref($lastactref) eq 'HASH') {
12857:                 $lastactref->{'domdefaults'} = 1;
12858:             }
12859:             $resulttext = &mt('Changes made:').'<ul>';
12860:             unless (($context eq 'requestcourses') ||
12861:                     ($context eq 'requestauthor')) {
12862:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
12863:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
12864:                     foreach my $type (@{$types},'default') {
12865:                         if (defined($changes{'defaultquota'}{$type})) {
12866:                             my $typetitle = $usertypes->{$type};
12867:                             if ($type eq 'default') {
12868:                                 $typetitle = $othertitle;
12869:                             }
12870:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
12871:                         }
12872:                     }
12873:                     $resulttext .= '</ul></li>';
12874:                 }
12875:                 if (ref($changes{'authorquota'}) eq 'HASH') {
12876:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
12877:                     foreach my $type (@{$types},'default') {
12878:                         if (defined($changes{'authorquota'}{$type})) {
12879:                             my $typetitle = $usertypes->{$type};
12880:                             if ($type eq 'default') {
12881:                                 $typetitle = $othertitle;
12882:                             }
12883:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
12884:                         }
12885:                     }
12886:                     $resulttext .= '</ul></li>';
12887:                 }
12888:             }
12889:             my %newenv;
12890:             foreach my $item (@usertools) {
12891:                 my (%haschgs,%inconf);
12892:                 if ($context eq 'requestauthor') {
12893:                     %haschgs = %changes;
12894:                     %inconf = %confhash;
12895:                 } else {
12896:                     if (ref($changes{$item}) eq 'HASH') {
12897:                         %haschgs = %{$changes{$item}};
12898:                     }
12899:                     if (ref($confhash{$item}) eq 'HASH') {
12900:                         %inconf = %{$confhash{$item}};
12901:                     }
12902:                 }
12903:                 if (keys(%haschgs) > 0) {
12904:                     my $newacc = 
12905:                         &Apache::lonnet::usertools_access($env{'user.name'},
12906:                                                           $env{'user.domain'},
12907:                                                           $item,'reload',$context);
12908:                     if (($context eq 'requestcourses') ||
12909:                         ($context eq 'requestauthor')) {
12910:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
12911:                             $newenv{'environment.canrequest.'.$item} = $newacc;
12912:                         }
12913:                     } else {
12914:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
12915:                             $newenv{'environment.availabletools.'.$item} = $newacc;
12916:                         }
12917:                     }
12918:                     unless ($context eq 'requestauthor') {
12919:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
12920:                     }
12921:                     foreach my $type (@{$types},'default','_LC_adv') {
12922:                         if ($haschgs{$type}) {
12923:                             my $typetitle = $usertypes->{$type};
12924:                             if ($type eq 'default') {
12925:                                 $typetitle = $othertitle;
12926:                             } elsif ($type eq '_LC_adv') {
12927:                                 $typetitle = 'LON-CAPA Advanced Users'; 
12928:                             }
12929:                             if ($inconf{$type}) {
12930:                                 if ($context eq 'requestcourses') {
12931:                                     my $cond;
12932:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
12933:                                         if ($1 eq '') {
12934:                                             $cond = &mt('(Automatic processing of any request).');
12935:                                         } else {
12936:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
12937:                                         }
12938:                                     } else { 
12939:                                         $cond = $conditions{$inconf{$type}};
12940:                                     }
12941:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
12942:                                 } elsif ($context eq 'requestauthor') {
12943:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
12944:                                                              $titles{$inconf{$type}},$typetitle);
12945: 
12946:                                 } else {
12947:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
12948:                                 }
12949:                             } else {
12950:                                 if ($type eq '_LC_adv') {
12951:                                     if ($inconf{$type} eq '0') {
12952:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12953:                                     } else { 
12954:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
12955:                                     }
12956:                                 } else {
12957:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
12958:                                 }
12959:                             }
12960:                         }
12961:                     }
12962:                     unless ($context eq 'requestauthor') {
12963:                         $resulttext .= '</ul></li>';
12964:                     }
12965:                 }
12966:             }
12967:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
12968:                 if (ref($changes{'notify'}) eq 'HASH') {
12969:                     if ($changes{'notify'}{'approval'}) {
12970:                         if (ref($confhash{'notify'}) eq 'HASH') {
12971:                             if ($confhash{'notify'}{'approval'}) {
12972:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
12973:                             } else {
12974:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
12975:                             }
12976:                         }
12977:                     }
12978:                 }
12979:             }
12980:             if ($action eq 'requestcourses') {
12981:                 my @offon = ('off','on');
12982:                 if ($changes{'uniquecode'}) {
12983:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
12984:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
12985:                         $resulttext .= '<li>'.
12986:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
12987:                                        '</li>';
12988:                     } else {
12989:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
12990:                                        '</li>';
12991:                     }
12992:                 }
12993:                 foreach my $type ('textbooks','templates') {
12994:                     if (ref($changes{$type}) eq 'HASH') {
12995:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
12996:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
12997:                             my %coursehash = &Apache::lonnet::coursedescription($key);
12998:                             my $coursetitle = $coursehash{'description'};
12999:                             my $position = $confhash{$type}{$key}{'order'} + 1;
13000:                             $resulttext .= '<li>';
13001:                             foreach my $item ('subject','title','publisher','author') {
13002:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
13003:                                          ($type eq 'templates'));
13004:                                 my $name = $item.':';
13005:                                 $name =~ s/^(\w)/\U$1/;
13006:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
13007:                             }
13008:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
13009:                             if ($type eq 'textbooks') {
13010:                                 if ($confhash{$type}{$key}{'image'}) {
13011:                                     $resulttext .= ' '.&mt('Image: [_1]',
13012:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
13013:                                                    ' alt="Textbook cover" />').'<br />';
13014:                                 }
13015:                             }
13016:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
13017:                         }
13018:                         $resulttext .= '</ul></li>';
13019:                     }
13020:                 }
13021:                 if (ref($changes{'validation'}) eq 'HASH') {
13022:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
13023:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
13024:                         foreach my $item (@{$validationitemsref}) {
13025:                             if (exists($changes{'validation'}{$item})) {
13026:                                 if ($item eq 'markup') {
13027:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13028:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
13029:                                 } else {
13030:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
13031:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
13032:                                 }
13033:                             }
13034:                         }
13035:                         if (exists($changes{'validation'}{'dc'})) {
13036:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
13037:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
13038:                         }
13039:                     }
13040:                 }
13041:             }
13042:             $resulttext .= '</ul>';
13043:             if (keys(%newenv)) {
13044:                 &Apache::lonnet::appenv(\%newenv);
13045:             }
13046:         } else {
13047:             if ($context eq 'requestcourses') {
13048:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
13049:             } elsif ($context eq 'requestauthor') {
13050:                 $resulttext = &mt('No changes made to rights to request author space.');
13051:             } else {
13052:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
13053:             }
13054:         }
13055:     } else {
13056:         $resulttext = '<span class="LC_error">'.
13057: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13058:     }
13059:     if ($errors) {
13060:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
13061:                        '<ul>'.$errors.'</ul></p>';
13062:     }
13063:     return $resulttext;
13064: }
13065: 
13066: sub process_textbook_image {
13067:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
13068:     my $filename = $env{'form.'.$caller.'.filename'};
13069:     my ($error,$url);
13070:     my ($width,$height) = (50,50);
13071:     if ($configuserok eq 'ok') {
13072:         if ($switchserver) {
13073:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
13074:                          $switchserver);
13075:         } elsif ($author_ok eq 'ok') {
13076:             my ($result,$imageurl) =
13077:                 &publishlogo($r,'upload',$caller,$dom,$confname,
13078:                              "$type/$cdom/$cnum/cover",$width,$height);
13079:             if ($result eq 'ok') {
13080:                 $url = $imageurl;
13081:             } else {
13082:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
13083:             }
13084:         } else {
13085:             $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);
13086:         }
13087:     } else {
13088:         $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);
13089:     }
13090:     return ($url,$error);
13091: }
13092: 
13093: sub modify_ltitools {
13094:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13095:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13096:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
13097:     my $confname = $dom.'-domainconfig';
13098:     my $servadm = $r->dir_config('lonAdmEMail');
13099:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13100:     my (%posslti,%possfield);
13101:     my @courseroles = ('cc','in','ta','ep','st');
13102:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
13103:     map { $posslti{$_} = 1; } @ltiroles;
13104:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
13105:     map { $possfield{$_} = 1; } @allfields;
13106:     my %lt = &ltitools_names(); 
13107:     if ($env{'form.ltitools_add'}) {
13108:         my $title = $env{'form.ltitools_add_title'};
13109:         $title =~ s/(`)/'/g;
13110:         ($newid,my $error) = &get_ltitools_id($dom,$title);
13111:         if ($newid) {
13112:             my $position = $env{'form.ltitools_add_pos'};
13113:             $position =~ s/\D+//g;
13114:             if ($position ne '') {
13115:                 $allpos[$position] = $newid;
13116:             }
13117:             $changes{$newid} = 1;
13118:             foreach my $item ('title','url','key','secret','lifetime') {
13119:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
13120:                 if ($item eq 'lifetime') {
13121:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
13122:                 }
13123:                 if ($env{'form.ltitools_add_'.$item}) {
13124:                     if (($item eq 'key') || ($item eq 'secret')) {
13125:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13126:                     } else {
13127:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
13128:                     }
13129:                 }
13130:             }
13131:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
13132:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
13133:             }
13134:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
13135:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
13136:             }
13137:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
13138:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
13139:             } else {
13140:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
13141:             }
13142:             foreach my $item ('width','height','linktext','explanation') {
13143:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
13144:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
13145:                 if (($item eq 'width') || ($item eq 'height')) {
13146:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
13147:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
13148:                     }
13149:                 } else {
13150:                     if ($env{'form.ltitools_add_'.$item} ne '') {
13151:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
13152:                     }
13153:                 }
13154:             }
13155:             if ($env{'form.ltitools_add_target'} eq 'window') {
13156:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13157:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
13158:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
13159:             } else {
13160:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
13161:             }
13162:             foreach my $item ('passback','roster') {
13163:                 if ($env{'form.ltitools_'.$item.'_add'}) {
13164:                     $confhash{$newid}{$item} = 1;
13165:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
13166:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
13167:                         $lifetime =~ s/^\s+|\s+$//g;
13168:                         if ($lifetime =~ /^\d+\.?\d*$/) {
13169:                             $confhash{$newid}{$item.'valid'} = $lifetime;
13170:                         }
13171:                     }
13172:                 }
13173:             }
13174:             if ($env{'form.ltitools_add_image.filename'} ne '') {
13175:                 my ($imageurl,$error) =
13176:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
13177:                                             $configuserok,$switchserver,$author_ok);
13178:                 if ($imageurl) {
13179:                     $confhash{$newid}{'image'} = $imageurl;
13180:                 }
13181:                 if ($error) {
13182:                     &Apache::lonnet::logthis($error);
13183:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13184:                 }
13185:             }
13186:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
13187:             foreach my $field (@fields) {
13188:                 if ($possfield{$field}) {
13189:                     if ($field eq 'roles') {
13190:                         foreach my $role (@courseroles) {
13191:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
13192:                             if (($choice ne '') && ($posslti{$choice})) {
13193:                                 $confhash{$newid}{'roles'}{$role} = $choice;
13194:                                 if ($role eq 'cc') {
13195:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
13196:                                 }
13197:                             }
13198:                         }
13199:                     } else {
13200:                         $confhash{$newid}{'fields'}{$field} = 1;
13201:                     }
13202:                 }
13203:             }
13204:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
13205:                 if ($confhash{$newid}{'fields'}{'user'}) {
13206:                     if ($env{'form.ltitools_userincdom_add'}) {
13207:                         $confhash{$newid}{'incdom'} = 1;
13208:                     }
13209:                 }
13210:             }
13211:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
13212:             foreach my $item (@courseconfig) {
13213:                 $confhash{$newid}{'crsconf'}{$item} = 1;
13214:             }
13215:             if ($env{'form.ltitools_add_custom'}) {
13216:                 my $name = $env{'form.ltitools_add_custom_name'};
13217:                 my $value = $env{'form.ltitools_add_custom_value'};
13218:                 $value =~ s/(`)/'/g;
13219:                 $name =~ s/(`)/'/g;
13220:                 $confhash{$newid}{'custom'}{$name} = $value;
13221:             }
13222:         } else {
13223:             my $error = &mt('Failed to acquire unique ID for new external tool');   
13224:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13225:         }
13226:     }
13227:     if (ref($domconfig{$action}) eq 'HASH') {
13228:         my %deletions;
13229:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
13230:         if (@todelete) {
13231:             map { $deletions{$_} = 1; } @todelete;
13232:         }
13233:         my %customadds;
13234:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
13235:         if (@newcustom) {
13236:             map { $customadds{$_} = 1; } @newcustom;
13237:         } 
13238:         my %imgdeletions;
13239:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
13240:         if (@todeleteimages) {
13241:             map { $imgdeletions{$_} = 1; } @todeleteimages;
13242:         }
13243:         my $maxnum = $env{'form.ltitools_maxnum'};
13244:         for (my $i=0; $i<=$maxnum; $i++) {
13245:             my $itemid = $env{'form.ltitools_id_'.$i};
13246:             $itemid =~ s/\D+//g;
13247:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13248:                 if ($deletions{$itemid}) {
13249:                     if ($domconfig{$action}{$itemid}{'image'}) {
13250:                         #FIXME need to obsolete item in RES space
13251:                     }
13252:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
13253:                     next;
13254:                 } else {
13255:                     my $newpos = $env{'form.ltitools_'.$itemid};
13256:                     $newpos =~ s/\D+//g;
13257:                     foreach my $item ('title','url','lifetime') {
13258:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13259:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
13260:                             $changes{$itemid} = 1;
13261:                         }
13262:                     }
13263:                     foreach my $item ('key','secret') {
13264:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13265:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
13266:                             $changes{$itemid} = 1;
13267:                         }
13268:                     }
13269:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
13270:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
13271:                     }
13272:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
13273:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
13274:                     }
13275:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
13276:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
13277:                     } else {
13278:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
13279:                     }
13280:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
13281:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
13282:                             $changes{$itemid} = 1;
13283:                         }
13284:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
13285:                         $changes{$itemid} = 1;
13286:                     }
13287:                     foreach my $size ('width','height') {
13288:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
13289:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
13290:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
13291:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
13292:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13293:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
13294:                                     $changes{$itemid} = 1;
13295:                                 }
13296:                             } else {
13297:                                 $changes{$itemid} = 1;
13298:                             }
13299:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13300:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
13301:                                 $changes{$itemid} = 1;
13302:                             }
13303:                         }
13304:                     }
13305:                     foreach my $item ('linktext','explanation') {
13306:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
13307:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
13308:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
13309:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
13310:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13311:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
13312:                                     $changes{$itemid} = 1;
13313:                                 }
13314:                             } else {
13315:                                 $changes{$itemid} = 1;
13316:                             }
13317:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13318:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
13319:                                 $changes{$itemid} = 1;
13320:                             }
13321:                         }
13322:                     }
13323:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
13324:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13325:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
13326:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
13327:                     } else {
13328:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
13329:                     }
13330:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
13331:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
13332:                             $changes{$itemid} = 1;
13333:                         }
13334:                     } else {
13335:                         $changes{$itemid} = 1;
13336:                     }
13337:                     foreach my $extra ('passback','roster') {
13338:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
13339:                             $confhash{$itemid}{$extra} = 1;
13340:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
13341:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
13342:                                 $lifetime =~ s/^\s+|\s+$//g;
13343:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
13344:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
13345:                                 }
13346:                             }
13347:                         }
13348:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
13349:                             $changes{$itemid} = 1;
13350:                         }
13351:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
13352:                             $changes{$itemid} = 1;
13353:                         }
13354:                     }
13355:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
13356:                     foreach my $item ('label','title','target','linktext','explanation','append') {
13357:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
13358:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
13359:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
13360:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
13361:                                     $changes{$itemid} = 1;
13362:                                 }
13363:                             } else {
13364:                                 $changes{$itemid} = 1;
13365:                             }
13366:                         }
13367:                     }
13368:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
13369:                     foreach my $field (@fields) {
13370:                         if ($possfield{$field}) {
13371:                             if ($field eq 'roles') {
13372:                                 foreach my $role (@courseroles) {
13373:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
13374:                                     if (($choice ne '') && ($posslti{$choice})) {
13375:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
13376:                                         if ($role eq 'cc') {
13377:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
13378:                                         }
13379:                                     }
13380:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
13381:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
13382:                                             $changes{$itemid} = 1;
13383:                                         }
13384:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
13385:                                         $changes{$itemid} = 1;
13386:                                     }
13387:                                 }
13388:                             } else {
13389:                                 $confhash{$itemid}{'fields'}{$field} = 1;
13390:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
13391:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
13392:                                         $changes{$itemid} = 1;
13393:                                     }
13394:                                 } else {
13395:                                     $changes{$itemid} = 1;
13396:                                 }
13397:                             }
13398:                         }
13399:                     }
13400:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
13401:                         if ($confhash{$itemid}{'fields'}{'user'}) {
13402:                             if ($env{'form.ltitools_userincdom_'.$i}) {
13403:                                 $confhash{$itemid}{'incdom'} = 1;
13404:                             }
13405:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
13406:                                 $changes{$itemid} = 1;
13407:                             }
13408:                         }
13409:                     }
13410:                     $allpos[$newpos] = $itemid;
13411:                 }
13412:                 if ($imgdeletions{$itemid}) {
13413:                     $changes{$itemid} = 1;
13414:                     #FIXME need to obsolete item in RES space
13415:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
13416:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
13417:                                                                  $itemid,$configuserok,$switchserver,
13418:                                                                  $author_ok);
13419:                     if ($imgurl) {
13420:                         $confhash{$itemid}{'image'} = $imgurl;
13421:                         $changes{$itemid} = 1;
13422:                     }
13423:                     if ($error) {
13424:                         &Apache::lonnet::logthis($error);
13425:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13426:                     }
13427:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
13428:                     $confhash{$itemid}{'image'} =
13429:                        $domconfig{$action}{$itemid}{'image'};
13430:                 }
13431:                 if ($customadds{$i}) {
13432:                     my $name = $env{'form.ltitools_custom_name_'.$i};
13433:                     $name =~ s/(`)/'/g;
13434:                     $name =~ s/^\s+//;
13435:                     $name =~ s/\s+$//;
13436:                     my $value = $env{'form.ltitools_custom_value_'.$i};
13437:                     $value =~ s/(`)/'/g;
13438:                     $value =~ s/^\s+//;
13439:                     $value =~ s/\s+$//;
13440:                     if ($name ne '') {
13441:                         $confhash{$itemid}{'custom'}{$name} = $value;
13442:                         $changes{$itemid} = 1;
13443:                     }
13444:                 }
13445:                 my %customdels;
13446:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
13447:                 if (@customdeletions) {
13448:                     $changes{$itemid} = 1;
13449:                 }
13450:                 map { $customdels{$_} = 1; } @customdeletions;
13451:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
13452:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
13453:                         unless ($customdels{$key}) {
13454:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
13455:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
13456:                             }
13457:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
13458:                                 $changes{$itemid} = 1;
13459:                             }
13460:                         }
13461:                     }
13462:                 }
13463:                 unless ($changes{$itemid}) {
13464:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
13465:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
13466:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
13467:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
13468:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
13469:                                         $changes{$itemid} = 1;
13470:                                         last;
13471:                                     }
13472:                                 }
13473:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
13474:                                 $changes{$itemid} = 1;
13475:                             }
13476:                         }
13477:                         last if ($changes{$itemid});
13478:                     }
13479:                 }
13480:             }
13481:         }
13482:     }
13483:     if (@allpos > 0) {
13484:         my $idx = 0;
13485:         foreach my $itemid (@allpos) {
13486:             if ($itemid ne '') {
13487:                 $confhash{$itemid}{'order'} = $idx;
13488:                 if (ref($domconfig{$action}) eq 'HASH') {
13489:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
13490:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
13491:                             $changes{$itemid} = 1;
13492:                         }
13493:                     }
13494:                 }
13495:                 $idx ++;
13496:             }
13497:         }
13498:     }
13499:     my %ltitoolshash = (
13500:                           $action => { %confhash }
13501:                        );
13502:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
13503:                                              $dom);
13504:     if ($putresult eq 'ok') {
13505:         my %ltienchash = (
13506:                              $action => { %encconfig }
13507:                          );
13508:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
13509:         if (keys(%changes) > 0) {
13510:             my $cachetime = 24*60*60;
13511:             my %ltiall = %confhash;
13512:             foreach my $id (keys(%ltiall)) {
13513:                 if (ref($encconfig{$id}) eq 'HASH') {
13514:                     foreach my $item ('key','secret') {
13515:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
13516:                     }
13517:                 }
13518:             }
13519:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
13520:             if (ref($lastactref) eq 'HASH') {
13521:                 $lastactref->{'ltitools'} = 1;
13522:             }
13523:             $resulttext = &mt('Changes made:').'<ul>';
13524:             my %bynum;
13525:             foreach my $itemid (sort(keys(%changes))) {
13526:                 my $position = $confhash{$itemid}{'order'};
13527:                 $bynum{$position} = $itemid;
13528:             }
13529:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13530:                 my $itemid = $bynum{$pos}; 
13531:                 if (ref($confhash{$itemid}) ne 'HASH') {
13532:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13533:                 } else {
13534:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
13535:                     if ($confhash{$itemid}{'image'}) {
13536:                         $resulttext .= '&nbsp;'.
13537:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
13538:                                        ' alt="'.&mt('Tool Provider icon').'" />';
13539:                     }
13540:                     $resulttext .= '</li><ul>';
13541:                     my $position = $pos + 1;
13542:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13543:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
13544:                         if ($confhash{$itemid}{$item} ne '') {
13545:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
13546:                         }
13547:                     }
13548:                     if ($encconfig{$itemid}{'key'} ne '') {
13549:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
13550:                     }
13551:                     if ($encconfig{$itemid}{'secret'} ne '') {
13552:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
13553:                         my $num = length($encconfig{$itemid}{'secret'});
13554:                         $resulttext .= ('*'x$num).'</li>';
13555:                     }
13556:                     $resulttext .= '<li>'.&mt('Configurable in course:');
13557:                     my @possconfig = ('label','title','target','linktext','explanation','append');
13558:                     my $numconfig = 0; 
13559:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
13560:                         foreach my $item (@possconfig) {
13561:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
13562:                                 $numconfig ++;
13563:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
13564:                             }
13565:                         }
13566:                     }
13567:                     if (!$numconfig) {
13568:                         $resulttext .= '&nbsp;'.&mt('None');
13569:                     }
13570:                     $resulttext .= '</li>';
13571:                     foreach my $item ('passback','roster') {
13572:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
13573:                         if ($confhash{$itemid}{$item}) {
13574:                             $resulttext .= &mt('Yes');
13575:                             if ($confhash{$itemid}{$item.'valid'}) {
13576:                                 if ($item eq 'passback') {
13577:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
13578:                                                            $confhash{$itemid}{$item.'valid'});
13579:                                 } else {
13580:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
13581:                                                            $confhash{$itemid}{$item.'valid'});
13582:                                 }
13583:                             }
13584:                         } else {
13585:                             $resulttext .= &mt('No');
13586:                         }
13587:                         $resulttext .= '</li>';
13588:                     }
13589:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
13590:                         my $displaylist;
13591:                         if ($confhash{$itemid}{'display'}{'target'}) {
13592:                             $displaylist = &mt('Display target').':&nbsp;'.
13593:                                            $confhash{$itemid}{'display'}{'target'}.',';
13594:                         }
13595:                         foreach my $size ('width','height') { 
13596:                             if ($confhash{$itemid}{'display'}{$size}) {
13597:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
13598:                                                 $confhash{$itemid}{'display'}{$size}.',';
13599:                             }
13600:                         }
13601:                         if ($displaylist) {
13602:                             $displaylist =~ s/,$//;
13603:                             $resulttext .= '<li>'.$displaylist.'</li>';
13604:                         }
13605:                         foreach my $item ('linktext','explanation') {
13606:                             if ($confhash{$itemid}{'display'}{$item}) {
13607:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
13608:                             }
13609:                         }
13610:                     }
13611:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
13612:                         my $fieldlist;
13613:                         foreach my $field (@allfields) {
13614:                             if ($confhash{$itemid}{'fields'}{$field}) {
13615:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
13616:                             }
13617:                         }
13618:                         if ($fieldlist) {
13619:                             $fieldlist =~ s/,$//;
13620:                             if ($confhash{$itemid}{'fields'}{'user'}) {
13621:                                 if ($confhash{$itemid}{'incdom'}) {
13622:                                     $fieldlist .= ' ('.&mt('username:domain').')';
13623:                                 } else {
13624:                                     $fieldlist .= ' ('.&mt('username').')';
13625:                                 }
13626:                             }
13627:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
13628:                         }
13629:                     }
13630:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
13631:                         my $rolemaps;
13632:                         foreach my $role (@courseroles) {
13633:                             if ($confhash{$itemid}{'roles'}{$role}) {
13634:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
13635:                                              $confhash{$itemid}{'roles'}{$role}.',';
13636:                             }
13637:                         }
13638:                         if ($rolemaps) {
13639:                             $rolemaps =~ s/,$//; 
13640:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
13641:                         }
13642:                     }
13643:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
13644:                         my $customlist;
13645:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
13646:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
13647:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
13648:                             } 
13649:                         }
13650:                         if ($customlist) {
13651:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
13652:                         }
13653:                     } 
13654:                     $resulttext .= '</ul></li>';
13655:                 }
13656:             }
13657:             $resulttext .= '</ul>';
13658:         } else {
13659:             $resulttext = &mt('No changes made.');
13660:         }
13661:     } else {
13662:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13663:     }
13664:     if ($errors) {
13665:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13666:                        $errors.'</ul>';
13667:     }
13668:     return $resulttext;
13669: }
13670: 
13671: sub process_ltitools_image {
13672:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
13673:     my $filename = $env{'form.'.$caller.'.filename'};
13674:     my ($error,$url);
13675:     my ($width,$height) = (21,21);
13676:     if ($configuserok eq 'ok') {
13677:         if ($switchserver) {
13678:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
13679:                          $switchserver);
13680:         } elsif ($author_ok eq 'ok') {
13681:             my ($result,$imageurl,$madethumb) =
13682:                 &publishlogo($r,'upload',$caller,$dom,$confname,
13683:                              "ltitools/$itemid/icon",$width,$height);
13684:             if ($result eq 'ok') {
13685:                 if ($madethumb) {
13686:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
13687:                     my $imagethumb = "$path/tn-".$imagefile;
13688:                     $url = $imagethumb;
13689:                 } else {
13690:                     $url = $imageurl;
13691:                 }
13692:             } else {
13693:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
13694:             }
13695:         } else {
13696:             $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);
13697:         }
13698:     } else {
13699:         $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);
13700:     }
13701:     return ($url,$error);
13702: }
13703: 
13704: sub get_ltitools_id {
13705:     my ($cdom,$title) = @_;
13706:     # get lock on ltitools db
13707:     my $lockhash = {
13708:                       lock => $env{'user.name'}.
13709:                               ':'.$env{'user.domain'},
13710:                    };
13711:     my $tries = 0;
13712:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
13713:     my ($id,$error);
13714:  
13715:     while (($gotlock ne 'ok') && ($tries<10)) {
13716:         $tries ++;
13717:         sleep (0.1);
13718:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
13719:     }
13720:     if ($gotlock eq 'ok') {
13721:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
13722:         if ($currids{'lock'}) {
13723:             delete($currids{'lock'});
13724:             if (keys(%currids)) {
13725:                 my @curr = sort { $a <=> $b } keys(%currids);
13726:                 if ($curr[-1] =~ /^\d+$/) {
13727:                     $id = 1 + $curr[-1];
13728:                 }
13729:             } else {
13730:                 $id = 1;
13731:             }
13732:             if ($id) {
13733:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
13734:                     $error = 'nostore';
13735:                 }
13736:             } else {
13737:                 $error = 'nonumber';
13738:             }
13739:         }
13740:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
13741:     } else {
13742:         $error = 'nolock';
13743:     }
13744:     return ($id,$error);
13745: }
13746: 
13747: sub modify_proctoring {
13748:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13749:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13750:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
13751:     my $confname = $dom.'-domainconfig';
13752:     my $servadm = $r->dir_config('lonAdmEMail');
13753:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13754:     my %providernames = &proctoring_providernames();
13755:     my $maxnum = scalar(keys(%providernames));
13756: 
13757:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
13758:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
13759:     if (ref($requref) eq 'HASH') {
13760:         %requserfields = %{$requref};
13761:     }
13762:     if (ref($opturef) eq 'HASH') {
13763:         %optuserfields = %{$opturef};
13764:     }
13765:     if (ref($defref) eq 'HASH') {
13766:         %defaults = %{$defref};
13767:     }
13768:     if (ref($extref) eq 'HASH') {
13769:         %extended = %{$extref};
13770:     }
13771:     if (ref($crsref) eq 'HASH') {
13772:         %crsconf = %{$crsref};
13773:     }
13774:     if (ref($rolesref) eq 'ARRAY') {
13775:         @courseroles = @{$rolesref};
13776:     }
13777:     if (ref($ltiref) eq 'ARRAY') {
13778:         @ltiroles = @{$ltiref};
13779:     }
13780: 
13781:     if (ref($domconfig{$action}) eq 'HASH') {
13782:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
13783:         if (@todeleteimages) {
13784:             map { $imgdeletions{$_} = 1; } @todeleteimages;
13785:         }
13786:     }
13787:     my %customadds;
13788:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
13789:     if (@newcustom) {
13790:         map { $customadds{$_} = 1; } @newcustom;
13791:     }
13792:     foreach my $provider (sort(keys(%providernames))) {
13793:         $confhash{$provider} = {};
13794:         my $pos = $env{'form.proctoring_pos_'.$provider};
13795:         $pos =~ s/\D+//g;
13796:         $allpos[$pos] = $provider;
13797:         my (%current,%currentenc);
13798:         my $showroles = 0;
13799:         if (ref($domconfig{$action}) eq 'HASH') {
13800:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
13801:                 %current = %{$domconfig{$action}{$provider}};
13802:                 foreach my $item ('key','secret') { 
13803:                     $currentenc{$item} = $current{$item};
13804:                     delete($current{$item});
13805:                 }
13806:             }
13807:         }
13808:         if ($env{'form.proctoring_available_'.$provider}) {
13809:             $confhash{$provider}{'available'} = 1;
13810:             unless ($current{'available'}) {
13811:                 $changes{$provider} = 1;
13812:             }
13813:         } else {
13814:             %{$confhash{$provider}} = %current;
13815:             %{$encconfhash{$provider}} = %currentenc;
13816:             $confhash{$provider}{'available'} = 0;
13817:             if ($current{'available'}) {
13818:                 $changes{$provider} = 1;
13819:             }
13820:         }
13821:         if ($confhash{$provider}{'available'}) {
13822:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
13823:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
13824:                 if ($field eq 'lifetime') {
13825:                     if ($possval =~ /^\d+$/) {
13826:                         $confhash{$provider}{$field} = $possval;
13827:                     }
13828:                 } elsif ($field eq 'version') {
13829:                     if ($possval =~ /^\d+\.\d+$/) {
13830:                         $confhash{$provider}{$field} = $possval;
13831:                     }
13832:                 } elsif ($field eq 'sigmethod') {
13833:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
13834:                         $confhash{$provider}{$field} = $possval;
13835:                     }
13836:                 } elsif ($field eq 'url') {
13837:                     $confhash{$provider}{$field} = $possval;
13838:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
13839:                     $encconfhash{$provider}{$field} = $possval;
13840:                     unless ($currentenc{$field} eq $possval) {
13841:                         $changes{$provider} = 1;
13842:                     }
13843:                 }
13844:                 unless (($field eq 'key') || ($field eq 'secret')) {
13845:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
13846:                         $changes{$provider} = 1;
13847:                     }
13848:                 }
13849:             }
13850:             if ($imgdeletions{$provider}) {
13851:                 $changes{$provider} = 1;
13852:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
13853:                 my ($imageurl,$error) =
13854:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
13855:                                               $configuserok,$switchserver,$author_ok);
13856:                 if ($imageurl) {
13857:                     $confhash{$provider}{'image'} = $imageurl;
13858:                     $changes{$provider} = 1; 
13859:                 }
13860:                 if ($error) {
13861:                     &Apache::lonnet::logthis($error);
13862:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13863:                 }
13864:             } elsif (exists($current{'image'})) {
13865:                 $confhash{$provider}{'image'} = $current{'image'};
13866:             }
13867:             if (ref($requserfields{$provider}) eq 'ARRAY') {
13868:                 if (@{$requserfields{$provider}} > 0) {
13869:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
13870:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
13871:                             $confhash{$provider}{'incdom'} = 1;
13872:                         }
13873:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
13874:                             $changes{$provider} = 1;
13875:                         }
13876:                     }
13877:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
13878:                         $showroles = 1;
13879:                     }
13880:                 }
13881:             }
13882:             $confhash{$provider}{'fields'} = [];
13883:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
13884:                 if (@{$optuserfields{$provider}} > 0) {
13885:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
13886:                     foreach my $field (@{$optuserfields{$provider}}) {
13887:                         if (grep(/^\Q$field\E$/,@optfields)) {
13888:                             push(@{$confhash{$provider}{'fields'}},$field);
13889:                         }
13890:                     }
13891:                 }
13892:                 if (ref($current{'fields'}) eq 'ARRAY') {
13893:                     unless ($changes{$provider}) {
13894:                         my @new = sort(@{$confhash{$provider}{'fields'}});
13895:                         my @old = sort(@{$current{'fields'}}); 
13896:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
13897:                         if (@diffs) {
13898:                             $changes{$provider} = 1;
13899:                         }
13900:                     }
13901:                 } elsif (@{$confhash{$provider}{'fields'}}) {
13902:                     $changes{$provider} = 1;
13903:                 }
13904:             }
13905:             if (ref($defaults{$provider}) eq 'ARRAY') {  
13906:                 if (@{$defaults{$provider}} > 0) {
13907:                     my %options;
13908:                     if (ref($extended{$provider}) eq 'HASH') {
13909:                         %options = %{$extended{$provider}};
13910:                     }
13911:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
13912:                     foreach my $field (@{$defaults{$provider}}) {
13913:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
13914:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
13915:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
13916:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
13917:                             }
13918:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
13919:                             foreach my $inner (keys(%{$options{$field}})) {
13920:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
13921:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
13922:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
13923:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
13924:                                     }
13925:                                 } else {
13926:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
13927:                                 }
13928:                             }
13929:                         } else {
13930:                             if (grep(/^\Q$field\E$/,@checked)) {
13931:                                 push(@{$confhash{$provider}{'defaults'}},$field);
13932:                             }
13933:                         }
13934:                     }
13935:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
13936:                         if (ref($current{'defaults'}) eq 'ARRAY') {
13937:                             unless ($changes{$provider}) {
13938:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
13939:                                 my @old = sort(@{$current{'defaults'}});
13940:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
13941:                                 if (@diffs) {
13942:                                     $changes{$provider} = 1; 
13943:                                 }
13944:                             }
13945:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
13946:                             if (@{$current{'defaults'}}) {
13947:                                 $changes{$provider} = 1;
13948:                             }
13949:                         }
13950:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
13951:                         if (ref($current{'defaults'}) eq 'HASH') {
13952:                             unless ($changes{$provider}) {
13953:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
13954:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
13955:                                         $changes{$provider} = 1;
13956:                                         last;
13957:                                     }
13958:                                 }
13959:                             }
13960:                             unless ($changes{$provider}) {
13961:                                 foreach my $key (keys(%{$current{'defaults'}})) {
13962:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
13963:                                         $changes{$provider} = 1;
13964:                                         last;
13965:                                     }
13966:                                 }
13967:                             }
13968:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
13969:                             $changes{$provider} = 1;
13970:                         }
13971:                     }
13972:                 }
13973:             }
13974:             if (ref($crsconf{$provider}) eq 'ARRAY') {
13975:                 if (@{$crsconf{$provider}} > 0) {
13976:                     $confhash{$provider}{'crsconf'} = [];
13977:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
13978:                     foreach my $crsfield (@{$crsconf{$provider}}) {
13979:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
13980:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
13981:                         }
13982:                     }
13983:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
13984:                         unless ($changes{$provider}) {  
13985:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
13986:                             my @old = sort(@{$current{'crsconf'}});
13987:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
13988:                             if (@diffs) {
13989:                                 $changes{$provider} = 1;
13990:                             }
13991:                         }
13992:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
13993:                         $changes{$provider} = 1;
13994:                     }
13995:                 }
13996:             }
13997:             if ($showroles) {
13998:                 $confhash{$provider}{'roles'} = {};
13999:                 foreach my $role (@courseroles) {
14000:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
14001:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
14002:                         $confhash{$provider}{'roles'}{$role} = $poss;
14003:                     }
14004:                 }
14005:                 unless ($changes{$provider}) {
14006:                     if (ref($current{'roles'}) eq 'HASH') {
14007:                         foreach my $role (keys(%{$current{'roles'}})) {
14008:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
14009:                                 $changes{$provider} = 1;
14010:                                 last
14011:                             }
14012:                         }
14013:                         unless ($changes{$provider}) {
14014:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
14015:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
14016:                                     $changes{$provider} = 1;
14017:                                     last;
14018:                                 }
14019:                             }
14020:                         }
14021:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
14022:                         $changes{$provider} = 1;
14023:                     }
14024:                 }
14025:             }
14026:             if (ref($current{'custom'}) eq 'HASH') {
14027:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
14028:                 foreach my $key (keys(%{$current{'custom'}})) {
14029:                     if (grep(/^\Q$key\E$/,@customdels)) {
14030:                         $changes{$provider} = 1;
14031:                     } else {
14032:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
14033:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
14034:                             $changes{$provider} = 1;
14035:                         }
14036:                     }
14037:                 }
14038:             }
14039:             if ($customadds{$provider}) {
14040:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
14041:                 $name =~ s/(`)/'/g;
14042:                 $name =~ s/^\s+//;
14043:                 $name =~ s/\s+$//;
14044:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
14045:                 $value =~ s/(`)/'/g;
14046:                 $value =~ s/^\s+//;
14047:                 $value =~ s/\s+$//;
14048:                 if ($name ne '') {
14049:                     $confhash{$provider}{'custom'}{$name} = $value;
14050:                     $changes{$provider} = 1;
14051:                 }
14052:             }
14053:         }
14054:     }
14055:     if (@allpos > 0) {
14056:         my $idx = 0;
14057:         foreach my $provider (@allpos) {
14058:             if ($provider ne '') {
14059:                 $confhash{$provider}{'order'} = $idx;
14060:                 unless ($changes{$provider}) {
14061:                     if (ref($domconfig{$action}) eq 'HASH') {
14062:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
14063:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
14064:                                 $changes{$provider} = 1;
14065:                             }
14066:                         }
14067:                     }
14068:                 }
14069:                 $idx ++;
14070:             }
14071:         }
14072:     }
14073:     my %proc_hash = (
14074:                           $action => { %confhash }
14075:                        );
14076:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
14077:                                              $dom);
14078:     if ($putresult eq 'ok') {
14079:         my %proc_enchash = (
14080:                              $action => { %encconfhash }
14081:                          );
14082:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom);
14083:         if (keys(%changes) > 0) {
14084:             my $cachetime = 24*60*60;
14085:             my %procall = %confhash;
14086:             foreach my $provider (keys(%procall)) {
14087:                 if (ref($encconfhash{$provider}) eq 'HASH') {
14088:                     foreach my $key ('key','secret') {
14089:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
14090:                     }
14091:                 }
14092:             }
14093:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
14094:             if (ref($lastactref) eq 'HASH') {
14095:                 $lastactref->{'proctoring'} = 1;
14096:             }
14097:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
14098:             my %bynum;
14099:             foreach my $provider (sort(keys(%changes))) {
14100:                 my $position = $confhash{$provider}{'order'};
14101:                 $bynum{$position} = $provider;
14102:             }
14103:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14104:                 my $provider = $bynum{$pos};
14105:                 my %lt = &proctoring_titles($provider);
14106:                 my %fieldtitles = &proctoring_fieldtitles($provider);
14107:                 if (!$confhash{$provider}{'available'}) {
14108:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
14109:                 } else {
14110:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
14111:                     if ($confhash{$provider}{'image'}) {
14112:                         $resulttext .= '&nbsp;'.
14113:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
14114:                                        ' alt="'.&mt('Proctoring icon').'" />';
14115:                     }
14116:                     $resulttext .= '<ul>';
14117:                     my $position = $pos + 1;
14118:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
14119:                     foreach my $key ('version','sigmethod','url','lifetime') {
14120:                         if ($confhash{$provider}{$key} ne '') {
14121:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
14122:                         }
14123:                     }
14124:                     if ($encconfhash{$provider}{'key'} ne '') {
14125:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
14126:                     }
14127:                     if ($encconfhash{$provider}{'secret'} ne '') {
14128:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
14129:                         my $num = length($encconfhash{$provider}{'secret'});
14130:                         $resulttext .= ('*'x$num).'</li>';
14131:                     }
14132:                     my (@fields,$showroles);
14133:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14134:                         push(@fields,@{$requserfields{$provider}});
14135:                     }
14136:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
14137:                         push(@fields,@{$confhash{$provider}{'fields'}});
14138:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
14139:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
14140:                     }
14141:                     if (@fields) {
14142:                         if (grep(/^roles$/,@fields)) {
14143:                             $showroles = 1;
14144:                         }
14145:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
14146:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
14147:                     }
14148:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
14149:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
14150:                             if ($confhash{$provider}{'incdom'}) {
14151:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
14152:                             } else { 
14153:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
14154:                             }
14155:                         }
14156:                     }
14157:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
14158:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
14159:                             $resulttext .= '<li>'.$lt{'defa'};
14160:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
14161:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
14162:                             }
14163:                             $resulttext =~ s/,$//;
14164:                             $resulttext .= '</li>';
14165:                         }
14166:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
14167:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
14168:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
14169:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
14170:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
14171:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
14172:                                 }
14173:                             }
14174:                             $resulttext .= '</ul></li>';
14175:                         }
14176:                     }
14177:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
14178:                         if (@{$crsconf{$provider}} > 0) {
14179:                             $resulttext .= '<li>'.&mt('Configurable in course:');
14180:                             my $numconfig = 0;
14181:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
14182:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
14183:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
14184:                                         $numconfig ++;
14185:                                         if ($provider eq 'examity') {
14186:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
14187:                                         } else {
14188:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
14189:                                         }
14190:                                     }
14191:                                     $resulttext =~ s/,$//;
14192:                                 }
14193:                             }
14194:                             if (!$numconfig) {
14195:                                 $resulttext .= '&nbsp;'.&mt('None');
14196:                             }
14197:                             $resulttext .= '</li>';
14198:                         }
14199:                     }
14200:                     if ($showroles) {
14201:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
14202:                             my $rolemaps;
14203:                             foreach my $role (@courseroles) {
14204:                                 if ($confhash{$provider}{'roles'}{$role}) {
14205:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
14206:                                                  $confhash{$provider}{'roles'}{$role}.',';
14207:                                 }
14208:                             }
14209:                             if ($rolemaps) {
14210:                                 $rolemaps =~ s/,$//;
14211:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14212:                             }
14213:                         }
14214:                     }
14215:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
14216:                         my $customlist;
14217:                         if (keys(%{$confhash{$provider}{'custom'}})) {
14218:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
14219:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
14220:                             }
14221:                             $customlist =~ s/,$//;
14222:                         }
14223:                         if ($customlist) {
14224:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
14225:                         }
14226:                     } 
14227:                     $resulttext .= '</ul></li>';
14228:                 }
14229:             }
14230:             $resulttext .= '</ul>';
14231:         } else {
14232:             $resulttext = &mt('No changes made.');
14233:         }
14234:     } else {
14235:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14236:     }
14237:     if ($errors) {
14238:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14239:                        $errors.'</ul>';
14240:     }
14241:     return $resulttext;
14242: }
14243: 
14244: sub process_proctoring_image {
14245:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
14246:     my $filename = $env{'form.'.$caller.'.filename'};
14247:     my ($error,$url);
14248:     my ($width,$height) = (21,21);
14249:     if ($configuserok eq 'ok') {
14250:         if ($switchserver) {
14251:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
14252:                          $switchserver);
14253:         } elsif ($author_ok eq 'ok') {
14254:             my ($result,$imageurl,$madethumb) =
14255:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14256:                              "proctoring/$provider/icon",$width,$height);
14257:             if ($result eq 'ok') {
14258:                 if ($madethumb) {
14259:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
14260:                     my $imagethumb = "$path/tn-".$imagefile;
14261:                     $url = $imagethumb;
14262:                 } else {
14263:                     $url = $imageurl;
14264:                 }
14265:             } else {
14266:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14267:             }
14268:         } else {
14269:             $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);
14270:         }
14271:     } else {
14272:         $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);
14273:     }
14274:     return ($url,$error);
14275: }
14276: 
14277: sub modify_lti {
14278:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14279:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14280:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14281:     my (%posslti,%posslticrs,%posscrstype);
14282:     my @courseroles = ('cc','in','ta','ep','st');
14283:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
14284:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
14285:     my @coursetypes = ('official','unofficial','community','textbook','placement');
14286:     my %coursetypetitles = &Apache::lonlocal::texthash (
14287:                                official   => 'Official',
14288:                                unofficial => 'Unofficial',
14289:                                community  => 'Community',
14290:                                textbook   => 'Textbook',
14291:                                placement  => 'Placement Test',
14292:     );
14293:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
14294:     my %lt = &lti_names();
14295:     map { $posslti{$_} = 1; } @ltiroles;
14296:     map { $posslticrs{$_} = 1; } @lticourseroles;
14297:     map { $posscrstype{$_} = 1; } @coursetypes;
14298: 
14299:     my %menutitles = &ltimenu_titles();
14300: 
14301:     my (@items,%deletions,%itemids);
14302:     if ($env{'form.lti_add'}) {
14303:         my $consumer = $env{'form.lti_consumer_add'};
14304:         $consumer =~ s/(`)/'/g;
14305:         ($newid,my $error) = &get_lti_id($dom,$consumer);
14306:         if ($newid) {
14307:             $itemids{'add'} = $newid;
14308:             push(@items,'add');
14309:             $changes{$newid} = 1;
14310:         } else {
14311:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
14312:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14313:         }
14314:     }
14315:     if (ref($domconfig{$action}) eq 'HASH') {
14316:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
14317:         if (@todelete) {
14318:             map { $deletions{$_} = 1; } @todelete;
14319:         }
14320:         my $maxnum = $env{'form.lti_maxnum'};
14321:         for (my $i=0; $i<=$maxnum; $i++) {
14322:             my $itemid = $env{'form.lti_id_'.$i};
14323:             $itemid =~ s/\D+//g;
14324:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14325:                 if ($deletions{$itemid}) {
14326:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
14327:                 } else {
14328:                    push(@items,$i);
14329:                    $itemids{$i} = $itemid;
14330:                 }
14331:             }
14332:         }
14333:     }
14334:     foreach my $idx (@items) {
14335:         my $itemid = $itemids{$idx};
14336:         next unless ($itemid);
14337:         my $position = $env{'form.lti_pos_'.$idx};
14338:         $position =~ s/\D+//g;
14339:         if ($position ne '') {
14340:             $allpos[$position] = $itemid;
14341:         }
14342:         foreach my $item ('consumer','key','secret','lifetime','requser') {
14343:             my $formitem = 'form.lti_'.$item.'_'.$idx;
14344:             $env{$formitem} =~ s/(`)/'/g;
14345:             if ($item eq 'lifetime') {
14346:                 $env{$formitem} =~ s/[^\d.]//g;
14347:             }
14348:             if ($env{$formitem} ne '') {
14349:                 if (($item eq 'key') || ($item eq 'secret')) {
14350:                     $encconfig{$itemid}{$item} = $env{$formitem};
14351:                 } else {
14352:                     $confhash{$itemid}{$item} = $env{$formitem};
14353:                     unless (($idx eq 'add') || ($changes{$itemid})) {
14354:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14355:                             $changes{$itemid} = 1;
14356:                         }
14357:                     }
14358:                 }
14359:             }
14360:         }
14361:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
14362:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
14363:         }
14364:         if ($confhash{$itemid}{'requser'}) {
14365:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
14366:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid'; 
14367:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
14368:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
14369:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
14370:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
14371:                 $mapuser =~ s/(`)/'/g;
14372:                 $mapuser =~ s/^\s+|\s+$//g; 
14373:                 $confhash{$itemid}{'mapuser'} = $mapuser; 
14374:             }
14375:             foreach my $ltirole (@lticourseroles) {
14376:                 my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
14377:                 if (grep(/^\Q$possrole\E$/,@courseroles)) {
14378:                     $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
14379:                 }
14380:             }
14381:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
14382:             my @makeuser;
14383:             foreach my $ltirole (sort(@possmakeuser)) {
14384:                 if ($posslti{$ltirole}) {
14385:                     push(@makeuser,$ltirole);
14386:                 }
14387:             }
14388:             $confhash{$itemid}{'makeuser'} = \@makeuser;
14389:             if (@makeuser) {
14390:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
14391:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
14392:                     $confhash{$itemid}{'lcauth'} = $lcauth;
14393:                     if ($lcauth ne 'internal') {
14394:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
14395:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
14396:                         $lcauthparm =~ s/`//g;
14397:                         if ($lcauthparm ne '') {
14398:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
14399:                         }
14400:                     }
14401:                 } else {
14402:                     $confhash{$itemid}{'lcauth'} = 'lti';
14403:                 }
14404:             }
14405:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
14406:             if (@possinstdata) {
14407:                 foreach my $field (@possinstdata) {
14408:                     if (exists($fieldtitles{$field})) {
14409:                         push(@{$confhash{$itemid}{'instdata'}});
14410:                     }
14411:                 }
14412:             }
14413:             if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
14414:                 ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
14415:                 $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
14416:             } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
14417:                 my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
14418:                 $mapcrs =~ s/(`)/'/g;
14419:                 $mapcrs =~ s/^\s+|\s+$//g;
14420:                 $confhash{$itemid}{'mapcrs'} = $mapcrs;
14421:             }
14422:             my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
14423:             my @crstypes;
14424:             foreach my $type (sort(@posstypes)) {
14425:                 if ($posscrstype{$type}) {
14426:                     push(@crstypes,$type);
14427:                 }
14428:             }
14429:             $confhash{$itemid}{'mapcrstype'} = \@crstypes;
14430:             if ($env{'form.lti_makecrs_'.$idx}) {
14431:                 $confhash{$itemid}{'makecrs'} = 1;
14432:             }
14433:             my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
14434:             my @selfenroll;
14435:             foreach my $type (sort(@possenroll)) {
14436:                 if ($posslticrs{$type}) {
14437:                     push(@selfenroll,$type);
14438:                 }
14439:             }
14440:             $confhash{$itemid}{'selfenroll'} = \@selfenroll;
14441:             if ($env{'form.lti_crssec_'.$idx}) {
14442:                 if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
14443:                     $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
14444:                 } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
14445:                     my $section = $env{'form.lti_customsection_'.$idx};
14446:                     $section =~ s/(`)/'/g;
14447:                     $section =~ s/^\s+|\s+$//g;
14448:                     if ($section ne '') {
14449:                         $confhash{$itemid}{'section'} = $section;
14450:                     }
14451:                 }
14452:             }
14453:             if ($env{'form.lti_callback_'.$idx}) {
14454:                 if ($env{'form.lti_callbackparam_'.$idx}) {
14455:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
14456:                     $callback =~ s/^\s+|\s+$//g;
14457:                     $confhash{$itemid}{'callback'} = $callback;
14458:                 }
14459:             }
14460:             foreach my $field ('passback','roster','topmenu','inlinemenu') {
14461:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
14462:                     $confhash{$itemid}{$field} = 1;
14463:                 }
14464:             }
14465:             if ($env{'form.lti_passback_'.$idx}) {
14466:                 if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
14467:                     $confhash{$itemid}{'passbackformat'} = '1.0';
14468:                 } else {
14469:                     $confhash{$itemid}{'passbackformat'} = '1.1';
14470:                 }
14471:             }
14472:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
14473:                 $confhash{$itemid}{lcmenu} = [];
14474:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
14475:                 foreach my $field (@possmenu) {
14476:                     if (exists($menutitles{$field})) {
14477:                         if ($field eq 'grades') {
14478:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
14479:                         }
14480:                         push(@{$confhash{$itemid}{lcmenu}},$field);
14481:                     }
14482:                 }
14483:             }
14484:             unless (($idx eq 'add') || ($changes{$itemid})) {
14485:                 foreach my $field ('mapuser','mapcrs','makecrs','section','passback','roster','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
14486:                     if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
14487:                         $changes{$itemid} = 1;
14488:                     }
14489:                 }
14490:                 unless ($changes{$itemid}) {
14491:                     if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
14492:                         if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
14493:                             $changes{$itemid} = 1;
14494:                         }
14495:                     }
14496:                 }
14497:                 foreach my $field ('makeuser','mapcrstype','selfenroll','instdata','lcmenu') {
14498:                     unless ($changes{$itemid}) {
14499:                         if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
14500:                             if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14501:                                 my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
14502:                                                                                $confhash{$itemid}{$field});
14503:                                 if (@diffs) {
14504:                                     $changes{$itemid} = 1;
14505:                                 }
14506:                             } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
14507:                                 $changes{$itemid} = 1;
14508:                             }
14509:                         } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
14510:                             if (@{$confhash{$itemid}{$field}} > 0) {
14511:                                 $changes{$itemid} = 1;
14512:                             }
14513:                         }
14514:                     }
14515:                 }
14516:                 unless ($changes{$itemid}) {
14517:                     if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
14518:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14519:                             foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
14520:                                 if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
14521:                                     $confhash{$itemid}{'maproles'}{$ltirole}) {
14522:                                     $changes{$itemid} = 1;
14523:                                     last;
14524:                                 }
14525:                             }
14526:                             unless ($changes{$itemid}) {
14527:                                 foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
14528:                                     if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
14529:                                         $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
14530:                                         $changes{$itemid} = 1;
14531:                                         last;
14532:                                     }
14533:                                 }
14534:                             }
14535:                         } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
14536:                             $changes{$itemid} = 1;
14537:                         }
14538:                     } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14539:                         unless ($changes{$itemid}) {
14540:                             if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
14541:                                 $changes{$itemid} = 1;
14542:                             }
14543:                         }
14544:                     }
14545:                 }
14546:             }
14547:         }
14548:     }
14549:     if (@allpos > 0) {
14550:         my $idx = 0;
14551:         foreach my $itemid (@allpos) {
14552:             if ($itemid ne '') {
14553:                 $confhash{$itemid}{'order'} = $idx;
14554:                 if (ref($domconfig{$action}) eq 'HASH') {
14555:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14556:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
14557:                             $changes{$itemid} = 1;
14558:                         }
14559:                     }
14560:                 }
14561:                 $idx ++;
14562:             }
14563:         }
14564:     }
14565:     my %ltihash = (
14566:                           $action => { %confhash }
14567:                        );
14568:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,
14569:                                              $dom);
14570:     if ($putresult eq 'ok') {
14571:         my %ltienchash = (
14572:                              $action => { %encconfig }
14573:                          );
14574:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom);
14575:         if (keys(%changes) > 0) {
14576:             my $cachetime = 24*60*60;
14577:             my %ltiall = %confhash;
14578:             foreach my $id (keys(%ltiall)) {
14579:                 if (ref($encconfig{$id}) eq 'HASH') {
14580:                     foreach my $item ('key','secret') {
14581:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
14582:                     }
14583:                 }
14584:             }
14585:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
14586:             if (ref($lastactref) eq 'HASH') {
14587:                 $lastactref->{'lti'} = 1;
14588:             }
14589:             $resulttext = &mt('Changes made:').'<ul>';
14590:             my %bynum;
14591:             foreach my $itemid (sort(keys(%changes))) {
14592:                 my $position = $confhash{$itemid}{'order'};
14593:                 $bynum{$position} = $itemid;
14594:             }
14595:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
14596:                 my $itemid = $bynum{$pos};
14597:                 if (ref($confhash{$itemid}) ne 'HASH') {
14598:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
14599:                 } else {
14600:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b></li><ul>';
14601:                     my $position = $pos + 1;
14602:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
14603:                     foreach my $item ('version','lifetime') {
14604:                         if ($confhash{$itemid}{$item} ne '') {
14605:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
14606:                         }
14607:                     }
14608:                     if ($encconfig{$itemid}{'key'} ne '') {
14609:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
14610:                     }
14611:                     if ($encconfig{$itemid}{'secret'} ne '') {
14612:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
14613:                         my $num = length($encconfig{$itemid}{'secret'});
14614:                         $resulttext .= ('*'x$num).'</li>';
14615:                     }
14616:                     if ($confhash{$itemid}{'requser'}) {
14617:                         if ($confhash{$itemid}{'mapuser'}) {
14618:                             my $shownmapuser;
14619:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
14620:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
14621:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
14622:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
14623:                             } else {
14624:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
14625:                             }
14626:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
14627:                         }
14628:                         if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
14629:                             my $rolemaps;
14630:                             foreach my $role (@ltiroles) {
14631:                                 if ($confhash{$itemid}{'maproles'}{$role}) {
14632:                                     $rolemaps .= ('&nbsp;'x2).$role.'='.
14633:                                                  &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
14634:                                                                             'Course').',';
14635:                                 }
14636:                             }
14637:                             if ($rolemaps) {
14638:                                 $rolemaps =~ s/,$//;
14639:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
14640:                             }
14641:                         }
14642:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
14643:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
14644:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
14645:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
14646:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
14647:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
14648:                                 } else {
14649:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
14650:                                                        $confhash{$itemid}{'lcauth'});
14651:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
14652:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
14653:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
14654:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
14655:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
14656:                                         }
14657:                                     } else {
14658:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
14659:                                     }
14660:                                 }
14661:                                 $resulttext .= '</li>';
14662:                             } else {
14663:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
14664:                             }
14665:                         }
14666:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
14667:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
14668:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
14669:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
14670:                             } else {
14671:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
14672:                             }
14673:                         }
14674:                         if ($confhash{$itemid}{'mapcrs'}) {
14675:                             $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
14676:                         }
14677:                         if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
14678:                             if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
14679:                                 $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
14680:                                                join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
14681:                                                '</li>';
14682:                             } else {
14683:                                 $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
14684:                             }
14685:                         }
14686:                         if ($confhash{$itemid}{'makecrs'}) {
14687:                             $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
14688:                         } else {
14689:                             $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
14690:                         }
14691:                         if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
14692:                             if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
14693:                                 $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
14694:                                                           join(', ',@{$confhash{$itemid}{'selfenroll'}})).
14695:                                                '</li>';
14696:                             } else {
14697:                                 $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
14698:                             }
14699:                         }
14700:                         if ($confhash{$itemid}{'section'}) {
14701:                             if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
14702:                                 $resulttext .= '<li>'.&mt('User section from standard field:').
14703:                                                      ' (course_section_sourcedid)'.'</li>';  
14704:                             } else {
14705:                                 $resulttext .= '<li>'.&mt('User section from:').' '.
14706:                                                       $confhash{$itemid}{'section'}.'</li>';
14707:                             }
14708:                         } else {
14709:                             $resulttext .= '<li>'.&mt('No section assignment').'</li>';
14710:                         }
14711:                         if ($confhash{$itemid}{'callback'}) {
14712:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
14713:                         } else {
14714:                             $resulttext .= '<li>'.&mt('No callback to logout LON-CAPA session when user logs out of Comsumer');
14715:                         }
14716:                         foreach my $item ('passback','roster','topmenu','inlinemenu') {
14717:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
14718:                             if ($confhash{$itemid}{$item}) {
14719:                                 $resulttext .= &mt('Yes');
14720:                                 if ($item eq 'passback') {
14721:                                     if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
14722:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
14723:                                     } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
14724:                                         $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
14725:                                     }
14726:                                 }
14727:                             } else {
14728:                                 $resulttext .= &mt('No');
14729:                             }
14730:                             $resulttext .= '</li>';
14731:                         }
14732:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
14733:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
14734:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
14735:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
14736:                             } else {
14737:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
14738:                             }
14739:                         }
14740:                     }
14741:                     $resulttext .= '</ul></li>';
14742:                 }
14743:             }
14744:             $resulttext .= '</ul>';
14745:         } else {
14746:             $resulttext = &mt('No changes made.');
14747:         }
14748:     } else {
14749:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
14750:     }
14751:     if ($errors) {
14752:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
14753:                        $errors.'</ul>';
14754:     }
14755:     return $resulttext;
14756: }
14757: 
14758: sub get_lti_id {
14759:     my ($domain,$consumer) = @_;
14760:     # get lock on lti db
14761:     my $lockhash = {
14762:                       lock => $env{'user.name'}.
14763:                               ':'.$env{'user.domain'},
14764:                    };
14765:     my $tries = 0;
14766:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
14767:     my ($id,$error);
14768: 
14769:     while (($gotlock ne 'ok') && ($tries<10)) {
14770:         $tries ++;
14771:         sleep (0.1);
14772:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
14773:     }
14774:     if ($gotlock eq 'ok') {
14775:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
14776:         if ($currids{'lock'}) {
14777:             delete($currids{'lock'});
14778:             if (keys(%currids)) {
14779:                 my @curr = sort { $a <=> $b } keys(%currids);
14780:                 if ($curr[-1] =~ /^\d+$/) {
14781:                     $id = 1 + $curr[-1];
14782:                 }
14783:             } else {
14784:                 $id = 1;
14785:             }
14786:             if ($id) {
14787:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
14788:                     $error = 'nostore';
14789:                 }
14790:             } else {
14791:                 $error = 'nonumber';
14792:             }
14793:         }
14794:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
14795:     } else {
14796:         $error = 'nolock';
14797:     }
14798:     return ($id,$error);
14799: }
14800: 
14801: sub modify_autoenroll {
14802:     my ($dom,$lastactref,%domconfig) = @_;
14803:     my ($resulttext,%changes);
14804:     my %currautoenroll;
14805:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
14806:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
14807:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
14808:         }
14809:     }
14810:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
14811:     my %title = ( run => 'Auto-enrollment active',
14812:                   sender => 'Sender for notification messages',
14813:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
14814:                   failsafe => 'Failsafe for no drops if institutional data missing for a section');
14815:     my @offon = ('off','on');
14816:     my $sender_uname = $env{'form.sender_uname'};
14817:     my $sender_domain = $env{'form.sender_domain'};
14818:     if ($sender_domain eq '') {
14819:         $sender_uname = '';
14820:     } elsif ($sender_uname eq '') {
14821:         $sender_domain = '';
14822:     }
14823:     my $coowners = $env{'form.autoassign_coowners'};
14824:     my $failsafe = $env{'form.autoenroll_failsafe'};
14825:     $failsafe =~ s{^\s+|\s+$}{}g;
14826:     if ($failsafe =~ /\D/) {
14827:         undef($failsafe);
14828:     }
14829:     my %autoenrollhash =  (
14830:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
14831:                                        'sender_uname' => $sender_uname,
14832:                                        'sender_domain' => $sender_domain,
14833:                                        'co-owners' => $coowners,
14834:                                        'autofailsafe' => $failsafe,
14835:                                 }
14836:                      );
14837:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
14838:                                              $dom);
14839:     if ($putresult eq 'ok') {
14840:         if (exists($currautoenroll{'run'})) {
14841:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
14842:                  $changes{'run'} = 1;
14843:              }
14844:         } elsif ($autorun) {
14845:             if ($env{'form.autoenroll_run'} ne '1') {
14846:                  $changes{'run'} = 1;
14847:             }
14848:         }
14849:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
14850:             $changes{'sender'} = 1;
14851:         }
14852:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
14853:             $changes{'sender'} = 1;
14854:         }
14855:         if ($currautoenroll{'co-owners'} ne '') {
14856:             if ($currautoenroll{'co-owners'} ne $coowners) {
14857:                 $changes{'coowners'} = 1;
14858:             }
14859:         } elsif ($coowners) {
14860:             $changes{'coowners'} = 1;
14861:         }
14862:         if ($currautoenroll{'autofailsafe'} ne $failsafe) {
14863:             $changes{'autofailsafe'} = 1;
14864:         }
14865:         if (keys(%changes) > 0) {
14866:             $resulttext = &mt('Changes made:').'<ul>';
14867:             if ($changes{'run'}) {
14868:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
14869:             }
14870:             if ($changes{'sender'}) {
14871:                 if ($sender_uname eq '' || $sender_domain eq '') {
14872:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
14873:                 } else {
14874:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
14875:                 }
14876:             }
14877:             if ($changes{'coowners'}) {
14878:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
14879:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
14880:                 if (ref($lastactref) eq 'HASH') {
14881:                     $lastactref->{'domainconfig'} = 1;
14882:                 }
14883:             }
14884:             if ($changes{'autofailsafe'}) {
14885:                 if ($failsafe ne '') {
14886:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$failsafe).'</li>';
14887:                 } else {
14888:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section: deleted');
14889:                 }
14890:                 &Apache::lonnet::get_domain_defaults($dom,1);
14891:                 if (ref($lastactref) eq 'HASH') {
14892:                     $lastactref->{'domdefaults'} = 1;
14893:                 }
14894:             }
14895:             $resulttext .= '</ul>';
14896:         } else {
14897:             $resulttext = &mt('No changes made to auto-enrollment settings');
14898:         }
14899:     } else {
14900:         $resulttext = '<span class="LC_error">'.
14901: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14902:     }
14903:     return $resulttext;
14904: }
14905: 
14906: sub modify_autoupdate {
14907:     my ($dom,%domconfig) = @_;
14908:     my ($resulttext,%currautoupdate,%fields,%changes);
14909:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
14910:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
14911:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
14912:         }
14913:     }
14914:     my @offon = ('off','on');
14915:     my %title = &Apache::lonlocal::texthash (
14916:                    run => 'Auto-update:',
14917:                    classlists => 'Updates to user information in classlists?'
14918:                 );
14919:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
14920:     my %fieldtitles = &Apache::lonlocal::texthash (
14921:                         id => 'Student/Employee ID',
14922:                         permanentemail => 'E-mail address',
14923:                         lastname => 'Last Name',
14924:                         firstname => 'First Name',
14925:                         middlename => 'Middle Name',
14926:                         generation => 'Generation',
14927:                       );
14928:     $othertitle = &mt('All users');
14929:     if (keys(%{$usertypes}) >  0) {
14930:         $othertitle = &mt('Other users');
14931:     }
14932:     foreach my $key (keys(%env)) {
14933:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
14934:             my ($usertype,$item) = ($1,$2);
14935:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
14936:                 if ($usertype eq 'default') {   
14937:                     push(@{$fields{$1}},$2);
14938:                 } elsif (ref($types) eq 'ARRAY') {
14939:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
14940:                         push(@{$fields{$1}},$2);
14941:                     }
14942:                 }
14943:             }
14944:         }
14945:     }
14946:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
14947:     @lockablenames = sort(@lockablenames);
14948:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
14949:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
14950:         if (@changed) {
14951:             $changes{'lockablenames'} = 1;
14952:         }
14953:     } else {
14954:         if (@lockablenames) {
14955:             $changes{'lockablenames'} = 1;
14956:         }
14957:     }
14958:     my %updatehash = (
14959:                       autoupdate => { run => $env{'form.autoupdate_run'},
14960:                                       classlists => $env{'form.classlists'},
14961:                                       fields => {%fields},
14962:                                       lockablenames => \@lockablenames,
14963:                                     }
14964:                      );
14965:     foreach my $key (keys(%currautoupdate)) {
14966:         if (($key eq 'run') || ($key eq 'classlists')) {
14967:             if (exists($updatehash{autoupdate}{$key})) {
14968:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
14969:                     $changes{$key} = 1;
14970:                 }
14971:             }
14972:         } elsif ($key eq 'fields') {
14973:             if (ref($currautoupdate{$key}) eq 'HASH') {
14974:                 foreach my $item (@{$types},'default') {
14975:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
14976:                         my $change = 0;
14977:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
14978:                             if (!exists($fields{$item})) {
14979:                                 $change = 1;
14980:                                 last;
14981:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
14982:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
14983:                                     $change = 1;
14984:                                     last;
14985:                                 }
14986:                             }
14987:                         }
14988:                         if ($change) {
14989:                             push(@{$changes{$key}},$item);
14990:                         }
14991:                     } 
14992:                 }
14993:             }
14994:         } elsif ($key eq 'lockablenames') {
14995:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
14996:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
14997:                 if (@changed) {
14998:                     $changes{'lockablenames'} = 1;
14999:                 }
15000:             } else {
15001:                 if (@lockablenames) {
15002:                     $changes{'lockablenames'} = 1;
15003:                 }
15004:             }
15005:         }
15006:     }
15007:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
15008:         if (@lockablenames) {
15009:             $changes{'lockablenames'} = 1;
15010:         }
15011:     }
15012:     foreach my $item (@{$types},'default') {
15013:         if (defined($fields{$item})) {
15014:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
15015:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
15016:                     my $change = 0;
15017:                     if (ref($fields{$item}) eq 'ARRAY') {
15018:                         foreach my $type (@{$fields{$item}}) {
15019:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
15020:                                 $change = 1;
15021:                                 last;
15022:                             }
15023:                         }
15024:                     }
15025:                     if ($change) {
15026:                         push(@{$changes{'fields'}},$item);
15027:                     }
15028:                 } else {
15029:                     push(@{$changes{'fields'}},$item);
15030:                 }
15031:             } else {
15032:                 push(@{$changes{'fields'}},$item);
15033:             }
15034:         }
15035:     }
15036:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
15037:                                              $dom);
15038:     if ($putresult eq 'ok') {
15039:         if (keys(%changes) > 0) {
15040:             $resulttext = &mt('Changes made:').'<ul>';
15041:             foreach my $key (sort(keys(%changes))) {
15042:                 if ($key eq 'lockablenames') {
15043:                     $resulttext .= '<li>';
15044:                     if (@lockablenames) {
15045:                         $usertypes->{'default'} = $othertitle;
15046:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
15047:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
15048:                     } else {
15049:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
15050:                     }
15051:                     $resulttext .= '</li>';
15052:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
15053:                     foreach my $item (@{$changes{$key}}) {
15054:                         my @newvalues;
15055:                         foreach my $type (@{$fields{$item}}) {
15056:                             push(@newvalues,$fieldtitles{$type});
15057:                         }
15058:                         my $newvaluestr;
15059:                         if (@newvalues > 0) {
15060:                             $newvaluestr = join(', ',@newvalues);
15061:                         } else {
15062:                             $newvaluestr = &mt('none');
15063:                         }
15064:                         if ($item eq 'default') {
15065:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
15066:                         } else {
15067:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
15068:                         }
15069:                     }
15070:                 } else {
15071:                     my $newvalue;
15072:                     if ($key eq 'run') {
15073:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
15074:                     } else {
15075:                         $newvalue = $offon[$env{'form.'.$key}];
15076:                     }
15077:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
15078:                 }
15079:             }
15080:             $resulttext .= '</ul>';
15081:         } else {
15082:             $resulttext = &mt('No changes made to autoupdates');
15083:         }
15084:     } else {
15085:         $resulttext = '<span class="LC_error">'.
15086: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
15087:     }
15088:     return $resulttext;
15089: }
15090: 
15091: sub modify_autocreate {
15092:     my ($dom,%domconfig) = @_;
15093:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
15094:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
15095:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
15096:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
15097:         }
15098:     }
15099:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
15100:                  req => 'Auto-creation of validated requests for official courses',
15101:                  xmldc => 'Identity of course creator of courses from XML files',
15102:                );
15103:     my @types = ('xml','req');
15104:     foreach my $item (@types) {
15105:         $newvals{$item} = $env{'form.autocreate_'.$item};
15106:         $newvals{$item} =~ s/\D//g;
15107:         $newvals{$item} = 0 if ($newvals{$item} eq '');
15108:     }
15109:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
15110:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
15111:     unless (exists($domcoords{$newvals{'xmldc'}})) {
15112:         $newvals{'xmldc'} = '';
15113:     } 
15114:     %autocreatehash =  (
15115:                         autocreate => { xml => $newvals{'xml'},
15116:                                         req => $newvals{'req'},
15117:                                       }
15118:                        );
15119:     if ($newvals{'xmldc'} ne '') {
15120:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
15121:     }
15122:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
15123:                                              $dom);
15124:     if ($putresult eq 'ok') {
15125:         my @items = @types;
15126:         if ($newvals{'xml'}) {
15127:             push(@items,'xmldc');
15128:         }
15129:         foreach my $item (@items) {
15130:             if (exists($currautocreate{$item})) {
15131:                 if ($currautocreate{$item} ne $newvals{$item}) {
15132:                     $changes{$item} = 1;
15133:                 }
15134:             } elsif ($newvals{$item}) {
15135:                 $changes{$item} = 1;
15136:             }
15137:         }
15138:         if (keys(%changes) > 0) {
15139:             my @offon = ('off','on'); 
15140:             $resulttext = &mt('Changes made:').'<ul>';
15141:             foreach my $item (@types) {
15142:                 if ($changes{$item}) {
15143:                     my $newtxt = $offon[$newvals{$item}];
15144:                     $resulttext .= '<li>'.
15145:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
15146:                                        '<b>','</b>').
15147:                                    '</li>';
15148:                 }
15149:             }
15150:             if ($changes{'xmldc'}) {
15151:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
15152:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
15153:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
15154:             }
15155:             $resulttext .= '</ul>';
15156:         } else {
15157:             $resulttext = &mt('No changes made to auto-creation settings');
15158:         }
15159:     } else {
15160:         $resulttext = '<span class="LC_error">'.
15161:             &mt('An error occurred: [_1]',$putresult).'</span>';
15162:     }
15163:     return $resulttext;
15164: }
15165: 
15166: sub modify_directorysrch {
15167:     my ($dom,$lastactref,%domconfig) = @_;
15168:     my ($resulttext,%changes);
15169:     my %currdirsrch;
15170:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
15171:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
15172:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
15173:         }
15174:     }
15175:     my %title = ( available => 'Institutional directory search available',
15176:                   localonly => 'Other domains can search institution',
15177:                   lcavailable => 'LON-CAPA directory search available',
15178:                   lclocalonly => 'Other domains can search LON-CAPA domain',
15179:                   searchby => 'Search types',
15180:                   searchtypes => 'Search latitude');
15181:     my @offon = ('off','on');
15182:     my @otherdoms = ('Yes','No');
15183: 
15184:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
15185:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
15186:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
15187: 
15188:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15189:     if (keys(%{$usertypes}) == 0) {
15190:         @cansearch = ('default');
15191:     } else {
15192:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
15193:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
15194:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
15195:                     push(@{$changes{'cansearch'}},$type);
15196:                 }
15197:             }
15198:             foreach my $type (@cansearch) {
15199:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
15200:                     push(@{$changes{'cansearch'}},$type);
15201:                 }
15202:             }
15203:         } else {
15204:             push(@{$changes{'cansearch'}},@cansearch);
15205:         }
15206:     }
15207: 
15208:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
15209:         foreach my $by (@{$currdirsrch{'searchby'}}) {
15210:             if (!grep(/^\Q$by\E$/,@searchby)) {
15211:                 push(@{$changes{'searchby'}},$by);
15212:             }
15213:         }
15214:         foreach my $by (@searchby) {
15215:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
15216:                 push(@{$changes{'searchby'}},$by);
15217:             }
15218:         }
15219:     } else {
15220:         push(@{$changes{'searchby'}},@searchby);
15221:     }
15222: 
15223:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
15224:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
15225:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
15226:                 push(@{$changes{'searchtypes'}},$type);
15227:             }
15228:         }
15229:         foreach my $type (@searchtypes) {
15230:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
15231:                 push(@{$changes{'searchtypes'}},$type);
15232:             }
15233:         }
15234:     } else {
15235:         if (exists($currdirsrch{'searchtypes'})) {
15236:             foreach my $type (@searchtypes) {  
15237:                 if ($type ne $currdirsrch{'searchtypes'}) { 
15238:                     push(@{$changes{'searchtypes'}},$type);
15239:                 }
15240:             }
15241:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
15242:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
15243:             }   
15244:         } else {
15245:             push(@{$changes{'searchtypes'}},@searchtypes); 
15246:         }
15247:     }
15248: 
15249:     my %dirsrch_hash =  (
15250:             directorysrch => { available => $env{'form.dirsrch_available'},
15251:                                cansearch => \@cansearch,
15252:                                localonly => $env{'form.dirsrch_instlocalonly'},
15253:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
15254:                                lcavailable => $env{'form.dirsrch_domavailable'},
15255:                                searchby => \@searchby,
15256:                                searchtypes => \@searchtypes,
15257:                              }
15258:             );
15259:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
15260:                                              $dom);
15261:     if ($putresult eq 'ok') {
15262:         if (exists($currdirsrch{'available'})) {
15263:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
15264:                  $changes{'available'} = 1;
15265:              }
15266:         } else {
15267:             if ($env{'form.dirsrch_available'} eq '1') {
15268:                 $changes{'available'} = 1;
15269:             }
15270:         }
15271:         if (exists($currdirsrch{'lcavailable'})) {
15272:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
15273:                 $changes{'lcavailable'} = 1;
15274:             }
15275:         } else {
15276:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
15277:                 $changes{'lcavailable'} = 1;
15278:             }
15279:         }
15280:         if (exists($currdirsrch{'localonly'})) {
15281:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
15282:                 $changes{'localonly'} = 1;
15283:             }
15284:         } else {
15285:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
15286:                 $changes{'localonly'} = 1;
15287:             }
15288:         }
15289:         if (exists($currdirsrch{'lclocalonly'})) {
15290:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
15291:                 $changes{'lclocalonly'} = 1;
15292:             }
15293:         } else {
15294:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
15295:                 $changes{'lclocalonly'} = 1;
15296:             }
15297:         }
15298:         if (keys(%changes) > 0) {
15299:             $resulttext = &mt('Changes made:').'<ul>';
15300:             if ($changes{'available'}) {
15301:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
15302:             }
15303:             if ($changes{'lcavailable'}) {
15304:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
15305:             }
15306:             if ($changes{'localonly'}) {
15307:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
15308:             }
15309:             if ($changes{'lclocalonly'}) {
15310:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
15311:             }
15312:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
15313:                 my $chgtext;
15314:                 if (ref($usertypes) eq 'HASH') {
15315:                     if (keys(%{$usertypes}) > 0) {
15316:                         foreach my $type (@{$types}) {
15317:                             if (grep(/^\Q$type\E$/,@cansearch)) {
15318:                                 $chgtext .= $usertypes->{$type}.'; ';
15319:                             }
15320:                         }
15321:                         if (grep(/^default$/,@cansearch)) {
15322:                             $chgtext .= $othertitle;
15323:                         } else {
15324:                             $chgtext =~ s/\; $//;
15325:                         }
15326:                         $resulttext .=
15327:                             '<li>'.
15328:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
15329:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
15330:                             '</li>';
15331:                     }
15332:                 }
15333:             }
15334:             if (ref($changes{'searchby'}) eq 'ARRAY') {
15335:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
15336:                 my $chgtext;
15337:                 foreach my $type (@{$titleorder}) {
15338:                     if (grep(/^\Q$type\E$/,@searchby)) {
15339:                         if (defined($searchtitles->{$type})) {
15340:                             $chgtext .= $searchtitles->{$type}.'; ';
15341:                         }
15342:                     }
15343:                 }
15344:                 $chgtext =~ s/\; $//;
15345:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
15346:             }
15347:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
15348:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
15349:                 my $chgtext;
15350:                 foreach my $type (@{$srchtypeorder}) {
15351:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
15352:                         if (defined($srchtypes_desc->{$type})) {
15353:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
15354:                         }
15355:                     }
15356:                 }
15357:                 $chgtext =~ s/\; $//;
15358:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
15359:             }
15360:             $resulttext .= '</ul>';
15361:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
15362:             if (ref($lastactref) eq 'HASH') {
15363:                 $lastactref->{'directorysrch'} = 1;
15364:             }
15365:         } else {
15366:             $resulttext = &mt('No changes made to directory search settings');
15367:         }
15368:     } else {
15369:         $resulttext = '<span class="LC_error">'.
15370:                       &mt('An error occurred: [_1]',$putresult).'</span>';
15371:     }
15372:     return $resulttext;
15373: }
15374: 
15375: sub modify_contacts {
15376:     my ($dom,$lastactref,%domconfig) = @_;
15377:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
15378:     if (ref($domconfig{'contacts'}) eq 'HASH') {
15379:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
15380:             $currsetting{$key} = $domconfig{'contacts'}{$key};
15381:         }
15382:     }
15383:     my (%others,%to,%bcc,%includestr,%includeloc);
15384:     my @contacts = ('supportemail','adminemail');
15385:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
15386:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
15387:     my @toggles = ('reporterrors','reportupdates','reportstatus');
15388:     my @lonstatus = ('threshold','sysmail','weights','excluded');
15389:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
15390:     foreach my $type (@mailings) {
15391:         @{$newsetting{$type}} = 
15392:             &Apache::loncommon::get_env_multiple('form.'.$type);
15393:         foreach my $item (@contacts) {
15394:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
15395:                 $contacts_hash{contacts}{$type}{$item} = 1;
15396:             } else {
15397:                 $contacts_hash{contacts}{$type}{$item} = 0;
15398:             }
15399:         }
15400:         $others{$type} = $env{'form.'.$type.'_others'};
15401:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
15402:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15403:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
15404:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
15405:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
15406:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
15407:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
15408:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15409:             }
15410:         }
15411:     }
15412:     foreach my $item (@contacts) {
15413:         $to{$item} = $env{'form.'.$item};
15414:         $contacts_hash{'contacts'}{$item} = $to{$item};
15415:     }
15416:     foreach my $item (@toggles) {
15417:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
15418:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
15419:         }
15420:     }
15421:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
15422:     foreach my $item (@lonstatus) {
15423:         if ($item eq 'excluded') {
15424:             my (%serverhomes,@excluded);
15425:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
15426:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
15427:             if (@possexcluded) {
15428:                 foreach my $id (sort(@possexcluded)) {
15429:                     if ($serverhomes{$id}) {
15430:                         push(@excluded,$id);
15431:                     }
15432:                 }
15433:             }
15434:             if (@excluded) {
15435:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
15436:             }
15437:         } elsif ($item eq 'weights') {
15438:             foreach my $type ('E','W','N','U') {
15439:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
15440:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
15441:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
15442:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
15443:                             $env{'form.error'.$item.'_'.$type};
15444:                     }
15445:                 }
15446:             }
15447:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
15448:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
15449:             if ($env{'form.error'.$item} =~ /^\d+$/) {
15450:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
15451:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
15452:                 }
15453:             }
15454:         }
15455:     }
15456:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
15457:         foreach my $field (@{$fields}) {
15458:             if (ref($possoptions->{$field}) eq 'ARRAY') {
15459:                 my $value = $env{'form.helpform_'.$field};
15460:                 $value =~ s/^\s+|\s+$//g;
15461:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
15462:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
15463:                     if ($field eq 'screenshot') {
15464:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
15465:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
15466:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
15467:                         }
15468:                     }
15469:                 }
15470:             }
15471:         }
15472:     }
15473:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
15474:     my (@statuses,%usertypeshash,@overrides);
15475:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
15476:         @statuses = @{$types};
15477:         if (ref($usertypes) eq 'HASH') {
15478:             %usertypeshash = %{$usertypes};
15479:         }
15480:     }
15481:     if (@statuses) {
15482:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
15483:         foreach my $type (@possoverrides) {
15484:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
15485:                 push(@overrides,$type);
15486:             }
15487:         }
15488:         if (@overrides) {
15489:             foreach my $type (@overrides) {
15490:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
15491:                 foreach my $item (@contacts) {
15492:                     if (grep(/^\Q$item\E$/,@standard)) {
15493:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
15494:                         $newsetting{'override_'.$type}{$item} = 1;
15495:                     } else {
15496:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
15497:                         $newsetting{'override_'.$type}{$item} = 0;
15498:                     }
15499:                 }
15500:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
15501:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15502:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
15503:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
15504:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
15505:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
15506:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
15507:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
15508:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
15509:                 }
15510:             }     
15511:         }
15512:     }
15513:     if (keys(%currsetting) > 0) {
15514:         foreach my $item (@contacts) {
15515:             if ($to{$item} ne $currsetting{$item}) {
15516:                 $changes{$item} = 1;
15517:             }
15518:         }
15519:         foreach my $type (@mailings) {
15520:             foreach my $item (@contacts) {
15521:                 if (ref($currsetting{$type}) eq 'HASH') {
15522:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
15523:                         push(@{$changes{$type}},$item);
15524:                     }
15525:                 } else {
15526:                     push(@{$changes{$type}},@{$newsetting{$type}});
15527:                 }
15528:             }
15529:             if ($others{$type} ne $currsetting{$type}{'others'}) {
15530:                 push(@{$changes{$type}},'others');
15531:             }
15532:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15533:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
15534:                     push(@{$changes{$type}},'bcc'); 
15535:                 }
15536:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
15537:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
15538:                     push(@{$changes{$type}},'include');
15539:                 }
15540:             }
15541:         }
15542:         if (ref($fields) eq 'ARRAY') {
15543:             if (ref($currsetting{'helpform'}) eq 'HASH') {
15544:                 foreach my $field (@{$fields}) {
15545:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
15546:                         push(@{$changes{'helpform'}},$field);
15547:                     }
15548:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15549:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
15550:                             push(@{$changes{'helpform'}},'maxsize');
15551:                         }
15552:                     }
15553:                 }
15554:             } else {
15555:                 foreach my $field (@{$fields}) {
15556:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
15557:                         push(@{$changes{'helpform'}},$field);
15558:                     }
15559:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15560:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
15561:                             push(@{$changes{'helpform'}},'maxsize');
15562:                         }
15563:                     }
15564:                 }
15565:             }
15566:         }
15567:         if (@statuses) {
15568:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
15569:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
15570:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
15571:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
15572:                             foreach my $item (@contacts,'bcc','others','include') {
15573:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
15574:                                     push(@{$changes{'overrides'}},$key);
15575:                                     last;
15576:                                 }
15577:                             }
15578:                         } else {
15579:                             push(@{$changes{'overrides'}},$key);
15580:                         }
15581:                     }
15582:                 }
15583:                 foreach my $key (@overrides) {
15584:                     unless (exists($currsetting{'overrides'}{$key})) {
15585:                         push(@{$changes{'overrides'}},$key);
15586:                     }
15587:                 }
15588:             } else {
15589:                 foreach my $key (@overrides) {
15590:                     push(@{$changes{'overrides'}},$key); 
15591:                 }
15592:             }
15593:         }
15594:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
15595:             foreach my $key ('excluded','weights','threshold','sysmail') {
15596:                 if ($key eq 'excluded') {
15597:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
15598:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
15599:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
15600:                             (@{$currsetting{'lonstatus'}{$key}})) {
15601:                             my @diffs =
15602:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
15603:                                                                    $currsetting{'lonstatus'}{$key});
15604:                             if (@diffs) {
15605:                                 push(@{$changes{'lonstatus'}},$key);
15606:                             }
15607:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
15608:                             push(@{$changes{'lonstatus'}},$key);
15609:                         }
15610:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
15611:                              (@{$currsetting{'lonstatus'}{$key}})) {
15612:                         push(@{$changes{'lonstatus'}},$key);
15613:                     }
15614:                 } elsif ($key eq 'weights') {
15615:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
15616:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
15617:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
15618:                             foreach my $type ('E','W','N','U') {
15619:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
15620:                                         $currsetting{'lonstatus'}{$key}{$type}) {
15621:                                     push(@{$changes{'lonstatus'}},$key);
15622:                                     last;
15623:                                 }
15624:                             }
15625:                         } else {
15626:                             foreach my $type ('E','W','N','U') {
15627:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
15628:                                     push(@{$changes{'lonstatus'}},$key);
15629:                                     last;
15630:                                 }
15631:                             }
15632:                         }
15633:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
15634:                         foreach my $type ('E','W','N','U') {
15635:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
15636:                                 push(@{$changes{'lonstatus'}},$key);
15637:                                 last;
15638:                             }
15639:                         }
15640:                     }
15641:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
15642:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
15643:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
15644:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
15645:                                 push(@{$changes{'lonstatus'}},$key);
15646:                             }
15647:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
15648:                             push(@{$changes{'lonstatus'}},$key);
15649:                         }
15650:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
15651:                         push(@{$changes{'lonstatus'}},$key);
15652:                     }
15653:                 }
15654:             }
15655:         } else {
15656:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
15657:                 foreach my $key ('excluded','weights','threshold','sysmail') {
15658:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
15659:                         push(@{$changes{'lonstatus'}},$key);
15660:                     }
15661:                 }
15662:             }
15663:         }
15664:     } else {
15665:         my %default;
15666:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
15667:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
15668:         $default{'errormail'} = 'adminemail';
15669:         $default{'packagesmail'} = 'adminemail';
15670:         $default{'helpdeskmail'} = 'supportemail';
15671:         $default{'otherdomsmail'} = 'supportemail';
15672:         $default{'lonstatusmail'} = 'adminemail';
15673:         $default{'requestsmail'} = 'adminemail';
15674:         $default{'updatesmail'} = 'adminemail';
15675:         $default{'hostipmail'} = 'adminemail';
15676:         foreach my $item (@contacts) {
15677:            if ($to{$item} ne $default{$item}) {
15678:                $changes{$item} = 1;
15679:            }
15680:         }
15681:         foreach my $type (@mailings) {
15682:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
15683:                 push(@{$changes{$type}},@{$newsetting{$type}});
15684:             }
15685:             if ($others{$type} ne '') {
15686:                 push(@{$changes{$type}},'others');
15687:             }
15688:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15689:                 if ($bcc{$type} ne '') {
15690:                     push(@{$changes{$type}},'bcc');
15691:                 }
15692:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
15693:                     push(@{$changes{$type}},'include');
15694:                 }
15695:             }
15696:         }
15697:         if (ref($fields) eq 'ARRAY') {
15698:             foreach my $field (@{$fields}) {
15699:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
15700:                     push(@{$changes{'helpform'}},$field);
15701:                 }
15702:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
15703:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
15704:                         push(@{$changes{'helpform'}},'maxsize');
15705:                     }
15706:                 }
15707:             }
15708:         }
15709:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
15710:             foreach my $key ('excluded','weights','threshold','sysmail') {
15711:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
15712:                     push(@{$changes{'lonstatus'}},$key);
15713:                 }
15714:             }
15715:         }
15716:     }
15717:     foreach my $item (@toggles) {
15718:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
15719:             $changes{$item} = 1;
15720:         } elsif ((!$env{'form.'.$item}) &&
15721:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
15722:             $changes{$item} = 1;
15723:         }
15724:     }
15725:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
15726:                                              $dom);
15727:     if ($putresult eq 'ok') {
15728:         if (keys(%changes) > 0) {
15729:             &Apache::loncommon::devalidate_domconfig_cache($dom);
15730:             if (ref($lastactref) eq 'HASH') {
15731:                 $lastactref->{'domainconfig'} = 1;
15732:             }
15733:             my ($titles,$short_titles)  = &contact_titles();
15734:             $resulttext = &mt('Changes made:').'<ul>';
15735:             foreach my $item (@contacts) {
15736:                 if ($changes{$item}) {
15737:                     $resulttext .= '<li>'.$titles->{$item}.
15738:                                     &mt(' set to: ').
15739:                                     '<span class="LC_cusr_emph">'.
15740:                                     $to{$item}.'</span></li>';
15741:                 }
15742:             }
15743:             foreach my $type (@mailings) {
15744:                 if (ref($changes{$type}) eq 'ARRAY') {
15745:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15746:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
15747:                     } else {
15748:                         $resulttext .= '<li>'.$titles->{$type}.': ';
15749:                     }
15750:                     my @text;
15751:                     foreach my $item (@{$newsetting{$type}}) {
15752:                         push(@text,$short_titles->{$item});
15753:                     }
15754:                     if ($others{$type} ne '') {
15755:                         push(@text,$others{$type});
15756:                     }
15757:                     if (@text) {
15758:                         $resulttext .= '<span class="LC_cusr_emph">'.
15759:                                        join(', ',@text).'</span>';
15760:                     }
15761:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
15762:                         if ($bcc{$type} ne '') {
15763:                             my $bcctext;
15764:                             if (@text) {
15765:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
15766:                             } else {
15767:                                 $bcctext = '(Bcc)';
15768:                             }
15769:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
15770:                         } elsif (!@text) {
15771:                             $resulttext .= &mt('No one');
15772:                         }   
15773:                         if ($includestr{$type} ne '') {
15774:                             if ($includeloc{$type} eq 'b') {
15775:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
15776:                             } elsif ($includeloc{$type} eq 's') {
15777:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
15778:                             }
15779:                         }
15780:                     } elsif (!@text) {
15781:                         $resulttext .= &mt('No recipients');
15782:                     }
15783:                     $resulttext .= '</li>';
15784:                 }
15785:             }
15786:             if (ref($changes{'overrides'}) eq 'ARRAY') {
15787:                 my @deletions;
15788:                 foreach my $type (@{$changes{'overrides'}}) {
15789:                     if ($usertypeshash{$type}) {
15790:                         if (grep(/^\Q$type\E/,@overrides)) {
15791:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
15792:                                                       $usertypeshash{$type}).'<ul><li>';
15793:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
15794:                                 my @text;
15795:                                 foreach my $item (@contacts) {
15796:                                     if ($newsetting{'override_'.$type}{$item}) { 
15797:                                         push(@text,$short_titles->{$item});
15798:                                     }
15799:                                 }
15800:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
15801:                                     push(@text,$newsetting{'override_'.$type}{'others'});
15802:                                 }
15803:   
15804:                                 if (@text) {
15805:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
15806:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
15807:                                 }
15808:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
15809:                                     my $bcctext;
15810:                                     if (@text) {
15811:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
15812:                                     } else {
15813:                                         $bcctext = '(Bcc)';
15814:                                     }
15815:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
15816:                                 } elsif (!@text) {
15817:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
15818:                                 }
15819:                                 $resulttext .= '</li>';
15820:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
15821:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
15822:                                     if ($loc eq 'b') {
15823:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
15824:                                     } elsif ($loc eq 's') {
15825:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
15826:                                     }
15827:                                 }
15828:                             }
15829:                             $resulttext .= '</li></ul></li>';
15830:                         } else {
15831:                             push(@deletions,$usertypeshash{$type});
15832:                         }
15833:                     }
15834:                 }
15835:                 if (@deletions) {
15836:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
15837:                                               join(', ',@deletions)).'</li>';
15838:                 }
15839:             }
15840:             my @offon = ('off','on');
15841:             my $corelink = &core_link_msu();
15842:             if ($changes{'reporterrors'}) {
15843:                 $resulttext .= '<li>'.
15844:                                &mt('E-mail error reports to [_1] set to "'.
15845:                                    $offon[$env{'form.reporterrors'}].'".',
15846:                                    $corelink).
15847:                                '</li>';
15848:             }
15849:             if ($changes{'reportupdates'}) {
15850:                 $resulttext .= '<li>'.
15851:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
15852:                                     $offon[$env{'form.reportupdates'}].'".',
15853:                                     $corelink).
15854:                                 '</li>';
15855:             }
15856:             if ($changes{'reportstatus'}) {
15857:                 $resulttext .= '<li>'.
15858:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
15859:                                     $offon[$env{'form.reportstatus'}].'".',
15860:                                     $corelink).
15861:                                 '</li>';
15862:             }
15863:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
15864:                 $resulttext .= '<li>'.
15865:                                &mt('Nightly status check e-mail settings').':<ul>';
15866:                 my (%defval,%use_def,%shown);
15867:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
15868:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
15869:                 $defval{'weights'} =
15870:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
15871:                 $defval{'excluded'} = &mt('None');
15872:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
15873:                     foreach my $item ('threshold','sysmail','weights','excluded') {
15874:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
15875:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
15876:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
15877:                             } elsif ($item eq 'weights') {
15878:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
15879:                                     foreach my $type ('E','W','N','U') {
15880:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
15881:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
15882:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
15883:                                         } else {
15884:                                             $shown{$item} .= $lonstatus_defs->{$type};
15885:                                         }
15886:                                         $shown{$item} .= ', ';
15887:                                     }
15888:                                     $shown{$item} =~ s/, $//;
15889:                                 } else {
15890:                                     $shown{$item} = $defval{$item};
15891:                                 }
15892:                             } elsif ($item eq 'excluded') {
15893:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
15894:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
15895:                                 } else {
15896:                                     $shown{$item} = $defval{$item};
15897:                                 }
15898:                             }
15899:                         } else {
15900:                             $shown{$item} = $defval{$item};
15901:                         }
15902:                     }
15903:                 } else {
15904:                     foreach my $item ('threshold','weights','excluded','sysmail') {
15905:                         $shown{$item} = $defval{$item};
15906:                     }
15907:                 }
15908:                 foreach my $item ('threshold','weights','excluded','sysmail') {
15909:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
15910:                                           $shown{$item}).'</li>';
15911:                 }
15912:                 $resulttext .= '</ul></li>';
15913:             }
15914:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
15915:                 my (@optional,@required,@unused,$maxsizechg);
15916:                 foreach my $field (@{$changes{'helpform'}}) {
15917:                     if ($field eq 'maxsize') {
15918:                         $maxsizechg = 1;
15919:                         next;
15920:                     }
15921:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
15922:                         push(@optional,$field);
15923:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
15924:                         push(@unused,$field);
15925:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
15926:                         push(@required,$field);
15927:                     }
15928:                 }
15929:                 if (@optional) {
15930:                     $resulttext .= '<li>'.
15931:                                    &mt('Help form fields changed to "Optional": [_1].',
15932:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
15933:                                    '</li>';
15934:                 }
15935:                 if (@required) {
15936:                     $resulttext .= '<li>'.
15937:                                    &mt('Help form fields changed to "Required": [_1].',
15938:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
15939:                                    '</li>';
15940:                 }
15941:                 if (@unused) {
15942:                     $resulttext .= '<li>'.
15943:                                    &mt('Help form fields changed to "Not shown": [_1].',
15944:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
15945:                                    '</li>';
15946:                 }
15947:                 if ($maxsizechg) {
15948:                     $resulttext .= '<li>'.
15949:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
15950:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
15951:                                    '</li>';
15952:                 }
15953:             }
15954:             $resulttext .= '</ul>';
15955:         } else {
15956:             $resulttext = &mt('No changes made to contacts and form settings');
15957:         }
15958:     } else {
15959:         $resulttext = '<span class="LC_error">'.
15960:             &mt('An error occurred: [_1].',$putresult).'</span>';
15961:     }
15962:     return $resulttext;
15963: }
15964: 
15965: sub modify_privacy {
15966:     my ($dom,%domconfig) = @_;
15967:     my ($resulttext,%current,%changes);
15968:     if (ref($domconfig{'privacy'}) eq 'HASH') {
15969:         %current = %{$domconfig{'privacy'}};
15970:     }
15971:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
15972:     my @items = ('domain','author','course','community');
15973:     my %names = &Apache::lonlocal::texthash (
15974:                    domain => 'Assigned domain role(s)',
15975:                    author => 'Assigned co-author role(s)',
15976:                    course => 'Assigned course role(s)',
15977:                    community => 'Assigned community role',
15978:                 );
15979:     my %roles = &Apache::lonlocal::texthash (
15980:                    domain => 'Domain role',
15981:                    author => 'Co-author role',
15982:                    course => 'Course role',
15983:                    community => 'Community role',
15984:                 );
15985:     my %titles = &Apache::lonlocal::texthash (
15986:                   approval => 'Approval for role in different domain',
15987:                   othdom   => 'User information available in other domain',
15988:                   priv     => 'Information viewable by privileged user in same domain',
15989:                   unpriv   => 'Information viewable by unprivileged user in same domain',
15990:                   instdom  => 'Other domain shares institution/provider',
15991:                   extdom   => 'Other domain has different institution/provider',
15992:                   none     => 'Not allowed',
15993:                   user     => 'User authorizes',
15994:                   domain   => 'Domain Coordinator authorizes',
15995:                   auto     => 'Unrestricted',
15996:     );
15997:     my %fieldnames = &Apache::lonlocal::texthash (
15998:                         id => 'Student/Employee ID',
15999:                         permanentemail => 'E-mail address',
16000:                         lastname => 'Last Name',
16001:                         firstname => 'First Name',
16002:                         middlename => 'Middle Name',
16003:                         generation => 'Generation',
16004:     );
16005:     my ($othertitle,$usertypes,$types) =
16006:         &Apache::loncommon::sorted_inst_types($dom);
16007:     my (%by_ip,%by_location,@intdoms,@instdoms);
16008:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
16009: 
16010:     my %privacyhash = (
16011:                        'approval' => {
16012:                                        instdom => {},
16013:                                        extdom  => {},
16014:                                      },
16015:                        'othdom'   => {},
16016:                        'priv'     => {},
16017:                        'unpriv'   => {},
16018:                       );
16019:     foreach my $item (@items) {
16020:         if (@instdoms > 1) {
16021:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
16022:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
16023:             }
16024:             if (ref($current{'approval'}) eq 'HASH') {
16025:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
16026:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
16027:                         $changes{'approval'} = 1;
16028:                     }
16029:                 }
16030:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
16031:                 $changes{'approval'} = 1;
16032:             }
16033:         }
16034:         if (keys(%by_location) > 0) {
16035:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
16036:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
16037:             }
16038:             if (ref($current{'approval'}) eq 'HASH') {
16039:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
16040:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
16041:                         $changes{'approval'} = 1;
16042:                     }
16043:                 }
16044:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
16045:                 $changes{'approval'} = 1;
16046:             }
16047:         }
16048:         foreach my $status ('priv','unpriv') {
16049:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
16050:             my @newvalues;
16051:             foreach my $field (@possibles) {
16052:                 if (grep(/^\Q$field\E$/,@fields)) {
16053:                     $privacyhash{$status}{$item}{$field} = 1;
16054:                     push(@newvalues,$field);
16055:                 }
16056:             }
16057:             @newvalues = sort(@newvalues);
16058:             if (ref($current{$status}) eq 'HASH') {
16059:                 if (ref($current{$status}{$item}) eq 'HASH') {
16060:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
16061:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16062:                     if (@diffs > 0) {
16063:                         $changes{$status} = 1;
16064:                     }
16065:                 }
16066:             } else {
16067:                 my @stdfields;
16068:                 foreach my $field (@fields) {
16069:                     if ($field eq 'id') {
16070:                         next if ($status eq 'unpriv');
16071:                         next if (($status eq 'priv') && ($item eq 'community'));
16072:                     }
16073:                     push(@stdfields,$field);
16074:                 }
16075:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16076:                 if (@diffs > 0) {
16077:                     $changes{$status} = 1;
16078:                 }
16079:             }
16080:         }
16081:     }
16082:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
16083:         my @statuses;
16084:         if (ref($types) eq 'ARRAY') {
16085:             @statuses = @{$types};
16086:         }
16087:         foreach my $type (@statuses,'default') {
16088:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
16089:             my @newvalues;
16090:             foreach my $field (sort(@possfields)) {
16091:                 if (grep(/^\Q$field\E$/,@fields)) {
16092:                     $privacyhash{'othdom'}{$type}{$field} = 1;
16093:                     push(@newvalues,$field);
16094:                 }
16095:             }
16096:             @newvalues = sort(@newvalues);
16097:             if (ref($current{'othdom'}) eq 'HASH') {
16098:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
16099:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
16100:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
16101:                     if (@diffs > 0) {
16102:                         $changes{'othdom'} = 1;
16103:                     }
16104:                 }
16105:             } else {
16106:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
16107:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
16108:                 if (@diffs > 0) {
16109:                     $changes{'othdom'} = 1;
16110:                 }
16111:             }
16112:         }
16113:     }
16114:     my %confighash = (
16115:                         privacy => \%privacyhash,
16116:                      );
16117:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16118:     if ($putresult eq 'ok') {
16119:         if (keys(%changes) > 0) {
16120:             $resulttext = &mt('Changes made: ').'<ul>';
16121:             foreach my $key ('approval','othdom','priv','unpriv') {
16122:                 if ($changes{$key}) {
16123:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16124:                     if ($key eq 'approval') {
16125:                         if (keys(%{$privacyhash{$key}{instdom}})) {
16126:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
16127:                             foreach my $item (@items) {
16128:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
16129:                             }
16130:                             $resulttext .= '</ul></li>';
16131:                         }
16132:                         if (keys(%{$privacyhash{$key}{extdom}})) {
16133:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
16134:                             foreach my $item (@items) {
16135:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
16136:                             }
16137:                             $resulttext .= '</ul></li>';
16138:                         }
16139:                     } elsif ($key eq 'othdom') {
16140:                         my @statuses;
16141:                         if (ref($types) eq 'ARRAY') {
16142:                             @statuses = @{$types};
16143:                         }
16144:                         if (ref($privacyhash{$key}) eq 'HASH') {
16145:                             foreach my $status (@statuses,'default') {
16146:                                 if ($status eq 'default') {
16147:                                     $resulttext .= '<li>'.$othertitle.': ';
16148:                                 } elsif (ref($usertypes) eq 'HASH') {
16149:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
16150:                                 } else {
16151:                                     next;
16152:                                 }
16153:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
16154:                                     if (keys(%{$privacyhash{$key}{$status}})) {
16155:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
16156:                                     } else {
16157:                                         $resulttext .= &mt('none');
16158:                                     }
16159:                                 }
16160:                                 $resulttext .= '</li>';
16161:                             }
16162:                         }
16163:                     } else {
16164:                         foreach my $item (@items) {
16165:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
16166:                                 $resulttext .= '<li>'.$names{$item}.': ';
16167:                                 if (keys(%{$privacyhash{$key}{$item}})) {
16168:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
16169:                                 } else {
16170:                                     $resulttext .= &mt('none');
16171:                                 }
16172:                                 $resulttext .= '</li>';
16173:                             }
16174:                         }
16175:                     }
16176:                     $resulttext .= '</ul></li>';
16177:                 }
16178:             }
16179:         } else {
16180:             $resulttext = &mt('No changes made to user information settings');
16181:         }
16182:     } else {
16183:         $resulttext = '<span class="LC_error">'.
16184:             &mt('An error occurred: [_1]',$putresult).'</span>';
16185:     }
16186:     return $resulttext;
16187: }
16188: 
16189: sub modify_passwords {
16190:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
16191:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
16192:         $updatedefaults,$updateconf);
16193:     my $customfn = 'resetpw.html';
16194:     if (ref($domconfig{'passwords'}) eq 'HASH') {
16195:         %current = %{$domconfig{'passwords'}};
16196:     }
16197:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16198:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16199:     if (ref($types) eq 'ARRAY') {
16200:         @oktypes = @{$types};
16201:     }
16202:     push(@oktypes,'default');
16203: 
16204:     my %titles = &Apache::lonlocal::texthash (
16205:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
16206:         intauth_check  => 'Check bcrypt cost if authenticated',
16207:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
16208:         permanent      => 'Permanent e-mail address',
16209:         critical       => 'Critical notification address',
16210:         notify         => 'Notification address',
16211:         min            => 'Minimum password length',
16212:         max            => 'Maximum password length',
16213:         chars          => 'Required characters',
16214:         expire         => 'Password expiration (days)',
16215:         numsaved       => 'Number of previous passwords to save',
16216:         reset          => 'Resetting Forgotten Password',
16217:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
16218:         rules          => 'Rules for LON-CAPA Passwords',
16219:         crsownerchg    => 'Course Owner Changing Student Passwords',
16220:         username       => 'Username',
16221:         email          => 'E-mail address',
16222:     );
16223: 
16224: #
16225: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
16226: #
16227:     my (%curr_defaults,%save_defaults);
16228:     if (ref($domconfig{'defaults'}) eq 'HASH') {
16229:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
16230:             if ($key =~ /^intauth_(cost|check|switch)$/) {
16231:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
16232:             } else {
16233:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
16234:             }
16235:         }
16236:     }
16237:     my %staticdefaults = (
16238:         'resetlink'      => 2,
16239:         'resetcase'      => \@oktypes,
16240:         'resetprelink'   => 'both',
16241:         'resetemail'     => ['critical','notify','permanent'],
16242:         'intauth_cost'   => 10,
16243:         'intauth_check'  => 0,
16244:         'intauth_switch' => 0,
16245:     );
16246:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
16247:     foreach my $type (@oktypes) {
16248:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
16249:     }
16250:     my $linklife = $env{'form.passwords_link'};
16251:     $linklife =~ s/^\s+|\s+$//g;
16252:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
16253:         $newvalues{'resetlink'} = $linklife;
16254:         if ($current{'resetlink'}) {
16255:             if ($current{'resetlink'} ne $linklife) {
16256:                 $changes{'reset'} = 1;
16257:             }
16258:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16259:             if ($staticdefaults{'resetlink'} ne $linklife) {
16260:                 $changes{'reset'} = 1;
16261:             }
16262:         }
16263:     } elsif ($current{'resetlink'}) {
16264:         $changes{'reset'} = 1;
16265:     }
16266:     my @casesens;
16267:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
16268:     foreach my $case (sort(@posscase)) {
16269:         if (grep(/^\Q$case\E$/,@oktypes)) {
16270:             push(@casesens,$case);
16271:         }
16272:     }
16273:     $newvalues{'resetcase'} = \@casesens;
16274:     if (ref($current{'resetcase'}) eq 'ARRAY') {
16275:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
16276:         if (@diffs > 0) {
16277:             $changes{'reset'} = 1;
16278:         }
16279:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16280:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
16281:         if (@diffs > 0) {
16282:             $changes{'reset'} = 1;
16283:         }
16284:     }
16285:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
16286:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
16287:         if (exists($current{'resetprelink'})) {
16288:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
16289:                 $changes{'reset'} = 1;
16290:             }
16291:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16292:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
16293:                 $changes{'reset'} = 1;
16294:             }
16295:         }
16296:     } elsif ($current{'resetprelink'}) {
16297:         $changes{'reset'} = 1;
16298:     }
16299:     foreach my $type (@oktypes) {
16300:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
16301:         my @postlink;
16302:         foreach my $item (sort(@possplink)) {
16303:             if ($item =~ /^(email|username)$/) {
16304:                 push(@postlink,$item);
16305:             }
16306:         }
16307:         $newvalues{'resetpostlink'}{$type} = \@postlink;
16308:         unless ($changes{'reset'}) {
16309:             if (ref($current{'resetpostlink'}) eq 'HASH') {
16310:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
16311:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
16312:                     if (@diffs > 0) {
16313:                         $changes{'reset'} = 1;
16314:                     }
16315:                 } else {
16316:                     $changes{'reset'} = 1;
16317:                 }
16318:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16319:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
16320:                 if (@diffs > 0) {
16321:                     $changes{'reset'} = 1;
16322:                 }
16323:             }
16324:         }
16325:     }
16326:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
16327:     my @resetemail;
16328:     foreach my $item (sort(@possemailsrc)) {
16329:         if ($item =~ /^(permanent|critical|notify)$/) {
16330:             push(@resetemail,$item);
16331:         }
16332:     }
16333:     $newvalues{'resetemail'} = \@resetemail;
16334:     unless ($changes{'reset'}) {
16335:         if (ref($current{'resetemail'}) eq 'ARRAY') {
16336:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
16337:             if (@diffs > 0) {
16338:                 $changes{'reset'} = 1;
16339:             }
16340:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
16341:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
16342:             if (@diffs > 0) {
16343:                 $changes{'reset'} = 1;
16344:             }
16345:         }
16346:     }
16347:     if ($env{'form.passwords_stdtext'} == 0) {
16348:         $newvalues{'resetremove'} = 1;
16349:         unless ($current{'resetremove'}) {
16350:             $changes{'reset'} = 1;
16351:         }
16352:     } elsif ($current{'resetremove'}) {
16353:         $changes{'reset'} = 1;
16354:     }
16355:     if ($env{'form.passwords_customfile.filename'} ne '') {
16356:         my $servadm = $r->dir_config('lonAdmEMail');
16357:         my ($configuserok,$author_ok,$switchserver) =
16358:             &config_check($dom,$confname,$servadm);
16359:         my $error;
16360:         if ($configuserok eq 'ok') {
16361:             if ($switchserver) {
16362:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
16363:             } else {
16364:                 if ($author_ok eq 'ok') {
16365:                     my ($result,$customurl) =
16366:                         &publishlogo($r,'upload','passwords_customfile',$dom,
16367:                                      $confname,'customtext/resetpw','','',$customfn);
16368:                     if ($result eq 'ok') {
16369:                         $newvalues{'resetcustom'} = $customurl;
16370:                         $changes{'reset'} = 1;
16371:                     } else {
16372:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
16373:                     }
16374:                 } else {
16375:                     $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);
16376:                 }
16377:             }
16378:         } else {
16379:             $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);
16380:         }
16381:         if ($error) {
16382:             &Apache::lonnet::logthis($error);
16383:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16384:         }
16385:     } elsif ($current{'resetcustom'}) {
16386:         if ($env{'form.passwords_custom_del'}) {
16387:             $changes{'reset'} = 1;
16388:         } else {
16389:             $newvalues{'resetcustom'} = $current{'resetcustom'};
16390:         }
16391:     }
16392:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
16393:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
16394:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
16395:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
16396:             $changes{'intauth'} = 1;
16397:         }
16398:     } else {
16399:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
16400:     }
16401:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
16402:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
16403:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
16404:             $changes{'intauth'} = 1;
16405:         }
16406:     } else {
16407:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16408:     }
16409:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
16410:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
16411:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
16412:             $changes{'intauth'} = 1;
16413:         }
16414:     } else {
16415:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
16416:     }
16417:     foreach my $item ('cost','check','switch') {
16418:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
16419:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
16420:             $updatedefaults = 1;
16421:         }
16422:     }
16423:     foreach my $rule ('min','max','expire','numsaved') {
16424:         $env{'form.passwords_'.$rule} =~ s/^\s+|\s+$//g;
16425:         my $ruleok;
16426:         if ($rule eq 'expire') {
16427:             if (($env{'form.passwords_'.$rule} =~ /^\d+(|\.\d*)$/) &&
16428:                 ($env{'form.passwords_'.$rule} ne '0')) {
16429:                 $ruleok = 1;
16430:             }
16431:         } elsif ($rule eq 'min') {
16432:             if ($env{'form.passwords_'.$rule} =~ /^\d+$/) {
16433:                 if ($env{'form.passwords_'.$rule} >= $Apache::lonnet::passwdmin) {
16434:                     $ruleok = 1;
16435:                 }
16436:             }
16437:         } elsif (($env{'form.passwords_'.$rule} =~ /^\d+$/) &&
16438:                  ($env{'form.passwords_'.$rule} ne '0')) {
16439:             $ruleok = 1;
16440:         }
16441:         if ($ruleok) {
16442:             $newvalues{$rule} = $env{'form.passwords_'.$rule};
16443:             if (exists($current{$rule})) {
16444:                 if ($newvalues{$rule} ne $current{$rule}) {
16445:                     $changes{'rules'} = 1;
16446:                 }
16447:             } elsif ($rule eq 'min') {
16448:                 if ($staticdefaults{$rule} ne $newvalues{$rule}) {
16449:                     $changes{'rules'} = 1;
16450:                 }
16451:             } else {
16452:                 $changes{'rules'} = 1;
16453:             }
16454:         } elsif (exists($current{$rule})) {
16455:             $changes{'rules'} = 1;
16456:         }
16457:     }
16458:     my @posschars = &Apache::loncommon::get_env_multiple('form.passwords_chars');
16459:     my @chars;
16460:     foreach my $item (sort(@posschars)) {
16461:         if ($item =~ /^(uc|lc|num|spec)$/) {
16462:             push(@chars,$item);
16463:         }
16464:     }
16465:     $newvalues{'chars'} = \@chars;
16466:     unless ($changes{'rules'}) {
16467:         if (ref($current{'chars'}) eq 'ARRAY') {
16468:             my @diffs = &Apache::loncommon::compare_arrays($current{'chars'},\@chars);
16469:             if (@diffs > 0) {
16470:                 $changes{'rules'} = 1;
16471:             }
16472:         } else {
16473:             if (@chars > 0) {
16474:                 $changes{'rules'} = 1;
16475:             }
16476:         }
16477:     }
16478:     my %crsownerchg = (
16479:                         by => [],
16480:                         for => [],
16481:                       );
16482:     foreach my $item ('by','for') {
16483:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
16484:         foreach my $type (sort(@posstypes)) {
16485:             if (grep(/^\Q$type\E$/,@oktypes)) {
16486:                 push(@{$crsownerchg{$item}},$type);
16487:             }
16488:         }
16489:     }
16490:     $newvalues{'crsownerchg'} = \%crsownerchg;
16491:     if (ref($current{'crsownerchg'}) eq 'HASH') {
16492:         foreach my $item ('by','for') {
16493:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
16494:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
16495:                 if (@diffs > 0) {
16496:                     $changes{'crsownerchg'} = 1;
16497:                     last;
16498:                 }
16499:             }
16500:         }
16501:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
16502:         foreach my $item ('by','for') {
16503:             if (@{$crsownerchg{$item}} > 0) {
16504:                 $changes{'crsownerchg'} = 1;
16505:                 last;
16506:             }
16507:         }
16508:     }
16509: 
16510:     my %confighash = (
16511:                         defaults  => \%save_defaults,
16512:                         passwords => \%newvalues,
16513:                      );
16514:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
16515: 
16516:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
16517:     if ($putresult eq 'ok') {
16518:         if (keys(%changes) > 0) {
16519:             $resulttext = &mt('Changes made: ').'<ul>';
16520:             foreach my $key ('reset','intauth','rules','crsownerchg') {
16521:                 if ($changes{$key}) {
16522:                     unless ($key eq 'intauth') {
16523:                         $updateconf = 1;
16524:                     }
16525:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
16526:                     if ($key eq 'reset') {
16527:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
16528:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
16529:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
16530:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
16531:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
16532:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
16533:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
16534:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
16535:                             }
16536:                         } else {
16537:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
16538:                         }
16539:                         if ($confighash{'passwords'}{'resetlink'}) {
16540:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
16541:                         } else {
16542:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
16543:                                                   &mt('Will default to 2 hours').'</li>';
16544:                         }
16545:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
16546:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
16547:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
16548:                             } else {
16549:                                 my $casesens;
16550:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
16551:                                     if ($type eq 'default') {
16552:                                         $casesens .= $othertitle.', ';
16553:                                     } elsif ($usertypes->{$type} ne '') {
16554:                                         $casesens .= $usertypes->{$type}.', ';
16555:                                     }
16556:                                 }
16557:                                 $casesens =~ s/\Q, \E$//;
16558:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
16559:                             }
16560:                         } else {
16561:                             $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>';
16562:                         }
16563:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
16564:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
16565:                         } else {
16566:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
16567:                         }
16568:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
16569:                             my $output;
16570:                             if (ref($types) eq 'ARRAY') {
16571:                                 foreach my $type (@{$types}) {
16572:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
16573:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
16574:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
16575:                                         } else {
16576:                                             $output .= $usertypes->{$type}.' -- '.
16577:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
16578:                                         }
16579:                                     }
16580:                                 }
16581:                             }
16582:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
16583:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
16584:                                     $output .= $othertitle.' -- '.&mt('none');
16585:                                 } else {
16586:                                     $output .= $othertitle.' -- '.
16587:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
16588:                                 }
16589:                             }
16590:                             if ($output) {
16591:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
16592:                             } else {
16593:                                 $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>';
16594:                             }
16595:                         } else {
16596:                             $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>';
16597:                         }
16598:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
16599:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
16600:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
16601:                             } else {
16602:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
16603:                             }
16604:                         } else {
16605:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
16606:                         }
16607:                         if ($confighash{'passwords'}{'resetremove'}) {
16608:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
16609:                         } else {
16610:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
16611:                         }
16612:                         if ($confighash{'passwords'}{'resetcustom'}) {
16613:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
16614:                                                                             &mt('custom text'),600,500,undef,undef,
16615:                                                                             undef,undef,'background-color:#ffffff');
16616:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
16617:                         } else {
16618:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
16619:                         }
16620:                     } elsif ($key eq 'intauth') {
16621:                         foreach my $item ('cost','switch','check') {
16622:                             my $value = $save_defaults{$key.'_'.$item};
16623:                             if ($item eq 'switch') {
16624:                                 my %optiondesc = &Apache::lonlocal::texthash (
16625:                                                      0 => 'No',
16626:                                                      1 => 'Yes',
16627:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
16628:                                                  );
16629:                                 if ($value =~ /^(0|1|2)$/) {
16630:                                     $value = $optiondesc{$value};
16631:                                 } else {
16632:                                     $value = &mt('none -- defaults to No');
16633:                                 }
16634:                             } elsif ($item eq 'check') {
16635:                                 my %optiondesc = &Apache::lonlocal::texthash (
16636:                                                      0 => 'No',
16637:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
16638:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
16639:                                                  );
16640:                                 if ($value =~ /^(0|1|2)$/) {
16641:                                     $value = $optiondesc{$value};
16642:                                 } else {
16643:                                     $value = &mt('none -- defaults to No');
16644:                                 }
16645:                             }
16646:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
16647:                         }
16648:                     } elsif ($key eq 'rules') {
16649:                         foreach my $rule ('min','max','expire','numsaved') {
16650:                             if ($confighash{'passwords'}{$rule} eq '') {
16651:                                 if ($rule eq 'min') {
16652:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
16653:                                                    ' '.&mt('Default of [_1] will be used',
16654:                                                            $Apache::lonnet::passwdmin).'</li>';
16655:                                 } else {
16656:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
16657:                                 }
16658:                             } else {
16659:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
16660:                             }
16661:                         }
16662:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
16663:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
16664:                                 my %rulenames = &Apache::lonlocal::texthash(
16665:                                                      uc => 'At least one upper case letter',
16666:                                                      lc => 'At least one lower case letter',
16667:                                                      num => 'At least one number',
16668:                                                      spec => 'At least one non-alphanumeric',
16669:                                                    );
16670:                                 my $needed = '<ul><li>'.
16671:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
16672:                                              '</li></ul>'; 
16673:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
16674:                             } else {
16675:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16676:                             }
16677:                         } else {
16678:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16679:                         }
16680:                     } elsif ($key eq 'crsownerchg') {
16681:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
16682:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
16683:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
16684:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
16685:                             } else {
16686:                                 my %crsownerstr;
16687:                                 foreach my $item ('by','for') {
16688:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
16689:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
16690:                                             if ($type eq 'default') {
16691:                                                 $crsownerstr{$item} .= $othertitle.', ';
16692:                                             } elsif ($usertypes->{$type} ne '') {
16693:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
16694:                                             }
16695:                                         }
16696:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
16697:                                     }
16698:                                 }
16699:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
16700:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
16701:                             }
16702:                         } else {
16703:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
16704:                         }
16705:                     }
16706:                     $resulttext .= '</ul></li>';
16707:                 }
16708:             }
16709:             $resulttext .= '</ul>';
16710:         } else {
16711:             $resulttext = &mt('No changes made to password settings');
16712:         }
16713:         my $cachetime = 24*60*60;
16714:         if ($updatedefaults) {
16715:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
16716:             if (ref($lastactref) eq 'HASH') {
16717:                 $lastactref->{'domdefaults'} = 1;
16718:             }
16719:         }
16720:         if ($updateconf) {
16721:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
16722:             if (ref($lastactref) eq 'HASH') {
16723:                 $lastactref->{'passwdconf'} = 1;
16724:             }
16725:         }
16726:     } else {
16727:         $resulttext = '<span class="LC_error">'.
16728:             &mt('An error occurred: [_1]',$putresult).'</span>';
16729:     }
16730:     if ($errors) {
16731:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
16732:                        $errors.'</ul></p>';
16733:     }
16734:     return $resulttext;
16735: }
16736: 
16737: sub modify_usercreation {
16738:     my ($dom,%domconfig) = @_;
16739:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
16740:     my $warningmsg;
16741:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
16742:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
16743:             if ($key eq 'cancreate') {
16744:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
16745:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
16746:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
16747:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16748:                         } else {
16749:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16750:                         }
16751:                     }
16752:                 }
16753:             } elsif ($key eq 'email_rule') {
16754:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
16755:             } else {
16756:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
16757:             }
16758:         }
16759:     }
16760:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
16761:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
16762:     my @contexts = ('author','course','requestcrs');
16763:     foreach my $item(@contexts) {
16764:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
16765:     }
16766:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
16767:         foreach my $item (@contexts) {
16768:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
16769:                 push(@{$changes{'cancreate'}},$item);
16770:             }
16771:         }
16772:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
16773:         foreach my $item (@contexts) {
16774:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
16775:                 if ($cancreate{$item} ne 'any') {
16776:                     push(@{$changes{'cancreate'}},$item);
16777:                 }
16778:             } else {
16779:                 if ($cancreate{$item} ne 'none') {
16780:                     push(@{$changes{'cancreate'}},$item);
16781:                 }
16782:             }
16783:         }
16784:     } else {
16785:         foreach my $item (@contexts)  {
16786:             push(@{$changes{'cancreate'}},$item);
16787:         }
16788:     }
16789: 
16790:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
16791:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
16792:             if (!grep(/^\Q$type\E$/,@username_rule)) {
16793:                 push(@{$changes{'username_rule'}},$type);
16794:             }
16795:         }
16796:         foreach my $type (@username_rule) {
16797:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
16798:                 push(@{$changes{'username_rule'}},$type);
16799:             }
16800:         }
16801:     } else {
16802:         push(@{$changes{'username_rule'}},@username_rule);
16803:     }
16804: 
16805:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
16806:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
16807:             if (!grep(/^\Q$type\E$/,@id_rule)) {
16808:                 push(@{$changes{'id_rule'}},$type);
16809:             }
16810:         }
16811:         foreach my $type (@id_rule) {
16812:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
16813:                 push(@{$changes{'id_rule'}},$type);
16814:             }
16815:         }
16816:     } else {
16817:         push(@{$changes{'id_rule'}},@id_rule);
16818:     }
16819: 
16820:     my @authen_contexts = ('author','course','domain');
16821:     my @authtypes = ('int','krb4','krb5','loc','lti');
16822:     my %authhash;
16823:     foreach my $item (@authen_contexts) {
16824:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
16825:         foreach my $auth (@authtypes) {
16826:             if (grep(/^\Q$auth\E$/,@authallowed)) {
16827:                 $authhash{$item}{$auth} = 1;
16828:             } else {
16829:                 $authhash{$item}{$auth} = 0;
16830:             }
16831:         }
16832:     }
16833:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
16834:         foreach my $item (@authen_contexts) {
16835:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
16836:                 foreach my $auth (@authtypes) {
16837:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
16838:                         push(@{$changes{'authtypes'}},$item);
16839:                         last;
16840:                     }
16841:                 }
16842:             }
16843:         }
16844:     } else {
16845:         foreach my $item (@authen_contexts) {
16846:             push(@{$changes{'authtypes'}},$item);
16847:         }
16848:     }
16849: 
16850:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
16851:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
16852:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
16853:     $save_usercreate{'id_rule'} = \@id_rule;
16854:     $save_usercreate{'username_rule'} = \@username_rule,
16855:     $save_usercreate{'authtypes'} = \%authhash;
16856: 
16857:     my %usercreation_hash =  (
16858:         usercreation     => \%save_usercreate,
16859:     );
16860: 
16861:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
16862:                                              $dom);
16863: 
16864:     if ($putresult eq 'ok') {
16865:         if (keys(%changes) > 0) {
16866:             $resulttext = &mt('Changes made:').'<ul>';
16867:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
16868:                 my %lt = &usercreation_types();
16869:                 foreach my $type (@{$changes{'cancreate'}}) {
16870:                     my $chgtext = $lt{$type}.', ';
16871:                     if ($cancreate{$type} eq 'none') {
16872:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
16873:                     } elsif ($cancreate{$type} eq 'any') {
16874:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
16875:                     } elsif ($cancreate{$type} eq 'official') {
16876:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
16877:                     } elsif ($cancreate{$type} eq 'unofficial') {
16878:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
16879:                     }
16880:                     $resulttext .= '<li>'.$chgtext.'</li>';
16881:                 }
16882:             }
16883:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
16884:                 my ($rules,$ruleorder) = 
16885:                     &Apache::lonnet::inst_userrules($dom,'username');
16886:                 my $chgtext = '<ul>';
16887:                 foreach my $type (@username_rule) {
16888:                     if (ref($rules->{$type}) eq 'HASH') {
16889:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
16890:                     }
16891:                 }
16892:                 $chgtext .= '</ul>';
16893:                 if (@username_rule > 0) {
16894:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
16895:                 } else {
16896:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
16897:                 }
16898:             }
16899:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
16900:                 my ($idrules,$idruleorder) = 
16901:                     &Apache::lonnet::inst_userrules($dom,'id');
16902:                 my $chgtext = '<ul>';
16903:                 foreach my $type (@id_rule) {
16904:                     if (ref($idrules->{$type}) eq 'HASH') {
16905:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
16906:                     }
16907:                 }
16908:                 $chgtext .= '</ul>';
16909:                 if (@id_rule > 0) {
16910:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
16911:                 } else {
16912:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
16913:                 }
16914:             }
16915:             my %authname = &authtype_names();
16916:             my %context_title = &context_names();
16917:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
16918:                 my $chgtext = '<ul>';
16919:                 foreach my $type (@{$changes{'authtypes'}}) {
16920:                     my @allowed;
16921:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
16922:                     foreach my $auth (@authtypes) {
16923:                         if ($authhash{$type}{$auth}) {
16924:                             push(@allowed,$authname{$auth});
16925:                         }
16926:                     }
16927:                     if (@allowed > 0) {
16928:                         $chgtext .= join(', ',@allowed).'</li>';
16929:                     } else {
16930:                         $chgtext .= &mt('none').'</li>';
16931:                     }
16932:                 }
16933:                 $chgtext .= '</ul>';
16934:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
16935:                 $resulttext .= '</li>';
16936:             }
16937:             $resulttext .= '</ul>';
16938:         } else {
16939:             $resulttext = &mt('No changes made to user creation settings');
16940:         }
16941:     } else {
16942:         $resulttext = '<span class="LC_error">'.
16943:             &mt('An error occurred: [_1]',$putresult).'</span>';
16944:     }
16945:     if ($warningmsg ne '') {
16946:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
16947:     }
16948:     return $resulttext;
16949: }
16950: 
16951: sub modify_selfcreation {
16952:     my ($dom,$lastactref,%domconfig) = @_;
16953:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
16954:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
16955:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
16956:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
16957:     if (ref($typesref) eq 'ARRAY') {
16958:         @types = @{$typesref};
16959:     }
16960:     if (ref($usertypesref) eq 'HASH') {
16961:         %usertypes = %{$usertypesref};
16962:     }
16963:     $usertypes{'default'} = $othertitle;
16964: #
16965: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
16966: #
16967:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
16968:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
16969:             if ($key eq 'cancreate') {
16970:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
16971:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
16972:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
16973:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
16974:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
16975:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
16976:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
16977:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
16978:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16979:                         } else {
16980:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
16981:                         }
16982:                     }
16983:                 }
16984:             } elsif ($key eq 'email_rule') {
16985:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
16986:             } else {
16987:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
16988:             }
16989:         }
16990:     }
16991: #
16992: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
16993: #
16994:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
16995:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
16996:             if ($key eq 'selfcreate') {
16997:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
16998:             } else {
16999:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
17000:             }
17001:         }
17002:     }
17003: #
17004: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
17005: #
17006:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
17007:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
17008:             if ($key eq 'inststatusguest') {
17009:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
17010:             } else {
17011:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
17012:             }
17013:         }
17014:     }
17015: 
17016:     my @contexts = ('selfcreate');
17017:     @{$cancreate{'selfcreate'}} = ();
17018:     %{$cancreate{'emailusername'}} = ();
17019:     if (@types) {
17020:         @{$cancreate{'statustocreate'}} = ();
17021:     }
17022:     %{$cancreate{'selfcreateprocessing'}} = ();
17023:     %{$cancreate{'shibenv'}} = ();
17024:     %{$cancreate{'emailverified'}} = ();
17025:     %{$cancreate{'emailoptions'}} = ();
17026:     %{$cancreate{'emaildomain'}} = ();
17027:     my %selfcreatetypes = (
17028:                              sso   => 'users authenticated by institutional single sign on',
17029:                              login => 'users authenticated by institutional log-in',
17030:                              email => 'users verified by e-mail',
17031:                           );
17032: #
17033: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
17034: # is permitted.
17035: #
17036:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
17037: 
17038:     my (@statuses,%email_rule);
17039:     foreach my $item ('login','sso','email') {
17040:         if ($item eq 'email') {
17041:             if ($env{'form.cancreate_email'}) {
17042:                 if (@types) {
17043:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
17044:                     foreach my $status (@poss_statuses) {
17045:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
17046:                             push(@statuses,$status);
17047:                         }
17048:                     }
17049:                     $save_inststatus{'inststatusguest'} = \@statuses;
17050:                 } else {
17051:                     push(@statuses,'default');
17052:                 }
17053:                 if (@statuses) {
17054:                     my %curr_rule;
17055:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
17056:                         foreach my $type (@statuses) {
17057:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
17058:                         }
17059:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
17060:                         foreach my $type (@statuses) {
17061:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
17062:                         }
17063:                     }
17064:                     push(@{$cancreate{'selfcreate'}},'email');
17065:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
17066:                     my %curremaildom;
17067:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
17068:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
17069:                     }
17070:                     foreach my $type (@statuses) {
17071:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
17072:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
17073:                         }
17074:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
17075:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
17076:                         }
17077:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
17078: #
17079: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
17080: #
17081:                             my $chosen = $1;
17082:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
17083:                                 my $emaildom;
17084:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
17085:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
17086:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
17087:                                     if (ref($curremaildom{$type}) eq 'HASH') {
17088:                                         if (exists($curremaildom{$type}{$chosen})) {
17089:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
17090:                                                 push(@{$changes{'cancreate'}},'emaildomain');
17091:                                             }
17092:                                         } elsif ($emaildom ne '') {
17093:                                             push(@{$changes{'cancreate'}},'emaildomain');
17094:                                         }
17095:                                     } elsif ($emaildom ne '') {
17096:                                         push(@{$changes{'cancreate'}},'emaildomain');
17097:                                     } 
17098:                                 }
17099:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17100:                             } elsif ($chosen eq 'custom') {
17101:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
17102:                                 $email_rule{$type} = [];
17103:                                 if (ref($emailrules) eq 'HASH') {
17104:                                     foreach my $rule (@possemail_rules) {
17105:                                         if (exists($emailrules->{$rule})) {
17106:                                             push(@{$email_rule{$type}},$rule);
17107:                                         }
17108:                                     }
17109:                                 }
17110:                                 if (@{$email_rule{$type}}) {
17111:                                     $cancreate{'emailoptions'}{$type} = 'custom';
17112:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
17113:                                         if (@{$curr_rule{$type}} > 0) {
17114:                                             foreach my $rule (@{$curr_rule{$type}}) {
17115:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
17116:                                                     push(@{$changes{'email_rule'}},$type);
17117:                                                 }
17118:                                             }
17119:                                         }
17120:                                         foreach my $type (@{$email_rule{$type}}) {
17121:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
17122:                                                 push(@{$changes{'email_rule'}},$type);
17123:                                             }
17124:                                         }
17125:                                     } else {
17126:                                         push(@{$changes{'email_rule'}},$type);
17127:                                     }
17128:                                 }
17129:                             } else {
17130:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
17131:                             }
17132:                         }
17133:                     }
17134:                     if (@types) {
17135:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17136:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
17137:                             if (@changed) {
17138:                                 push(@{$changes{'inststatus'}},'inststatusguest');
17139:                             }
17140:                         } else {
17141:                             push(@{$changes{'inststatus'}},'inststatusguest');
17142:                         }
17143:                     }
17144:                 } else {
17145:                     delete($env{'form.cancreate_email'});
17146:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17147:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17148:                             push(@{$changes{'inststatus'}},'inststatusguest');
17149:                         }
17150:                     }
17151:                 }
17152:             } else {
17153:                 $save_inststatus{'inststatusguest'} = [];
17154:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
17155:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
17156:                         push(@{$changes{'inststatus'}},'inststatusguest');
17157:                     }
17158:                 }
17159:             }
17160:         } else {
17161:             if ($env{'form.cancreate_'.$item}) {
17162:                 push(@{$cancreate{'selfcreate'}},$item);
17163:             }
17164:         }
17165:     }
17166:     my (%userinfo,%savecaptcha);
17167:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
17168: #
17169: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
17170: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
17171: #
17172: 
17173:     if ($env{'form.cancreate_email'}) {
17174:         push(@contexts,'emailusername');
17175:         if (@statuses) {
17176:             foreach my $type (@statuses) {
17177:                 if (ref($infofields) eq 'ARRAY') {
17178:                     foreach my $field (@{$infofields}) {
17179:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
17180:                             $cancreate{'emailusername'}{$type}{$field} = $1;
17181:                         }
17182:                     }
17183:                 }
17184:             }
17185:         }
17186: #
17187: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
17188: # queued requests for self-creation of account verified by e-mail.
17189: #
17190: 
17191:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
17192:         @approvalnotify = sort(@approvalnotify);
17193:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
17194:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17195:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
17196:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
17197:                     push(@{$changes{'cancreate'}},'notify');
17198:                 }
17199:             } else {
17200:                 if ($cancreate{'notify'}{'approval'}) {
17201:                     push(@{$changes{'cancreate'}},'notify');
17202:                 }
17203:             }
17204:         } elsif ($cancreate{'notify'}{'approval'}) {
17205:             push(@{$changes{'cancreate'}},'notify');
17206:         }
17207: 
17208:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
17209:     }
17210: #  
17211: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
17212: # institutional log-in.
17213: #
17214:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
17215:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
17216:                ($domdefaults{'auth_def'} eq 'localauth'))) {
17217:             $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.').' '.
17218:                           &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.');
17219:         }
17220:     }
17221:     my @fields = ('lastname','firstname','middlename','generation',
17222:                   'permanentemail','id');
17223:     my @shibfields = (@fields,'inststatus');
17224:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17225: #
17226: # Where usernames may created for institutional log-in and/or institutional single sign on:
17227: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
17228: # may self-create accounts 
17229: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
17230: # which the user may supply, if institutional data is unavailable.
17231: #
17232:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
17233:         if (@types) {
17234:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
17235:             push(@contexts,'statustocreate');
17236:             foreach my $type (@types) {
17237:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
17238:                 foreach my $field (@fields) {
17239:                     if (grep(/^\Q$field\E$/,@modifiable)) {
17240:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
17241:                     } else {
17242:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
17243:                     }
17244:                 }
17245:             }
17246:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
17247:                 foreach my $type (@types) {
17248:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
17249:                         foreach my $field (@fields) {
17250:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
17251:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
17252:                                 push(@{$changes{'selfcreate'}},$type);
17253:                                 last;
17254:                             }
17255:                         }
17256:                     }
17257:                 }
17258:             } else {
17259:                 foreach my $type (@types) {
17260:                     push(@{$changes{'selfcreate'}},$type);
17261:                 }
17262:             }
17263:         }
17264:         foreach my $field (@shibfields) {
17265:             if ($env{'form.shibenv_'.$field} ne '') {
17266:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
17267:             }
17268:         }
17269:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
17270:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
17271:                 foreach my $field (@shibfields) {
17272:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
17273:                         push(@{$changes{'cancreate'}},'shibenv');
17274:                     }
17275:                 }
17276:             } else {
17277:                 foreach my $field (@shibfields) {
17278:                     if ($env{'form.shibenv_'.$field}) {
17279:                         push(@{$changes{'cancreate'}},'shibenv');
17280:                         last;
17281:                     }
17282:                 }
17283:             }
17284:         }
17285:     }
17286:     foreach my $item (@contexts) {
17287:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
17288:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
17289:                 if (ref($cancreate{$item}) eq 'ARRAY') {
17290:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
17291:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17292:                             push(@{$changes{'cancreate'}},$item);
17293:                         }
17294:                     }
17295:                 }
17296:             }
17297:             if (ref($cancreate{$item}) eq 'ARRAY') {
17298:                 foreach my $type (@{$cancreate{$item}}) {
17299:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
17300:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17301:                             push(@{$changes{'cancreate'}},$item);
17302:                         }
17303:                     }
17304:                 }
17305:             }
17306:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
17307:             if (ref($cancreate{$item}) eq 'HASH') {
17308:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
17309:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17310:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
17311:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17312:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17313:                                     push(@{$changes{'cancreate'}},$item);
17314:                                 }
17315:                             }
17316:                         }
17317:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17318:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17319:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17320:                                 push(@{$changes{'cancreate'}},$item);
17321:                             }
17322:                         }
17323:                     }
17324:                 }
17325:                 foreach my $type (keys(%{$cancreate{$item}})) {
17326:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17327:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17328:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
17329:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
17330:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17331:                                         push(@{$changes{'cancreate'}},$item);
17332:                                     }
17333:                                 }
17334:                             } else {
17335:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17336:                                     push(@{$changes{'cancreate'}},$item);
17337:                                 }
17338:                             }
17339:                         }
17340:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17341:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
17342:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17343:                                 push(@{$changes{'cancreate'}},$item);
17344:                             }
17345:                         }
17346:                     }
17347:                 }
17348:             }
17349:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
17350:             if (ref($cancreate{$item}) eq 'ARRAY') {
17351:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
17352:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17353:                         push(@{$changes{'cancreate'}},$item);
17354:                     }
17355:                 }
17356:             }
17357:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
17358:             if (ref($cancreate{$item}) eq 'HASH') {
17359:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17360:                     push(@{$changes{'cancreate'}},$item);
17361:                 }
17362:             }
17363:         } elsif ($item eq 'emailusername') {
17364:             if (ref($cancreate{$item}) eq 'HASH') {
17365:                 foreach my $type (keys(%{$cancreate{$item}})) {
17366:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
17367:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
17368:                             if ($cancreate{$item}{$type}{$field}) {
17369:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
17370:                                     push(@{$changes{'cancreate'}},$item);
17371:                                 }
17372:                                 last;
17373:                             }
17374:                         }
17375:                     }
17376:                 }
17377:             }
17378:         }
17379:     }
17380: #
17381: # Populate %save_usercreate hash with updates to self-creation configuration.
17382: #
17383:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
17384:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
17385:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
17386:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
17387:     if (ref($cancreate{'notify'}) eq 'HASH') {
17388:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
17389:     }
17390:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
17391:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
17392:     }
17393:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
17394:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
17395:     }
17396:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
17397:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
17398:     }
17399:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
17400:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
17401:     }
17402:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17403:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
17404:     }
17405:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
17406:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
17407:     }
17408:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
17409:     $save_usercreate{'email_rule'} = \%email_rule;
17410: 
17411:     my %userconfig_hash = (
17412:             usercreation     => \%save_usercreate,
17413:             usermodification => \%save_usermodify,
17414:             inststatus       => \%save_inststatus,
17415:     );
17416: 
17417:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
17418:                                              $dom);
17419: #
17420: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
17421: #
17422:     if ($putresult eq 'ok') {
17423:         if (keys(%changes) > 0) {
17424:             $resulttext = &mt('Changes made:').'<ul>';
17425:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
17426:                 my %lt = &selfcreation_types();
17427:                 foreach my $type (@{$changes{'cancreate'}}) {
17428:                     my $chgtext = '';
17429:                     if ($type eq 'selfcreate') {
17430:                         if (@{$cancreate{$type}} == 0) {
17431:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
17432:                         } else {
17433:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
17434:                                         '<ul>';
17435:                             foreach my $case (@{$cancreate{$type}}) {
17436:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
17437:                             }
17438:                             $chgtext .= '</ul>';
17439:                             if (ref($cancreate{$type}) eq 'ARRAY') {
17440:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
17441:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
17442:                                         if (@{$cancreate{'statustocreate'}} == 0) {
17443:                                             $chgtext .= '<span class="LC_warning">'.
17444:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
17445:                                                         '</span><br />';
17446:                                         }
17447:                                     }
17448:                                 }
17449:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
17450:                                     if (!@statuses) {
17451:                                         $chgtext .= '<span class="LC_warning">'.
17452:                                                     &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.").
17453:                                                     '</span><br />';
17454: 
17455:                                     }
17456:                                 }
17457:                             }
17458:                         }
17459:                     } elsif ($type eq 'shibenv') {
17460:                         if (keys(%{$cancreate{$type}}) == 0) {
17461:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
17462:                         } else {
17463:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
17464:                                         '<ul>';
17465:                             foreach my $field (@shibfields) {
17466:                                 next if ($cancreate{$type}{$field} eq '');
17467:                                 if ($field eq 'inststatus') {
17468:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
17469:                                 } else {
17470:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
17471:                                 }
17472:                             }
17473:                             $chgtext .= '</ul>';
17474:                         }
17475:                     } elsif ($type eq 'statustocreate') {
17476:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
17477:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
17478:                             if (@{$cancreate{'selfcreate'}} > 0) {
17479:                                 if (@{$cancreate{'statustocreate'}} == 0) {
17480:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
17481:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
17482:                                         $chgtext .= '<br />'.
17483:                                                     '<span class="LC_warning">'.
17484:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
17485:                                                     '</span>';
17486:                                     }
17487:                                 } elsif (keys(%usertypes) > 0) {
17488:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17489:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
17490:                                     } else {
17491:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
17492:                                     }
17493:                                     $chgtext .= '<ul>';
17494:                                     foreach my $case (@{$cancreate{$type}}) {
17495:                                         if ($case eq 'default') {
17496:                                             $chgtext .= '<li>'.$othertitle.'</li>';
17497:                                         } else {
17498:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
17499:                                         }
17500:                                     }
17501:                                     $chgtext .= '</ul>';
17502:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
17503:                                         $chgtext .= '<span class="LC_warning">'.
17504:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
17505:                                                     '</span>';
17506:                                     }
17507:                                 }
17508:                             } else {
17509:                                 if (@{$cancreate{$type}} == 0) {
17510:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
17511:                                 } else {
17512:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
17513:                                 }
17514:                             }
17515:                             $chgtext .= '<br />';
17516:                         }
17517:                     } elsif ($type eq 'selfcreateprocessing') {
17518:                         my %choices = &Apache::lonlocal::texthash (
17519:                                                                     automatic => 'Automatic approval',
17520:                                                                     approval  => 'Queued for approval',
17521:                                                                   );
17522:                         if (@types) {
17523:                             if (@statuses) {
17524:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
17525:                                             '<ul>';
17526:                                 foreach my $status (@statuses) {
17527:                                     if ($status eq 'default') {
17528:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17529:                                     } else {
17530:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
17531:                                     }
17532:                                 }
17533:                                 $chgtext .= '</ul>';
17534:                             }
17535:                         } else {
17536:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
17537:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
17538:                         }
17539:                     } elsif ($type eq 'emailverified') {
17540:                         my %options = &Apache::lonlocal::texthash (
17541:                                                                     all   => 'Same as e-mail',
17542:                                                                     first => 'Omit @domain',
17543:                                                                     free  => 'Free to choose',
17544:                                                                   );
17545:                         if (@types) {
17546:                             if (@statuses) {
17547:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
17548:                                             '<ul>';
17549:                                 foreach my $status (@statuses) {
17550:                                     if ($status eq 'default') {
17551:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
17552:                                     } else {
17553:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
17554:                                     }
17555:                                 }
17556:                                 $chgtext .= '</ul>';
17557:                             }
17558:                         } else {
17559:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
17560:                                             $options{$cancreate{'emailverified'}{'default'}});
17561:                         }
17562:                     } elsif ($type eq 'emailoptions') {
17563:                         my %options = &Apache::lonlocal::texthash (
17564:                                                                     any     => 'Any e-mail',
17565:                                                                     inst    => 'Institutional only',
17566:                                                                     noninst => 'Non-institutional only',
17567:                                                                     custom  => 'Custom restrictions',
17568:                                                                   );
17569:                         if (@types) {
17570:                             if (@statuses) {
17571:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
17572:                                             '<ul>';
17573:                                 foreach my $status (@statuses) {
17574:                                     if ($type eq 'default') {
17575:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
17576:                                     } else {
17577:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
17578:                                     }
17579:                                 }
17580:                                 $chgtext .= '</ul>';
17581:                             }
17582:                         } else {
17583:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
17584:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
17585:                             } else {
17586:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
17587:                                                 $options{$cancreate{'emailoptions'}{'default'}});
17588:                             }
17589:                         }
17590:                     } elsif ($type eq 'emaildomain') {
17591:                         my $output;
17592:                         if (@statuses) {
17593:                             foreach my $type (@statuses) {
17594:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
17595:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
17596:                                         if ($type eq 'default') {
17597:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17598:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
17599:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
17600:                                             } else {
17601:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
17602:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
17603:                                             }
17604:                                         } else {
17605:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17606:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
17607:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
17608:                                             } else {
17609:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
17610:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
17611:                                             }
17612:                                         }
17613:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
17614:                                         if ($type eq 'default') {
17615:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17616:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
17617:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
17618:                                             } else {
17619:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
17620:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
17621:                                             }
17622:                                         } else {
17623:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
17624:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
17625:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
17626:                                             } else {
17627:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
17628:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
17629:                                             }
17630:                                         }
17631:                                     }
17632:                                 }
17633:                             }
17634:                         }
17635:                         if ($output ne '') {
17636:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
17637:                                         '<ul>'.$output.'</ul>';
17638:                         }
17639:                     } elsif ($type eq 'captcha') {
17640:                         if ($savecaptcha{$type} eq 'notused') {
17641:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
17642:                         } else {
17643:                             my %captchas = &captcha_phrases();
17644:                             if ($captchas{$savecaptcha{$type}}) {
17645:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
17646:                             } else {
17647:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
17648:                             }
17649:                         }
17650:                     } elsif ($type eq 'recaptchakeys') {
17651:                         my ($privkey,$pubkey);
17652:                         if (ref($savecaptcha{$type}) eq 'HASH') {
17653:                             $pubkey = $savecaptcha{$type}{'public'};
17654:                             $privkey = $savecaptcha{$type}{'private'};
17655:                         }
17656:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
17657:                         if (!$pubkey) {
17658:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
17659:                         } else {
17660:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
17661:                         }
17662:                         if (!$privkey) {
17663:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
17664:                         } else {
17665:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
17666:                         }
17667:                         $chgtext .= '</ul>';
17668:                     } elsif ($type eq 'recaptchaversion') {
17669:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
17670:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
17671:                         }
17672:                     } elsif ($type eq 'emailusername') {
17673:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
17674:                             if (@statuses) {
17675:                                 foreach my $type (@statuses) {
17676:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
17677:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
17678:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
17679:                                                     '<ul>';
17680:                                             foreach my $field (@{$infofields}) {
17681:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
17682:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
17683:                                                 }
17684:                                             }
17685:                                             $chgtext .= '</ul>';
17686:                                         } else {
17687:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
17688:                                         }
17689:                                     } else {
17690:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
17691:                                     }
17692:                                 }
17693:                             }
17694:                         }
17695:                     } elsif ($type eq 'notify') {
17696:                         my $numapprove = 0;
17697:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
17698:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
17699:                                 if ($cancreate{'notify'}{'approval'}) {
17700:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
17701:                                     $numapprove ++;
17702:                                 }
17703:                             }
17704:                         }
17705:                         unless ($numapprove) {
17706:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
17707:                         }
17708:                     }
17709:                     if ($chgtext) {
17710:                         $resulttext .= '<li>'.$chgtext.'</li>';
17711:                     }
17712:                 }
17713:             }
17714:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
17715:                 my ($emailrules,$emailruleorder) =
17716:                     &Apache::lonnet::inst_userrules($dom,'email');
17717:                 foreach my $type (@{$changes{'email_rule'}}) {
17718:                     if (ref($email_rule{$type}) eq 'ARRAY') {
17719:                         my $chgtext = '<ul>';
17720:                         foreach my $rule (@{$email_rule{$type}}) {
17721:                             if (ref($emailrules->{$rule}) eq 'HASH') {
17722:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
17723:                             }
17724:                         }
17725:                         $chgtext .= '</ul>';
17726:                         my $typename;
17727:                         if (@types) {
17728:                             if ($type eq 'default') {
17729:                                 $typename = $othertitle;
17730:                             } else {
17731:                                 $typename = $usertypes{$type};
17732:                             } 
17733:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
17734:                         }
17735:                         if (@{$email_rule{$type}} > 0) {
17736:                             $resulttext .= '<li>'.
17737:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
17738:                                                $usertypes{$type}).
17739:                                            $chgtext.
17740:                                            '</li>';
17741:                         } else {
17742:                             $resulttext .= '<li>'.
17743:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
17744:                                            '</li>'.
17745:                                            &mt('(Affiliation: [_1])',$typename);
17746:                         }
17747:                     }
17748:                 }
17749:             }
17750:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
17751:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
17752:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
17753:                         my $chgtext = '<ul>';
17754:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
17755:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
17756:                         }
17757:                         $chgtext .= '</ul>';
17758:                         $resulttext .= '<li>'.
17759:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
17760:                                           $chgtext.
17761:                                        '</li>';
17762:                     } else {
17763:                         $resulttext .= '<li>'.
17764:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
17765:                                        '</li>';
17766:                     }
17767:                 }
17768:             }
17769:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
17770:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
17771:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17772:                 foreach my $type (@{$changes{'selfcreate'}}) {
17773:                     my $typename = $type;
17774:                     if (keys(%usertypes) > 0) {
17775:                         if ($usertypes{$type} ne '') {
17776:                             $typename = $usertypes{$type};
17777:                         }
17778:                     }
17779:                     my @modifiable;
17780:                     $resulttext .= '<li>'.
17781:                                     &mt('Self-creation of account by users with status: [_1]',
17782:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
17783:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
17784:                     foreach my $field (@fields) {
17785:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
17786:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
17787:                         }
17788:                     }
17789:                     if (@modifiable > 0) {
17790:                         $resulttext .= join(', ',@modifiable);
17791:                     } else {
17792:                         $resulttext .= &mt('none');
17793:                     }
17794:                     $resulttext .= '</li>';
17795:                 }
17796:                 $resulttext .= '</ul></li>';
17797:             }
17798:             $resulttext .= '</ul>';
17799:             my $cachetime = 24*60*60;
17800:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
17801:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
17802:             if (ref($lastactref) eq 'HASH') {
17803:                 $lastactref->{'domdefaults'} = 1;
17804:             }
17805:         } else {
17806:             $resulttext = &mt('No changes made to self-creation settings');
17807:         }
17808:     } else {
17809:         $resulttext = '<span class="LC_error">'.
17810:             &mt('An error occurred: [_1]',$putresult).'</span>';
17811:     }
17812:     if ($warningmsg ne '') {
17813:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
17814:     }
17815:     return $resulttext;
17816: }
17817: 
17818: sub process_captcha {
17819:     my ($container,$changes,$newsettings,$currsettings) = @_;
17820:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
17821:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
17822:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
17823:         $newsettings->{'captcha'} = 'original';
17824:     }
17825:     my %current;
17826:     if (ref($currsettings) eq 'HASH') {
17827:         %current = %{$currsettings};
17828:     }
17829:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
17830:         if ($container eq 'cancreate') {
17831:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
17832:                 push(@{$changes->{'cancreate'}},'captcha');
17833:             } elsif (!defined($changes->{'cancreate'})) {
17834:                 $changes->{'cancreate'} = ['captcha'];
17835:             }
17836:         } elsif ($container eq 'passwords') {
17837:             $changes->{'reset'} = 1;
17838:         } else {
17839:             $changes->{'captcha'} = 1;
17840:         }
17841:     }
17842:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
17843:     if ($newsettings->{'captcha'} eq 'recaptcha') {
17844:         $newpub = $env{'form.'.$container.'_recaptchapub'};
17845:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
17846:         $newpub =~ s/[^\w\-]//g;
17847:         $newpriv =~ s/[^\w\-]//g;
17848:         $newsettings->{'recaptchakeys'} = {
17849:                                              public  => $newpub,
17850:                                              private => $newpriv,
17851:                                           };
17852:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
17853:         $newversion =~ s/\D//g;
17854:         if ($newversion ne '2') {
17855:             $newversion = 1;
17856:         }
17857:         $newsettings->{'recaptchaversion'} = $newversion;
17858:     }
17859:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
17860:         $currpub = $current{'recaptchakeys'}{'public'};
17861:         $currpriv = $current{'recaptchakeys'}{'private'};
17862:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
17863:             $newsettings->{'recaptchakeys'} = {
17864:                                                  public  => '',
17865:                                                  private => '',
17866:                                               }
17867:         }
17868:     }
17869:     if ($current{'captcha'} eq 'recaptcha') {
17870:         $currversion = $current{'recaptchaversion'};
17871:         if ($currversion ne '2') {
17872:             $currversion = 1;
17873:         }
17874:     }
17875:     if ($currversion ne $newversion) {
17876:         if ($container eq 'cancreate') {
17877:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
17878:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
17879:             } elsif (!defined($changes->{'cancreate'})) {
17880:                 $changes->{'cancreate'} = ['recaptchaversion'];
17881:             }
17882:         } elsif ($container eq 'passwords') {
17883:             $changes->{'reset'} = 1;
17884:         } else {
17885:             $changes->{'recaptchaversion'} = 1;
17886:         }
17887:     }
17888:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
17889:         if ($container eq 'cancreate') {
17890:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
17891:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
17892:             } elsif (!defined($changes->{'cancreate'})) {
17893:                 $changes->{'cancreate'} = ['recaptchakeys'];
17894:             }
17895:         } elsif ($container eq 'passwords') {
17896:             $changes->{'reset'} = 1;
17897:         } else {
17898:             $changes->{'recaptchakeys'} = 1;
17899:         }
17900:     }
17901:     return;
17902: }
17903: 
17904: sub modify_usermodification {
17905:     my ($dom,%domconfig) = @_;
17906:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
17907:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
17908:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
17909:             if ($key eq 'selfcreate') {
17910:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
17911:             } else {  
17912:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
17913:             }
17914:         }
17915:     }
17916:     my @contexts = ('author','course');
17917:     my %context_title = (
17918:                            author => 'In author context',
17919:                            course => 'In course context',
17920:                         );
17921:     my @fields = ('lastname','firstname','middlename','generation',
17922:                   'permanentemail','id');
17923:     my %roles = (
17924:                   author => ['ca','aa'],
17925:                   course => ['st','ep','ta','in','cr'],
17926:                 );
17927:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
17928:     foreach my $context (@contexts) {
17929:         foreach my $role (@{$roles{$context}}) {
17930:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
17931:             foreach my $item (@fields) {
17932:                 if (grep(/^\Q$item\E$/,@modifiable)) {
17933:                     $modifyhash{$context}{$role}{$item} = 1;
17934:                 } else {
17935:                     $modifyhash{$context}{$role}{$item} = 0;
17936:                 }
17937:             }
17938:         }
17939:         if (ref($curr_usermodification{$context}) eq 'HASH') {
17940:             foreach my $role (@{$roles{$context}}) {
17941:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
17942:                     foreach my $field (@fields) {
17943:                         if ($modifyhash{$context}{$role}{$field} ne 
17944:                                 $curr_usermodification{$context}{$role}{$field}) {
17945:                             push(@{$changes{$context}},$role);
17946:                             last;
17947:                         }
17948:                     }
17949:                 }
17950:             }
17951:         } else {
17952:             foreach my $context (@contexts) {
17953:                 foreach my $role (@{$roles{$context}}) {
17954:                     push(@{$changes{$context}},$role);
17955:                 }
17956:             }
17957:         }
17958:     }
17959:     my %usermodification_hash =  (
17960:                                    usermodification => \%modifyhash,
17961:                                  );
17962:     my $putresult = &Apache::lonnet::put_dom('configuration',
17963:                                              \%usermodification_hash,$dom);
17964:     if ($putresult eq 'ok') {
17965:         if (keys(%changes) > 0) {
17966:             $resulttext = &mt('Changes made: ').'<ul>';
17967:             foreach my $context (@contexts) {
17968:                 if (ref($changes{$context}) eq 'ARRAY') {
17969:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
17970:                     if (ref($changes{$context}) eq 'ARRAY') {
17971:                         foreach my $role (@{$changes{$context}}) {
17972:                             my $rolename;
17973:                             if ($role eq 'cr') {
17974:                                 $rolename = &mt('Custom');
17975:                             } else {
17976:                                 $rolename = &Apache::lonnet::plaintext($role);
17977:                             }
17978:                             my @modifiable;
17979:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
17980:                             foreach my $field (@fields) {
17981:                                 if ($modifyhash{$context}{$role}{$field}) {
17982:                                     push(@modifiable,$fieldtitles{$field});
17983:                                 }
17984:                             }
17985:                             if (@modifiable > 0) {
17986:                                 $resulttext .= join(', ',@modifiable);
17987:                             } else {
17988:                                 $resulttext .= &mt('none'); 
17989:                             }
17990:                             $resulttext .= '</li>';
17991:                         }
17992:                         $resulttext .= '</ul></li>';
17993:                     }
17994:                 }
17995:             }
17996:             $resulttext .= '</ul>';
17997:         } else {
17998:             $resulttext = &mt('No changes made to user modification settings');
17999:         }
18000:     } else {
18001:         $resulttext = '<span class="LC_error">'.
18002:             &mt('An error occurred: [_1]',$putresult).'</span>';
18003:     }
18004:     return $resulttext;
18005: }
18006: 
18007: sub modify_defaults {
18008:     my ($dom,$lastactref,%domconfig) = @_;
18009:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
18010:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18011:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
18012:                  'portal_def');
18013:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
18014:     foreach my $item (@items) {
18015:         $newvalues{$item} = $env{'form.'.$item};
18016:         if ($item eq 'auth_def') {
18017:             if ($newvalues{$item} ne '') {
18018:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
18019:                     push(@errors,$item);
18020:                 }
18021:             }
18022:         } elsif ($item eq 'lang_def') {
18023:             if ($newvalues{$item} ne '') {
18024:                 if ($newvalues{$item} =~ /^(\w+)/) {
18025:                     my $langcode = $1;
18026:                     if ($langcode ne 'x_chef') {
18027:                         if (code2language($langcode) eq '') {
18028:                             push(@errors,$item);
18029:                         }
18030:                     }
18031:                 } else {
18032:                     push(@errors,$item);
18033:                 }
18034:             }
18035:         } elsif ($item eq 'timezone_def') {
18036:             if ($newvalues{$item} ne '') {
18037:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
18038:                     push(@errors,$item);   
18039:                 }
18040:             }
18041:         } elsif ($item eq 'datelocale_def') {
18042:             if ($newvalues{$item} ne '') {
18043:                 my @datelocale_ids = DateTime::Locale->ids();
18044:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
18045:                     push(@errors,$item);
18046:                 }
18047:             }
18048:         } elsif ($item eq 'portal_def') {
18049:             if ($newvalues{$item} ne '') {
18050:                 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])\/?$/) {
18051:                     push(@errors,$item);
18052:                 }
18053:             }
18054:         }
18055:         if (grep(/^\Q$item\E$/,@errors)) {
18056:             $newvalues{$item} = $domdefaults{$item};
18057:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
18058:             $changes{$item} = 1;
18059:         }
18060:         $domdefaults{$item} = $newvalues{$item};
18061:     }
18062:     my %staticdefaults = (
18063:                            'intauth_cost'   => 10,
18064:                            'intauth_check'  => 0,
18065:                            'intauth_switch' => 0,
18066:                          );
18067:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
18068:         if (exists($domdefaults{$item})) {
18069:             $newvalues{$item} = $domdefaults{$item};
18070:         } else {
18071:             $newvalues{$item} = $staticdefaults{$item};
18072:         }
18073:     }
18074:     my %defaults_hash = (
18075:                          defaults => \%newvalues,
18076:                         );
18077:     my $title = &defaults_titles();
18078: 
18079:     my $currinststatus;
18080:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18081:         $currinststatus = $domconfig{'inststatus'};
18082:     } else {
18083:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18084:         $currinststatus = {
18085:                              inststatustypes => $usertypes,
18086:                              inststatusorder => $types,
18087:                              inststatusguest => [],
18088:                           };
18089:     }
18090:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
18091:     my @allpos;
18092:     my %alltypes;
18093:     my @inststatusguest;
18094:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
18095:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
18096:             unless (grep(/^\Q$type\E$/,@todelete)) {
18097:                 push(@inststatusguest,$type);
18098:             }
18099:         }
18100:     }
18101:     my ($currtitles,$currorder);
18102:     if (ref($currinststatus) eq 'HASH') {
18103:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
18104:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
18105:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
18106:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
18107:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
18108:                     }
18109:                 }
18110:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
18111:                     my $position = $env{'form.inststatus_pos_'.$type};
18112:                     $position =~ s/\D+//g;
18113:                     $allpos[$position] = $type;
18114:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
18115:                     $alltypes{$type} =~ s/`//g;
18116:                 }
18117:             }
18118:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
18119:             $currtitles =~ s/,$//;
18120:         }
18121:     }
18122:     if ($env{'form.addinststatus'}) {
18123:         my $newtype = $env{'form.addinststatus'};
18124:         $newtype =~ s/\W//g;
18125:         unless (exists($alltypes{$newtype})) {
18126:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
18127:             $alltypes{$newtype} =~ s/`//g; 
18128:             my $position = $env{'form.addinststatus_pos'};
18129:             $position =~ s/\D+//g;
18130:             if ($position ne '') {
18131:                 $allpos[$position] = $newtype;
18132:             }
18133:         }
18134:     }
18135:     my @orderedstatus;
18136:     foreach my $type (@allpos) {
18137:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
18138:             push(@orderedstatus,$type);
18139:         }
18140:     }
18141:     foreach my $type (keys(%alltypes)) {
18142:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
18143:             delete($alltypes{$type});
18144:         }
18145:     }
18146:     $defaults_hash{'inststatus'} = {
18147:                                      inststatustypes => \%alltypes,
18148:                                      inststatusorder => \@orderedstatus,
18149:                                      inststatusguest => \@inststatusguest,
18150:                                    };
18151:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
18152:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
18153:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
18154:         }
18155:     }
18156:     if ($currorder ne join(',',@orderedstatus)) {
18157:         $changes{'inststatus'}{'inststatusorder'} = 1;
18158:     }
18159:     my $newtitles;
18160:     foreach my $item (@orderedstatus) {
18161:         $newtitles .= $alltypes{$item}.',';
18162:     }
18163:     $newtitles =~ s/,$//;
18164:     if ($currtitles ne $newtitles) {
18165:         $changes{'inststatus'}{'inststatustypes'} = 1;
18166:     }
18167:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
18168:                                              $dom);
18169:     if ($putresult eq 'ok') {
18170:         if (keys(%changes) > 0) {
18171:             $resulttext = &mt('Changes made:').'<ul>';
18172:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
18173:             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";
18174:             foreach my $item (sort(keys(%changes))) {
18175:                 if ($item eq 'inststatus') {
18176:                     if (ref($changes{'inststatus'}) eq 'HASH') {
18177:                         if (@orderedstatus) {
18178:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
18179:                             foreach my $type (@orderedstatus) { 
18180:                                 $resulttext .= $alltypes{$type}.', ';
18181:                             }
18182:                             $resulttext =~ s/, $//;
18183:                             $resulttext .= '</li>';
18184:                         } else {
18185:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
18186:                         }
18187:                     }
18188:                 } else {
18189:                     my $value = $env{'form.'.$item};
18190:                     if ($value eq '') {
18191:                         $value = &mt('none');
18192:                     } elsif ($item eq 'auth_def') {
18193:                         my %authnames = &authtype_names();
18194:                         my %shortauth = (
18195:                                           internal   => 'int',
18196:                                           krb4       => 'krb4',
18197:                                           krb5       => 'krb5',
18198:                                           localauth  => 'loc',
18199:                                           lti        => 'lti',
18200:                         );
18201:                         $value = $authnames{$shortauth{$value}};
18202:                     }
18203:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
18204:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
18205:                 }
18206:             }
18207:             $resulttext .= '</ul>';
18208:             $mailmsgtext .= "\n";
18209:             my $cachetime = 24*60*60;
18210:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18211:             if (ref($lastactref) eq 'HASH') {
18212:                 $lastactref->{'domdefaults'} = 1;
18213:             }
18214:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
18215:                 my $notify = 1;
18216:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
18217:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
18218:                         $notify = 0;
18219:                     }
18220:                 }
18221:                 if ($notify) {
18222:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
18223:                                                "LON-CAPA Domain Settings Change - $dom",
18224:                                                $mailmsgtext);
18225:                 }
18226:             }
18227:         } else {
18228:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
18229:         }
18230:     } else {
18231:         $resulttext = '<span class="LC_error">'.
18232:             &mt('An error occurred: [_1]',$putresult).'</span>';
18233:     }
18234:     if (@errors > 0) {
18235:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
18236:         foreach my $item (@errors) {
18237:             $resulttext .= ' "'.$title->{$item}.'",';
18238:         }
18239:         $resulttext =~ s/,$//;
18240:     }
18241:     return $resulttext;
18242: }
18243: 
18244: sub modify_scantron {
18245:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18246:     my ($resulttext,%confhash,%changes,$errors);
18247:     my $custom = 'custom.tab';
18248:     my $default = 'default.tab';
18249:     my $servadm = $r->dir_config('lonAdmEMail');
18250:     my ($configuserok,$author_ok,$switchserver) =
18251:         &config_check($dom,$confname,$servadm);
18252:     if ($env{'form.scantronformat.filename'} ne '') {
18253:         my $error;
18254:         if ($configuserok eq 'ok') {
18255:             if ($switchserver) {
18256:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
18257:             } else {
18258:                 if ($author_ok eq 'ok') {
18259:                     my ($result,$scantronurl) =
18260:                         &publishlogo($r,'upload','scantronformat',$dom,
18261:                                      $confname,'scantron','','',$custom);
18262:                     if ($result eq 'ok') {
18263:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
18264:                         $changes{'scantronformat'} = 1;
18265:                     } else {
18266:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
18267:                     }
18268:                 } else {
18269:                     $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);
18270:                 }
18271:             }
18272:         } else {
18273:             $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);
18274:         }
18275:         if ($error) {
18276:             &Apache::lonnet::logthis($error);
18277:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18278:         }
18279:     }
18280:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18281:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
18282:             if ($env{'form.scantronformat_del'}) {
18283:                 $confhash{'scantron'}{'scantronformat'} = '';
18284:                 $changes{'scantronformat'} = 1;
18285:             } else {
18286:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
18287:             }
18288:         }
18289:     }
18290:     my @options = ('hdr','pad','rem');
18291:     my @fields = &scantroncsv_fields();
18292:     my %titles = &scantronconfig_titles();
18293:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
18294:     my ($newdat,$currdat,%newcol,%currcol);
18295:     if (grep(/^dat$/,@formats)) {
18296:         $confhash{'scantron'}{config}{dat} = 1;
18297:         $newdat = 1;
18298:     } else {
18299:         $newdat = 0;
18300:     }
18301:     if (grep(/^csv$/,@formats)) {
18302:         my %bynum;
18303:         foreach my $field (@fields) {
18304:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
18305:                 my $posscol = $1;
18306:                 if (($posscol < 20) && (!$bynum{$posscol})) {
18307:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
18308:                     $bynum{$posscol} = $field;
18309:                     $newcol{$field} = $posscol;
18310:                 }
18311:             }
18312:         }
18313:         if (keys(%newcol)) {
18314:             foreach my $option (@options) {
18315:                 if ($env{'form.scantroncsv_'.$option}) {
18316:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
18317:                 }
18318:             }
18319:         }
18320:     }
18321:     $currdat = 1;
18322:     if (ref($domconfig{'scantron'}) eq 'HASH') {
18323:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
18324:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
18325:                 $currdat = 0;
18326:             }
18327:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18328:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18329:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
18330:                 }
18331:             }
18332:         }
18333:     }
18334:     if ($currdat != $newdat) {
18335:         $changes{'config'} = 1;
18336:     } else {
18337:         foreach my $field (@fields) {
18338:             if ($currcol{$field} ne '') {
18339:                 if ($currcol{$field} ne $newcol{$field}) {
18340:                     $changes{'config'} = 1;
18341:                     last;
18342:                 }
18343:             } elsif ($newcol{$field} ne '') {
18344:                 $changes{'config'} = 1;
18345:                 last;
18346:             }
18347:         }
18348:     }
18349:     if (keys(%confhash) > 0) {
18350:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
18351:                                                  $dom);
18352:         if ($putresult eq 'ok') {
18353:             if (keys(%changes) > 0) {
18354:                 if (ref($confhash{'scantron'}) eq 'HASH') {
18355:                     $resulttext = &mt('Changes made:').'<ul>';
18356:                     if ($changes{'scantronformat'}) {
18357:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
18358:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
18359:                         } else {
18360:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
18361:                         }
18362:                     }
18363:                     if ($changes{'config'}) {
18364:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
18365:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
18366:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
18367:                             }
18368:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
18369:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
18370:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
18371:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
18372:                                         foreach my $field (@fields) {
18373:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
18374:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
18375:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
18376:                                             }
18377:                                         }
18378:                                         $resulttext .= '</ul></li>';
18379:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
18380:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
18381:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
18382:                                                 foreach my $option (@options) {
18383:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
18384:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
18385:                                                     }
18386:                                                 }
18387:                                                 $resulttext .= '</ul></li>';
18388:                                             }
18389:                                         }
18390:                                     }
18391:                                 }
18392:                             }
18393:                         } else {
18394:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
18395:                         }
18396:                     }
18397:                     $resulttext .= '</ul>';
18398:                 } else {
18399:                     $resulttext = &mt('Changes made to bubblesheet format file.');
18400:                 }
18401:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
18402:                 if (ref($lastactref) eq 'HASH') {
18403:                     $lastactref->{'domainconfig'} = 1;
18404:                 }
18405:             } else {
18406:                 $resulttext = &mt('No changes made to bubblesheet format settings');
18407:             }
18408:         } else {
18409:             $resulttext = '<span class="LC_error">'.
18410:                 &mt('An error occurred: [_1]',$putresult).'</span>';
18411:         }
18412:     } else {
18413:         $resulttext = &mt('No changes made to bubblesheet format file'); 
18414:     }
18415:     if ($errors) {
18416:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18417:                        $errors.'</ul></p>';
18418:     }
18419:     return $resulttext;
18420: }
18421: 
18422: sub modify_coursecategories {
18423:     my ($dom,$lastactref,%domconfig) = @_;
18424:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
18425:         $cathash);
18426:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
18427:     my @catitems = ('unauth','auth');
18428:     my @cattypes = ('std','domonly','codesrch','none');
18429:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
18430:         $cathash = $domconfig{'coursecategories'}{'cats'};
18431:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
18432:             $changes{'togglecats'} = 1;
18433:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
18434:         }
18435:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
18436:             $changes{'categorize'} = 1;
18437:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
18438:         }
18439:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
18440:             $changes{'togglecatscomm'} = 1;
18441:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
18442:         }
18443:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
18444:             $changes{'categorizecomm'} = 1;
18445:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
18446: 
18447:         }
18448:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
18449:             $changes{'togglecatsplace'} = 1;
18450:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
18451:         }
18452:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
18453:             $changes{'categorizeplace'} = 1;
18454:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
18455:         }
18456:         foreach my $item (@catitems) {
18457:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18458:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
18459:                     $changes{$item} = 1;
18460:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18461:                 }
18462:             }
18463:         }
18464:     } else {
18465:         $changes{'togglecats'} = 1;
18466:         $changes{'categorize'} = 1;
18467:         $changes{'togglecatscomm'} = 1;
18468:         $changes{'categorizecomm'} = 1;
18469:         $changes{'togglecatsplace'} = 1;
18470:         $changes{'categorizeplace'} = 1;
18471:         $domconfig{'coursecategories'} = {
18472:                                              togglecats => $env{'form.togglecats'},
18473:                                              categorize => $env{'form.categorize'},
18474:                                              togglecatscomm => $env{'form.togglecatscomm'},
18475:                                              categorizecomm => $env{'form.categorizecomm'},
18476:                                              togglecatsplace => $env{'form.togglecatsplace'},
18477:                                              categorizeplace => $env{'form.categorizeplace'},
18478:                                          };
18479:         foreach my $item (@catitems) {
18480:             if ($env{'form.coursecat_'.$item} ne 'std') {
18481:                 $changes{$item} = 1;
18482:             }
18483:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
18484:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
18485:             }
18486:         }
18487:     }
18488:     if (ref($cathash) eq 'HASH') {
18489:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
18490:             push (@deletecategory,'instcode::0');
18491:         }
18492:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
18493:             push(@deletecategory,'communities::0');
18494:         }
18495:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
18496:             push(@deletecategory,'placement::0');
18497:         }
18498:     }
18499:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
18500:     if (ref($cathash) eq 'HASH') {
18501:         if (@deletecategory > 0) {
18502:             #FIXME Need to remove category from all courses using a deleted category 
18503:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
18504:             foreach my $item (@deletecategory) {
18505:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
18506:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
18507:                     $deletions{$item} = 1;
18508:                     &recurse_cat_deletes($item,$cathash,\%deletions);
18509:                 }
18510:             }
18511:         }
18512:         foreach my $item (keys(%{$cathash})) {
18513:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
18514:             if ($cathash->{$item} ne $env{'form.'.$item}) {
18515:                 $reorderings{$item} = 1;
18516:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
18517:             }
18518:             if ($env{'form.addcategory_name_'.$item} ne '') {
18519:                 my $newcat = $env{'form.addcategory_name_'.$item};
18520:                 my $newdepth = $depth+1;
18521:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18522:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
18523:                 $adds{$newitem} = 1; 
18524:             }
18525:             if ($env{'form.subcat_'.$item} ne '') {
18526:                 my $newcat = $env{'form.subcat_'.$item};
18527:                 my $newdepth = $depth+1;
18528:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
18529:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
18530:                 $adds{$newitem} = 1;
18531:             }
18532:         }
18533:     }
18534:     if ($env{'form.instcode'} eq '1') {
18535:         if (ref($cathash) eq 'HASH') {
18536:             my $newitem = 'instcode::0';
18537:             if ($cathash->{$newitem} eq '') {  
18538:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18539:                 $adds{$newitem} = 1;
18540:             }
18541:         } else {
18542:             my $newitem = 'instcode::0';
18543:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
18544:             $adds{$newitem} = 1;
18545:         }
18546:     }
18547:     if ($env{'form.communities'} eq '1') {
18548:         if (ref($cathash) eq 'HASH') {
18549:             my $newitem = 'communities::0';
18550:             if ($cathash->{$newitem} eq '') {
18551:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
18552:                 $adds{$newitem} = 1;
18553:             }
18554:         } else {
18555:             my $newitem = 'communities::0';
18556:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
18557:             $adds{$newitem} = 1;
18558:         }
18559:     }
18560:     if ($env{'form.placement'} eq '1') {
18561:         if (ref($cathash) eq 'HASH') {
18562:             my $newitem = 'placement::0';
18563:             if ($cathash->{$newitem} eq '') {
18564:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
18565:                 $adds{$newitem} = 1;
18566:             }
18567:         } else {
18568:             my $newitem = 'placement::0';
18569:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
18570:             $adds{$newitem} = 1;
18571:         }
18572:     }
18573:     if ($env{'form.addcategory_name'} ne '') {
18574:         if (($env{'form.addcategory_name'} ne 'instcode') &&
18575:             ($env{'form.addcategory_name'} ne 'communities') &&
18576:             ($env{'form.addcategory_name'} ne 'placement')) {
18577:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
18578:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
18579:             $adds{$newitem} = 1;
18580:         }
18581:     }
18582:     my $putresult;
18583:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
18584:         if (keys(%deletions) > 0) {
18585:             foreach my $key (keys(%deletions)) {
18586:                 if ($predelallitems{$key} ne '') {
18587:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
18588:                 }
18589:             }
18590:         }
18591:         my (@chkcats,@chktrails,%chkallitems);
18592:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
18593:         if (ref($chkcats[0]) eq 'ARRAY') {
18594:             my $depth = 0;
18595:             my $chg = 0;
18596:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
18597:                 my $name = $chkcats[0][$i];
18598:                 my $item;
18599:                 if ($name eq '') {
18600:                     $chg ++;
18601:                 } else {
18602:                     $item = &escape($name).'::0';
18603:                     if ($chg) {
18604:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
18605:                     }
18606:                     $depth ++; 
18607:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
18608:                     $depth --;
18609:                 }
18610:             }
18611:         }
18612:     }
18613:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
18614:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
18615:         if ($putresult eq 'ok') {
18616:             my %title = (
18617:                          togglecats     => 'Show/Hide a course in catalog',
18618:                          categorize     => 'Assign a category to a course',
18619:                          togglecatscomm => 'Show/Hide a community in catalog',
18620:                          categorizecomm => 'Assign a category to a community',
18621:                         );
18622:             my %level = (
18623:                          dom  => 'set in Domain ("Modify Course/Community")',
18624:                          crs  => 'set in Course ("Course Configuration")',
18625:                          comm => 'set in Community ("Community Configuration")',
18626:                          none     => 'No catalog',
18627:                          std      => 'Standard catalog',
18628:                          domonly  => 'Domain-only catalog',
18629:                          codesrch => 'Code search form',
18630:                         );
18631:             $resulttext = &mt('Changes made:').'<ul>';
18632:             if ($changes{'togglecats'}) {
18633:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
18634:             }
18635:             if ($changes{'categorize'}) {
18636:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
18637:             }
18638:             if ($changes{'togglecatscomm'}) {
18639:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
18640:             }
18641:             if ($changes{'categorizecomm'}) {
18642:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
18643:             }
18644:             if ($changes{'unauth'}) {
18645:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
18646:             }
18647:             if ($changes{'auth'}) {
18648:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
18649:             }
18650:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
18651:                 my $cathash;
18652:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
18653:                     $cathash = $domconfig{'coursecategories'}{'cats'};
18654:                 } else {
18655:                     $cathash = {};
18656:                 } 
18657:                 my (@cats,@trails,%allitems);
18658:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
18659:                 if (keys(%deletions) > 0) {
18660:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
18661:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
18662:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
18663:                     }
18664:                     $resulttext .= '</ul></li>';
18665:                 }
18666:                 if (keys(%reorderings) > 0) {
18667:                     my %sort_by_trail;
18668:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
18669:                     foreach my $key (keys(%reorderings)) {
18670:                         if ($allitems{$key} ne '') {
18671:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
18672:                         }
18673:                     }
18674:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
18675:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
18676:                     }
18677:                     $resulttext .= '</ul></li>';
18678:                 }
18679:                 if (keys(%adds) > 0) {
18680:                     my %sort_by_trail;
18681:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
18682:                     foreach my $key (keys(%adds)) {
18683:                         if ($allitems{$key} ne '') {
18684:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
18685:                         }
18686:                     }
18687:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
18688:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
18689:                     }
18690:                     $resulttext .= '</ul></li>';
18691:                 }
18692:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
18693:                 if (ref($lastactref) eq 'HASH') {
18694:                     $lastactref->{'cats'} = 1;
18695:                 }
18696:             }
18697:             $resulttext .= '</ul>';
18698:             if ($changes{'unauth'} || $changes{'auth'}) {
18699:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
18700:                 if ($changes{'auth'}) {
18701:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
18702:                 }
18703:                 if ($changes{'unauth'}) {
18704:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
18705:                 }
18706:                 my $cachetime = 24*60*60;
18707:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18708:                 if (ref($lastactref) eq 'HASH') {
18709:                     $lastactref->{'domdefaults'} = 1;
18710:                 }
18711:             }
18712:         } else {
18713:             $resulttext = '<span class="LC_error">'.
18714:                           &mt('An error occurred: [_1]',$putresult).'</span>';
18715:         }
18716:     } else {
18717:         $resulttext = &mt('No changes made to course and community categories');
18718:     }
18719:     return $resulttext;
18720: }
18721: 
18722: sub modify_serverstatuses {
18723:     my ($dom,%domconfig) = @_;
18724:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
18725:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
18726:         %currserverstatus = %{$domconfig{'serverstatuses'}};
18727:     }
18728:     my @pages = &serverstatus_pages();
18729:     foreach my $type (@pages) {
18730:         $newserverstatus{$type}{'namedusers'} = '';
18731:         $newserverstatus{$type}{'machines'} = '';
18732:         if (defined($env{'form.'.$type.'_namedusers'})) {
18733:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
18734:             my @okusers;
18735:             foreach my $user (@users) {
18736:                 my ($uname,$udom) = split(/:/,$user);
18737:                 if (($udom =~ /^$match_domain$/) &&   
18738:                     (&Apache::lonnet::domain($udom)) &&
18739:                     ($uname =~ /^$match_username$/)) {
18740:                     if (!grep(/^\Q$user\E/,@okusers)) {
18741:                         push(@okusers,$user);
18742:                     }
18743:                 }
18744:             }
18745:             if (@okusers > 0) {
18746:                  @okusers = sort(@okusers);
18747:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
18748:             }
18749:         }
18750:         if (defined($env{'form.'.$type.'_machines'})) {
18751:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
18752:             my @okmachines;
18753:             foreach my $ip (@machines) {
18754:                 my @parts = split(/\./,$ip);
18755:                 next if (@parts < 4);
18756:                 my $badip = 0;
18757:                 for (my $i=0; $i<4; $i++) {
18758:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
18759:                         $badip = 1;
18760:                         last;
18761:                     }
18762:                 }
18763:                 if (!$badip) {
18764:                     push(@okmachines,$ip);     
18765:                 }
18766:             }
18767:             @okmachines = sort(@okmachines);
18768:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
18769:         }
18770:     }
18771:     my %serverstatushash =  (
18772:                                 serverstatuses => \%newserverstatus,
18773:                             );
18774:     foreach my $type (@pages) {
18775:         foreach my $setting ('namedusers','machines') {
18776:             my (@current,@new);
18777:             if (ref($currserverstatus{$type}) eq 'HASH') {
18778:                 if ($currserverstatus{$type}{$setting} ne '') { 
18779:                     @current = split(/,/,$currserverstatus{$type}{$setting});
18780:                 }
18781:             }
18782:             if ($newserverstatus{$type}{$setting} ne '') {
18783:                 @new = split(/,/,$newserverstatus{$type}{$setting});
18784:             }
18785:             if (@current > 0) {
18786:                 if (@new > 0) {
18787:                     foreach my $item (@current) {
18788:                         if (!grep(/^\Q$item\E$/,@new)) {
18789:                             $changes{$type}{$setting} = 1;
18790:                             last;
18791:                         }
18792:                     }
18793:                     foreach my $item (@new) {
18794:                         if (!grep(/^\Q$item\E$/,@current)) {
18795:                             $changes{$type}{$setting} = 1;
18796:                             last;
18797:                         }
18798:                     }
18799:                 } else {
18800:                     $changes{$type}{$setting} = 1;
18801:                 }
18802:             } elsif (@new > 0) {
18803:                 $changes{$type}{$setting} = 1;
18804:             }
18805:         }
18806:     }
18807:     if (keys(%changes) > 0) {
18808:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
18809:         my $putresult = &Apache::lonnet::put_dom('configuration',
18810:                                                  \%serverstatushash,$dom);
18811:         if ($putresult eq 'ok') {
18812:             $resulttext .= &mt('Changes made:').'<ul>';
18813:             foreach my $type (@pages) {
18814:                 if (ref($changes{$type}) eq 'HASH') {
18815:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
18816:                     if ($changes{$type}{'namedusers'}) {
18817:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
18818:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
18819:                         } else {
18820:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
18821:                         }
18822:                     }
18823:                     if ($changes{$type}{'machines'}) {
18824:                         if ($newserverstatus{$type}{'machines'} eq '') {
18825:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
18826:                         } else {
18827:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
18828:                         }
18829: 
18830:                     }
18831:                     $resulttext .= '</ul></li>';
18832:                 }
18833:             }
18834:             $resulttext .= '</ul>';
18835:         } else {
18836:             $resulttext = '<span class="LC_error">'.
18837:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
18838: 
18839:         }
18840:     } else {
18841:         $resulttext = &mt('No changes made to access to server status pages');
18842:     }
18843:     return $resulttext;
18844: }
18845: 
18846: sub modify_helpsettings {
18847:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18848:     my ($resulttext,$errors,%changes,%helphash);
18849:     my %defaultchecked = ('submitbugs' => 'on');
18850:     my @offon = ('off','on');
18851:     my @toggles = ('submitbugs');
18852:     my %current = ('submitbugs' => '',
18853:                    'adhoc'      => {},
18854:                   );
18855:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
18856:         %current = %{$domconfig{'helpsettings'}};
18857:     }
18858:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18859:     foreach my $item (@toggles) {
18860:         if ($defaultchecked{$item} eq 'on') { 
18861:             if ($current{$item} eq '') {
18862:                 if ($env{'form.'.$item} eq '0') {
18863:                     $changes{$item} = 1;
18864:                 }
18865:             } elsif ($current{$item} ne $env{'form.'.$item}) {
18866:                 $changes{$item} = 1;
18867:             }
18868:         } elsif ($defaultchecked{$item} eq 'off') {
18869:             if ($current{$item} eq '') {
18870:                 if ($env{'form.'.$item} eq '1') {
18871:                     $changes{$item} = 1;
18872:                 }
18873:             } elsif ($current{$item} ne $env{'form.'.$item}) {
18874:                 $changes{$item} = 1;
18875:             }
18876:         }
18877:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
18878:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
18879:         }
18880:     }
18881:     my $maxnum = $env{'form.helproles_maxnum'};
18882:     my $confname = $dom.'-domainconfig';
18883:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
18884:     my (@allpos,%newsettings,%changedprivs,$newrole);
18885:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18886:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
18887:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
18888:     my %lt = &Apache::lonlocal::texthash(
18889:                     s      => 'system',
18890:                     d      => 'domain',
18891:                     order  => 'Display order',
18892:                     access => 'Role usage',
18893:                     all    => 'All with domain helpdesk or helpdesk assistant role',
18894:                     dh     => 'All with domain helpdesk role',
18895:                     da     => 'All with domain helpdesk assistant role',
18896:                     none   => 'None',
18897:                     status => 'Determined based on institutional status',
18898:                     inc    => 'Include all, but exclude specific personnel',
18899:                     exc    => 'Exclude all, but include specific personnel',
18900:     );
18901:     for (my $num=0; $num<=$maxnum; $num++) {
18902:         my ($prefix,$identifier,$rolename,%curr);
18903:         if ($num == $maxnum) {
18904:             next unless ($env{'form.newcusthelp'} == $maxnum);
18905:             $identifier = 'custhelp'.$num;
18906:             $prefix = 'helproles_'.$num;
18907:             $rolename = $env{'form.custhelpname'.$num};
18908:             $rolename=~s/[^A-Za-z0-9]//gs;
18909:             next if ($rolename eq '');
18910:             next if (exists($existing{'rolesdef_'.$rolename}));
18911:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
18912:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
18913:                                                      $newprivs{'c'},$confname,$dom);
18914:             if ($result ne 'ok') {
18915:                 $errors .= '<li><span class="LC_error">'.
18916:                            &mt('An error occurred storing the new custom role: [_1]',
18917:                            $result).'</span></li>';
18918:                 next;
18919:             } else {
18920:                 $changedprivs{$rolename} = \%newprivs;
18921:                 $newrole = $rolename;
18922:             }
18923:         } else {
18924:             $prefix = 'helproles_'.$num;
18925:             $rolename = $env{'form.'.$prefix};
18926:             next if ($rolename eq '');
18927:             next unless (exists($existing{'rolesdef_'.$rolename}));
18928:             $identifier = 'custhelp'.$num;
18929:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
18930:             my %currprivs;
18931:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
18932:                 split(/\_/,$existing{'rolesdef_'.$rolename});
18933:             foreach my $level ('c','d','s') {
18934:                 if ($newprivs{$level} ne $currprivs{$level}) {
18935:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
18936:                                                              $newprivs{'c'},$confname,$dom);
18937:                     if ($result ne 'ok') {
18938:                         $errors .= '<li><span class="LC_error">'.
18939:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
18940:                                        $rolename,$result).'</span></li>';
18941:                     } else {
18942:                         $changedprivs{$rolename} = \%newprivs;
18943:                     }
18944:                     last;
18945:                 }
18946:             }
18947:             if (ref($current{'adhoc'}) eq 'HASH') {
18948:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
18949:                     %curr = %{$current{'adhoc'}{$rolename}};
18950:                 }
18951:             }
18952:         }
18953:         my $newpos = $env{'form.'.$prefix.'_pos'};
18954:         $newpos =~ s/\D+//g;
18955:         $allpos[$newpos] = $rolename;
18956:         my $newdesc = $env{'form.'.$prefix.'_desc'};
18957:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
18958:         if ($curr{'desc'}) {
18959:             if ($curr{'desc'} ne $newdesc) {
18960:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
18961:                 $newsettings{$rolename}{'desc'} = $newdesc;
18962:             }
18963:         } elsif ($newdesc ne '') {
18964:             $changes{'customrole'}{$rolename}{'desc'} = 1;
18965:             $newsettings{$rolename}{'desc'} = $newdesc;
18966:         }
18967:         my $access = $env{'form.'.$prefix.'_access'};
18968:         if (grep(/^\Q$access\E$/,@accesstypes)) {
18969:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
18970:             if ($access eq 'status') {
18971:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
18972:                 if (scalar(@statuses) == 0) {
18973:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
18974:                 } else {
18975:                     my (@shownstatus,$numtypes);
18976:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
18977:                     if (ref($types) eq 'ARRAY') {
18978:                         $numtypes = scalar(@{$types});
18979:                         foreach my $type (sort(@statuses)) {
18980:                             if ($type eq 'default') {
18981:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
18982:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
18983:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
18984:                                 push(@shownstatus,$usertypes->{$type});
18985:                             }
18986:                         }
18987:                     }
18988:                     if (grep(/^default$/,@statuses)) {
18989:                         push(@shownstatus,$othertitle);
18990:                     }
18991:                     if (scalar(@shownstatus) == 1+$numtypes) {
18992:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
18993:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
18994:                     } else {
18995:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
18996:                         if (ref($curr{'status'}) eq 'ARRAY') {
18997:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
18998:                             if (@diffs) {
18999:                                 $changes{'customrole'}{$rolename}{$access} = 1;
19000:                             }
19001:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19002:                             $changes{'customrole'}{$rolename}{$access} = 1;
19003:                         }
19004:                     }
19005:                 }
19006:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
19007:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
19008:                 my @newspecstaff;
19009:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
19010:                 foreach my $person (sort(@personnel)) {
19011:                     if ($domhelpdesk{$person}) {
19012:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
19013:                     }
19014:                 }
19015:                 if (ref($curr{$access}) eq 'ARRAY') {
19016:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
19017:                     if (@diffs) {
19018:                         $changes{'customrole'}{$rolename}{$access} = 1;
19019:                     }
19020:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19021:                     $changes{'customrole'}{$rolename}{$access} = 1;
19022:                 }
19023:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
19024:                     my ($uname,$udom) = split(/:/,$person);
19025:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
19026:                 }
19027:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
19028:             }
19029:         } else {
19030:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
19031:         }
19032:         unless ($curr{'access'} eq $access) {
19033:             $changes{'customrole'}{$rolename}{'access'} = 1;
19034:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
19035:         }
19036:     }
19037:     if (@allpos > 0) {
19038:         my $idx = 0;
19039:         foreach my $rolename (@allpos) {
19040:             if ($rolename ne '') {
19041:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
19042:                 if (ref($current{'adhoc'}) eq 'HASH') {
19043:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
19044:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
19045:                             $changes{'customrole'}{$rolename}{'order'} = 1;
19046:                             $newsettings{$rolename}{'order'} = $idx+1;
19047:                         }
19048:                     }
19049:                 }
19050:                 $idx ++;
19051:             }
19052:         }
19053:     }
19054:     my $putresult;
19055:     if (keys(%changes) > 0) {
19056:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
19057:         if ($putresult eq 'ok') {
19058:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
19059:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
19060:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
19061:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
19062:                 }
19063:             }
19064:             my $cachetime = 24*60*60;
19065:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19066:             if (ref($lastactref) eq 'HASH') {
19067:                 $lastactref->{'domdefaults'} = 1;
19068:             }
19069:         } else {
19070:             $errors .= '<li><span class="LC_error">'.
19071:                        &mt('An error occurred storing the settings: [_1]',
19072:                            $putresult).'</span></li>';
19073:         }
19074:     }
19075:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
19076:         $resulttext = &mt('Changes made:').'<ul>';
19077:         my (%shownprivs,@levelorder);
19078:         @levelorder = ('c','d','s');
19079:         if ((keys(%changes)) && ($putresult eq 'ok')) {
19080:             foreach my $item (sort(keys(%changes))) {
19081:                 if ($item eq 'submitbugs') {
19082:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
19083:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
19084:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
19085:                 } elsif ($item eq 'customrole') {
19086:                     if (ref($changes{'customrole'}) eq 'HASH') {
19087:                         my @keyorder = ('order','desc','access','status','exc','inc');
19088:                         my %keytext = &Apache::lonlocal::texthash(
19089:                                                                    order  => 'Order',
19090:                                                                    desc   => 'Role description',
19091:                                                                    access => 'Role usage',
19092:                                                                    status => 'Allowed institutional types',
19093:                                                                    exc    => 'Allowed personnel',
19094:                                                                    inc    => 'Disallowed personnel',
19095:                         );
19096:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
19097:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
19098:                                 if ($role eq $newrole) {
19099:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
19100:                                                               $role).'<ul>';
19101:                                 } else {
19102:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19103:                                                               $role).'<ul>';
19104:                                 }
19105:                                 foreach my $key (@keyorder) {
19106:                                     if ($changes{'customrole'}{$role}{$key}) {
19107:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
19108:                                                                   $keytext{$key},$newsettings{$role}{$key}).
19109:                                                        '</li>';
19110:                                     }
19111:                                 }
19112:                                 if (ref($changedprivs{$role}) eq 'HASH') {
19113:                                     $shownprivs{$role} = 1;
19114:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
19115:                                     foreach my $level (@levelorder) {
19116:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
19117:                                             next if ($item eq '');
19118:                                             my ($priv) = split(/\&/,$item,2);
19119:                                             if (&Apache::lonnet::plaintext($priv)) {
19120:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
19121:                                                 unless ($level eq 'c') {
19122:                                                     $resulttext .= ' ('.$lt{$level}.')';
19123:                                                 }
19124:                                                 $resulttext .= '</li>';
19125:                                             }
19126:                                         }
19127:                                     }
19128:                                     $resulttext .= '</ul>';
19129:                                 }
19130:                                 $resulttext .= '</ul></li>';
19131:                             }
19132:                         }
19133:                     }
19134:                 }
19135:             }
19136:         }
19137:         if (keys(%changedprivs)) {
19138:             foreach my $role (sort(keys(%changedprivs))) {
19139:                 unless ($shownprivs{$role}) {
19140:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
19141:                                               $role).'<ul>'.
19142:                                    '<li>'.&mt('Privileges set to :').'<ul>';
19143:                     foreach my $level (@levelorder) {
19144:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
19145:                             next if ($item eq '');
19146:                             my ($priv) = split(/\&/,$item,2);
19147:                             if (&Apache::lonnet::plaintext($priv)) {
19148:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
19149:                                 unless ($level eq 'c') {
19150:                                     $resulttext .= ' ('.$lt{$level}.')';
19151:                                 }
19152:                                 $resulttext .= '</li>';
19153:                             }
19154:                         }
19155:                     }
19156:                     $resulttext .= '</ul></li></ul></li>';
19157:                 }
19158:             }
19159:         }
19160:         $resulttext .= '</ul>';
19161:     } else {
19162:         $resulttext = &mt('No changes made to help settings');
19163:     }
19164:     if ($errors) {
19165:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
19166:                                     $errors.'</ul>';
19167:     }
19168:     return $resulttext;
19169: }
19170: 
19171: sub modify_coursedefaults {
19172:     my ($dom,$lastactref,%domconfig) = @_;
19173:     my ($resulttext,$errors,%changes,%defaultshash);
19174:     my %defaultchecked = (
19175:                            'canuse_pdfforms' => 'off',
19176:                            'uselcmath'       => 'on',
19177:                            'usejsme'         => 'on'
19178:                          );
19179:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme');
19180:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
19181:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
19182:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
19183:                    'mysqltables_textbook','mysqltables_placement');
19184:     my @types = ('official','unofficial','community','textbook','placement');
19185:     my %staticdefaults = (
19186:                            anonsurvey_threshold => 10,
19187:                            uploadquota          => 500,
19188:                            postsubmit           => 60,
19189:                            mysqltables          => 172800,
19190:                          );
19191:     my %texoptions = (
19192:                         MathJax  => 'MathJax',
19193:                         mimetex  => &mt('Convert to Images'),
19194:                         tth      => &mt('TeX to HTML'),
19195:                      );
19196:     $defaultshash{'coursedefaults'} = {};
19197: 
19198:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
19199:         if ($domconfig{'coursedefaults'} eq '') {
19200:             $domconfig{'coursedefaults'} = {};
19201:         }
19202:     }
19203: 
19204:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
19205:         foreach my $item (@toggles) {
19206:             if ($defaultchecked{$item} eq 'on') {
19207:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19208:                     ($env{'form.'.$item} eq '0')) {
19209:                     $changes{$item} = 1;
19210:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19211:                     $changes{$item} = 1;
19212:                 }
19213:             } elsif ($defaultchecked{$item} eq 'off') {
19214:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
19215:                     ($env{'form.'.$item} eq '1')) {
19216:                     $changes{$item} = 1;
19217:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
19218:                     $changes{$item} = 1;
19219:                 }
19220:             }
19221:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
19222:         }
19223:         foreach my $item (@numbers) {
19224:             my ($currdef,$newdef);
19225:             $newdef = $env{'form.'.$item};
19226:             if ($item eq 'anonsurvey_threshold') {
19227:                 $currdef = $domconfig{'coursedefaults'}{$item};
19228:                 $newdef =~ s/\D//g;
19229:                 if ($newdef eq '' || $newdef < 1) {
19230:                     $newdef = 1;
19231:                 }
19232:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
19233:             } else {
19234:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
19235:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
19236:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
19237:                 }
19238:                 $newdef =~ s/[^\w.\-]//g;
19239:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
19240:             }
19241:             if ($currdef ne $newdef) {
19242:                 if ($item eq 'anonsurvey_threshold') {
19243:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
19244:                         $changes{$item} = 1;
19245:                     }
19246:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
19247:                     my $setting = $1;
19248:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
19249:                         $changes{$setting} = 1;
19250:                     }
19251:                 }
19252:             }
19253:         }
19254:         my $texengine;
19255:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
19256:             $texengine = $env{'form.texengine'};
19257:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
19258:             if ($currdef eq '') {
19259:                 unless ($texengine eq $Apache::lonnet::deftex) {
19260:                     $changes{'texengine'} = 1;
19261:                 }
19262:             } elsif ($currdef ne $texengine) {
19263:                 $changes{'texengine'} = 1;
19264:             }
19265:         }
19266:         if ($texengine ne '') {
19267:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
19268:         }
19269:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
19270:         my @currclonecode;
19271:         if (ref($currclone) eq 'HASH') {
19272:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
19273:                 @currclonecode = @{$currclone->{'instcode'}};
19274:             }
19275:         }
19276:         my $newclone;
19277:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
19278:             $newclone = $env{'form.canclone'};
19279:         }
19280:         if ($newclone eq 'instcode') {
19281:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
19282:             my (%codedefaults,@code_order,@clonecode);
19283:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
19284:                                                     \@code_order);
19285:             foreach my $item (@code_order) {
19286:                 if (grep(/^\Q$item\E$/,@newcodes)) {
19287:                     push(@clonecode,$item);
19288:                 }
19289:             }
19290:             if (@clonecode) {
19291:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
19292:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
19293:                 if (@diffs) {
19294:                     $changes{'canclone'} = 1;
19295:                 }
19296:             } else {
19297:                 $newclone eq '';
19298:             }
19299:         } elsif ($newclone ne '') {
19300:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
19301:         }
19302:         if ($newclone ne $currclone) {
19303:             $changes{'canclone'} = 1;
19304:         }
19305:         my %credits;
19306:         foreach my $type (@types) {
19307:             unless ($type eq 'community') {
19308:                 $credits{$type} = $env{'form.'.$type.'_credits'};
19309:                 $credits{$type} =~ s/[^\d.]+//g;
19310:             }
19311:         }
19312:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
19313:             ($env{'form.coursecredits'} eq '1')) {
19314:             $changes{'coursecredits'} = 1;
19315:             foreach my $type (keys(%credits)) {
19316:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19317:             }
19318:         } else {
19319:             if ($env{'form.coursecredits'} eq '1') {
19320:                 foreach my $type (@types) {
19321:                     unless ($type eq 'community') {
19322:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
19323:                             $changes{'coursecredits'} = 1;
19324:                         }
19325:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
19326:                     }
19327:                 }
19328:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19329:                 foreach my $type (@types) {
19330:                     unless ($type eq 'community') {
19331:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
19332:                             $changes{'coursecredits'} = 1;
19333:                             last;
19334:                         }
19335:                     }
19336:                 }
19337:             }
19338:         }
19339:         if ($env{'form.postsubmit'} eq '1') {
19340:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
19341:             my %currtimeout;
19342:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19343:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
19344:                     $changes{'postsubmit'} = 1;
19345:                 }
19346:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19347:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
19348:                 }
19349:             } else {
19350:                 $changes{'postsubmit'} = 1;
19351:             }
19352:             foreach my $type (@types) {
19353:                 my $timeout = $env{'form.'.$type.'_timeout'};
19354:                 $timeout =~ s/\D//g;
19355:                 if ($timeout == $staticdefaults{'postsubmit'}) {
19356:                     $timeout = '';
19357:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
19358:                     $timeout = '0';
19359:                 }
19360:                 unless ($timeout eq '') {
19361:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
19362:                 }
19363:                 if (exists($currtimeout{$type})) {
19364:                     if ($timeout ne $currtimeout{$type}) {
19365:                         $changes{'postsubmit'} = 1;
19366:                     }
19367:                 } elsif ($timeout ne '') {
19368:                     $changes{'postsubmit'} = 1;
19369:                 }
19370:             }
19371:         } else {
19372:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
19373:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19374:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
19375:                     $changes{'postsubmit'} = 1;
19376:                 }
19377:             } else {
19378:                 $changes{'postsubmit'} = 1;
19379:             }
19380:         }
19381:     }
19382:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19383:                                              $dom);
19384:     if ($putresult eq 'ok') {
19385:         if (keys(%changes) > 0) {
19386:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19387:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
19388:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
19389:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'})) {
19390:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','texengine') {
19391:                     if ($changes{$item}) {
19392:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
19393:                     }
19394:                 }
19395:                 if ($changes{'coursecredits'}) {
19396:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19397:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
19398:                             $domdefaults{$type.'credits'} =
19399:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
19400:                         }
19401:                     }
19402:                 }
19403:                 if ($changes{'postsubmit'}) {
19404:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19405:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
19406:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19407:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
19408:                                 $domdefaults{$type.'postsubtimeout'} =
19409:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19410:                             }
19411:                         }
19412:                     }
19413:                 }
19414:                 if ($changes{'uploadquota'}) {
19415:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19416:                         foreach my $type (@types) {
19417:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
19418:                         }
19419:                     }
19420:                 }
19421:                 if ($changes{'canclone'}) {
19422:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
19423:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
19424:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
19425:                             if (@clonecodes) {
19426:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
19427:                             }
19428:                         }
19429:                     } else {
19430:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
19431:                     }
19432:                 }
19433:                 my $cachetime = 24*60*60;
19434:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19435:                 if (ref($lastactref) eq 'HASH') {
19436:                     $lastactref->{'domdefaults'} = 1;
19437:                 }
19438:             }
19439:             $resulttext = &mt('Changes made:').'<ul>';
19440:             foreach my $item (sort(keys(%changes))) {
19441:                 if ($item eq 'canuse_pdfforms') {
19442:                     if ($env{'form.'.$item} eq '1') {
19443:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
19444:                     } else {
19445:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
19446:                     }
19447:                 } elsif ($item eq 'uselcmath') {
19448:                     if ($env{'form.'.$item} eq '1') {
19449:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
19450:                     } else {
19451:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
19452:                     }
19453:                 } elsif ($item eq 'usejsme') {
19454:                     if ($env{'form.'.$item} eq '1') {
19455:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
19456:                     } else {
19457:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
19458:                     }
19459:                 } elsif ($item eq 'texengine') {
19460:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
19461:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
19462:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
19463:                     }
19464:                 } elsif ($item eq 'anonsurvey_threshold') {
19465:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
19466:                 } elsif ($item eq 'uploadquota') {
19467:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
19468:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
19469:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
19470:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
19471:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
19472:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
19473:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
19474:                                        '</ul>'.
19475:                                        '</li>';
19476:                     } else {
19477:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
19478:                     }
19479:                 } elsif ($item eq 'mysqltables') {
19480:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
19481:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
19482:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
19483:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
19484:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
19485:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
19486:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
19487:                                        '</ul>'.
19488:                                        '</li>';
19489:                     } else {
19490:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
19491:                     }
19492:                 } elsif ($item eq 'postsubmit') {
19493:                     if ($domdefaults{'postsubmit'} eq 'off') {
19494:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
19495:                     } else {
19496:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
19497:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
19498:                             $resulttext .= &mt('durations:').'<ul>';
19499:                             foreach my $type (@types) {
19500:                                 $resulttext .= '<li>';
19501:                                 my $timeout;
19502:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
19503:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
19504:                                 }
19505:                                 my $display;
19506:                                 if ($timeout eq '0') {
19507:                                     $display = &mt('unlimited');
19508:                                 } elsif ($timeout eq '') {
19509:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
19510:                                 } else {
19511:                                     $display = &mt('[quant,_1,second]',$timeout);
19512:                                 }
19513:                                 if ($type eq 'community') {
19514:                                     $resulttext .= &mt('Communities');
19515:                                 } elsif ($type eq 'official') {
19516:                                     $resulttext .= &mt('Official courses');
19517:                                 } elsif ($type eq 'unofficial') {
19518:                                     $resulttext .= &mt('Unofficial courses');
19519:                                 } elsif ($type eq 'textbook') {
19520:                                     $resulttext .= &mt('Textbook courses');
19521:                                 } elsif ($type eq 'placement') {
19522:                                     $resulttext .= &mt('Placement tests');
19523:                                 }
19524:                                 $resulttext .= ' -- '.$display.'</li>';
19525:                             }
19526:                             $resulttext .= '</ul>';
19527:                         }
19528:                         $resulttext .= '</li>';
19529:                     }
19530:                 } elsif ($item eq 'coursecredits') {
19531:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
19532:                         if (($domdefaults{'officialcredits'} eq '') &&
19533:                             ($domdefaults{'unofficialcredits'} eq '') &&
19534:                             ($domdefaults{'textbookcredits'} eq '')) {
19535:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
19536:                         } else {
19537:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
19538:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
19539:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
19540:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
19541:                                            '</ul>'.
19542:                                            '</li>';
19543:                         }
19544:                     } else {
19545:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
19546:                     }
19547:                 } elsif ($item eq 'canclone') {
19548:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
19549:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
19550:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
19551:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
19552:                         }
19553:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
19554:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
19555:                     } else {
19556:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
19557:                     }
19558:                 }
19559:             }
19560:             $resulttext .= '</ul>';
19561:         } else {
19562:             $resulttext = &mt('No changes made to course defaults');
19563:         }
19564:     } else {
19565:         $resulttext = '<span class="LC_error">'.
19566:             &mt('An error occurred: [_1]',$putresult).'</span>';
19567:     }
19568:     return $resulttext;
19569: }
19570: 
19571: sub modify_selfenrollment {
19572:     my ($dom,$lastactref,%domconfig) = @_;
19573:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
19574:     my @types = ('official','unofficial','community','textbook','placement');
19575:     my %titles = &tool_titles();
19576:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
19577:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
19578:     $ordered{'default'} = ['types','registered','approval','limit'];
19579: 
19580:     my (%roles,%shown,%toplevel);
19581:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
19582: 
19583:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
19584:         if ($domconfig{'selfenrollment'} eq '') {
19585:             $domconfig{'selfenrollment'} = {};
19586:         }
19587:     }
19588:     %toplevel = (
19589:                   admin      => 'Configuration Rights',
19590:                   default    => 'Default settings',
19591:                   validation => 'Validation of self-enrollment requests',
19592:                 );
19593:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
19594: 
19595:     if (ref($ordered{'admin'}) eq 'ARRAY') {
19596:         foreach my $item (@{$ordered{'admin'}}) {
19597:             foreach my $type (@types) {
19598:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
19599:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
19600:                 } else {
19601:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
19602:                 }
19603:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
19604:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
19605:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
19606:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
19607:                             push(@{$changes{'admin'}{$type}},$item);
19608:                         }
19609:                     } else {
19610:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
19611:                             push(@{$changes{'admin'}{$type}},$item);
19612:                         }
19613:                     }
19614:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
19615:                     push(@{$changes{'admin'}{$type}},$item);
19616:                 }
19617:             }
19618:         }
19619:     }
19620: 
19621:     foreach my $item (@{$ordered{'default'}}) {
19622:         foreach my $type (@types) {
19623:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
19624:             if ($item eq 'types') {
19625:                 unless (($value eq 'all') || ($value eq 'dom')) {
19626:                     $value = '';
19627:                 }
19628:             } elsif ($item eq 'registered') {
19629:                 unless ($value eq '1') {
19630:                     $value = 0;
19631:                 }
19632:             } elsif ($item eq 'approval') {
19633:                 unless ($value =~ /^[012]$/) {
19634:                     $value = 0;
19635:                 }
19636:             } else {
19637:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
19638:                     $value = 'none';
19639:                 }
19640:             }
19641:             $selfenrollhash{'default'}{$type}{$item} = $value;
19642:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
19643:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
19644:                     if ($selfenrollhash{'default'}{$type}{$item} ne
19645:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
19646:                          push(@{$changes{'default'}{$type}},$item);
19647:                     }
19648:                 } else {
19649:                     push(@{$changes{'default'}{$type}},$item);
19650:                 }
19651:             } else {
19652:                 push(@{$changes{'default'}{$type}},$item);
19653:             }
19654:             if ($item eq 'limit') {
19655:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
19656:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
19657:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
19658:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
19659:                     }
19660:                 } else {
19661:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
19662:                 }
19663:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
19664:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
19665:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
19666:                          push(@{$changes{'default'}{$type}},'cap');
19667:                     }
19668:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
19669:                     push(@{$changes{'default'}{$type}},'cap');
19670:                 }
19671:             }
19672:         }
19673:     }
19674: 
19675:     foreach my $item (@{$itemsref}) {
19676:         if ($item eq 'fields') {
19677:             my @changed;
19678:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
19679:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
19680:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
19681:             }
19682:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
19683:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
19684:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
19685:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
19686:                 } else {
19687:                     @changed = @{$selfenrollhash{'validation'}{$item}};
19688:                 }
19689:             } else {
19690:                 @changed = @{$selfenrollhash{'validation'}{$item}};
19691:             }
19692:             if (@changed) {
19693:                 if ($selfenrollhash{'validation'}{$item}) { 
19694:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
19695:                 } else {
19696:                     $changes{'validation'}{$item} = &mt('None');
19697:                 }
19698:             }
19699:         } else {
19700:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
19701:             if ($item eq 'markup') {
19702:                if ($env{'form.selfenroll_validation_'.$item}) {
19703:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
19704:                }
19705:             }
19706:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
19707:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
19708:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
19709:                 }
19710:             }
19711:         }
19712:     }
19713: 
19714:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
19715:                                              $dom);
19716:     if ($putresult eq 'ok') {
19717:         if (keys(%changes) > 0) {
19718:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19719:             $resulttext = &mt('Changes made:').'<ul>';
19720:             foreach my $key ('admin','default','validation') {
19721:                 if (ref($changes{$key}) eq 'HASH') {
19722:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
19723:                     if ($key eq 'validation') {
19724:                         foreach my $item (@{$itemsref}) {
19725:                             if (exists($changes{$key}{$item})) {
19726:                                 if ($item eq 'markup') {
19727:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
19728:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
19729:                                 } else {  
19730:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
19731:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
19732:                                 }
19733:                             }
19734:                         }
19735:                     } else {
19736:                         foreach my $type (@types) {
19737:                             if ($type eq 'community') {
19738:                                 $roles{'1'} = &mt('Community personnel');
19739:                             } else {
19740:                                 $roles{'1'} = &mt('Course personnel');
19741:                             }
19742:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
19743:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
19744:                                     if ($key eq 'admin') {
19745:                                         my @mgrdc = ();
19746:                                         if (ref($ordered{$key}) eq 'ARRAY') {
19747:                                             foreach my $item (@{$ordered{'admin'}}) {
19748:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
19749:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
19750:                                                         push(@mgrdc,$item);
19751:                                                     }
19752:                                                 }
19753:                                             }
19754:                                             if (@mgrdc) {
19755:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
19756:                                             } else {
19757:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
19758:                                             }
19759:                                         }
19760:                                     } else {
19761:                                         if (ref($ordered{$key}) eq 'ARRAY') {
19762:                                             foreach my $item (@{$ordered{$key}}) {
19763:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
19764:                                                     $domdefaults{$type.'selfenroll'.$item} =
19765:                                                         $selfenrollhash{$key}{$type}{$item};
19766:                                                 }
19767:                                             }
19768:                                         }
19769:                                     }
19770:                                 }
19771:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
19772:                                 foreach my $item (@{$ordered{$key}}) {
19773:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
19774:                                         $resulttext .= '<li>';
19775:                                         if ($key eq 'admin') {
19776:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
19777:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
19778:                                         } else {
19779:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
19780:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
19781:                                         }
19782:                                         $resulttext .= '</li>';
19783:                                     }
19784:                                 }
19785:                                 $resulttext .= '</ul></li>';
19786:                             }
19787:                         }
19788:                         $resulttext .= '</ul></li>'; 
19789:                     }
19790:                 }
19791:             }
19792:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
19793:                 my $cachetime = 24*60*60;
19794:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19795:                 if (ref($lastactref) eq 'HASH') {
19796:                     $lastactref->{'domdefaults'} = 1;
19797:                 }
19798:             }
19799:             $resulttext .= '</ul>';
19800:         } else {
19801:             $resulttext = &mt('No changes made to self-enrollment settings');
19802:         }
19803:     } else {
19804:         $resulttext = '<span class="LC_error">'.
19805:             &mt('An error occurred: [_1]',$putresult).'</span>';
19806:     }
19807:     return $resulttext;
19808: }
19809: 
19810: sub modify_wafproxy {
19811:     my ($dom,$action,$lastactref,%domconfig) = @_;
19812:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
19813:     my (%othercontrol,%canset,%values,%curralias,%currvalue,@warnings,%wafproxy,
19814:         %changes,%expirecache);
19815:     foreach my $server (sort(keys(%servers))) {
19816:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
19817:         if ($serverhome eq $server) {
19818:             my $serverdom = &Apache::lonnet::host_domain($server);
19819:             if ($serverdom eq $dom) {
19820:                 $canset{$server} = 1;
19821:             }
19822:         }
19823:     }
19824:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
19825:         %{$values{$dom}} = ();
19826:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
19827:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
19828:         }
19829:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
19830:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
19831:         }
19832:     }
19833:     my $output;
19834:     if (keys(%canset)) {
19835:         %{$wafproxy{'alias'}} = ();
19836:         foreach my $key (sort(keys(%canset))) {
19837:             if ($env{'form.wafproxy_'.$dom}) {
19838:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
19839:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
19840:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
19841:                     $changes{'alias'} = 1;
19842:                 }
19843:             } else {
19844:                 $wafproxy{'alias'}{$key} = '';
19845:                 if ($curralias{$key}) {
19846:                     $changes{'alias'} = 1;
19847:                 }
19848:             }
19849:             if ($wafproxy{'alias'}{$key} eq '') {
19850:                 if ($curralias{$key}) {
19851:                     $expirecache{$key} = 1;
19852:                 }
19853:                 delete($wafproxy{'alias'}{$key});
19854:             }
19855:         }
19856:         unless (keys(%{$wafproxy{'alias'}})) {
19857:             delete($wafproxy{'alias'});
19858:         }
19859:         # Localization for values in %warn occus in &mt() calls separately.
19860:         my %warn = (
19861:                      trusted => 'trusted IP range(s)',
19862:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
19863:                      vpnext => 'IP range(s) for backend WAF connections',
19864:                    );
19865:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
19866:             my $possible = $env{'form.wafproxy_'.$item};
19867:             $possible =~ s/^\s+|\s+$//g;
19868:             if ($possible ne '') {
19869:                 if ($item eq 'remoteip') {
19870:                     if ($possible =~ /^[mhn]$/) {
19871:                         $wafproxy{$item} = $possible;
19872:                     }
19873:                 } elsif ($item eq 'ipheader') {
19874:                     if ($wafproxy{'remoteip'} eq 'h') {
19875:                         $wafproxy{$item} = $possible;
19876:                     }
19877:                 } else {
19878:                     my (@ok,$count);
19879:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
19880:                         unless ($env{'form.wafproxy_vpnaccess'}) {
19881:                             $possible = '';
19882:                         }
19883:                     } elsif ($item eq 'trusted') {
19884:                         unless ($wafproxy{'remoteip'} eq 'h') {
19885:                             $possible = '';
19886:                         }
19887:                     }
19888:                     unless ($possible eq '') {
19889:                         $possible =~ s/[\r\n]+/\s/g;
19890:                         $possible =~ s/\s*-\s*/-/g;
19891:                         $possible =~ s/\s+/,/g;
19892:                     }
19893:                     $count = 0;
19894:                     if ($possible ne '') {
19895:                         foreach my $poss (split(/\,/,$possible)) {
19896:                             $count ++;
19897:                             if (&validate_ip_pattern($poss)) {
19898:                                 push(@ok,$poss);
19899:                             }
19900:                         }
19901:                         if (@ok) {
19902:                             $wafproxy{$item} = join(',',@ok);
19903:                         }
19904:                         my $diff = $count - scalar(@ok);
19905:                         if ($diff) {
19906:                             push(@warnings,'<li>'.
19907:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
19908:                                      $diff,$warn{$item}).
19909:                                  '</li>');
19910:                         }
19911:                     }
19912:                 }
19913:                 if ($wafproxy{$item} ne $currvalue{$item}) {
19914:                     $changes{$item} = 1;
19915:                 }
19916:             } elsif ($currvalue{$item}) {
19917:                 $changes{$item} = 1;
19918:             } 
19919:         }
19920:     } else {
19921:         if (keys(%curralias)) {
19922:             $changes{'alias'} = 1;
19923:         } 
19924:         if (keys(%currvalue)) {
19925:             foreach my $key (keys(%currvalue)) {
19926:                 $changes{$key} = 1;
19927:             }
19928:         }
19929:     }
19930:     if (keys(%changes)) {
19931:         my %defaultshash = (
19932:                               wafproxy => \%wafproxy,
19933:                            ); 
19934:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
19935:                                                  $dom);
19936:         if ($putresult eq 'ok') {
19937:             my $cachetime = 24*60*60;
19938:             my (%domdefaults,$updatedomdefs);
19939:             foreach my $item ('ipheader','trusted','vpnint','vpnext') {
19940:                 if ($changes{$item}) {
19941:                     unless ($updatedomdefs) {
19942:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
19943:                         $updatedomdefs = 1;
19944:                     }
19945:                     if ($wafproxy{$item}) {
19946:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
19947:                     } elsif (exists($domdefaults{'waf_'.$item})) {
19948:                         delete($domdefaults{'waf_'.$item});
19949:                     } 
19950:                 }
19951:             }
19952:             if ($updatedomdefs) {
19953:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19954:                 if (ref($lastactref) eq 'HASH') {
19955:                     $lastactref->{'domdefaults'} = 1;
19956:                 }
19957:             }
19958:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
19959:                 my %updates = %expirecache;
19960:                 foreach my $key (keys(%expirecache)) {
19961:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
19962:                 }
19963:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
19964:                     my $cachetime = 24*60*60;
19965:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
19966:                         $updates{$key} = 1;
19967:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
19968:                                                       $cachetime);
19969:                     }
19970:                 }
19971:                 if (ref($lastactref) eq 'HASH') {
19972:                     $lastactref->{'proxyalias'} = \%updates;
19973:                 }
19974:             }
19975:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
19976:             foreach my $item ('alias','remoteip','ipheader','trusted','vpnint','vpnext') {
19977:                 if ($changes{$item}) {
19978:                     if ($item eq 'alias') {
19979:                         my $numaliased = 0;
19980:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
19981:                             my $shown;
19982:                             if (keys(%{$wafproxy{'alias'}})) {
19983:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
19984:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
19985:                                                          &Apache::lonnet::hostname($server),
19986:                                                          $wafproxy{'alias'}{$server}).'</li>';
19987:                                     $numaliased ++;
19988:                                 }
19989:                                 if ($numaliased) {
19990:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
19991:                                                           '<ul>'.$shown.'</ul>').'</li>';
19992:                                 }
19993:                             }
19994:                         }
19995:                         unless ($numaliased) {
19996:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
19997:                         }
19998:                     } else {
19999:                         if ($item eq 'remoteip') {
20000:                             my %ip_methods = &remoteip_methods();
20001:                             if ($wafproxy{$item} =~ /^[mh]$/) {
20002:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
20003:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
20004:                             } else {
20005:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
20006:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
20007:                                                '</li>';
20008:                                 } else {
20009:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
20010:                                 }
20011:                             }
20012:                         } elsif ($item eq 'ipheader') {
20013:                             if ($wafproxy{$item}) {
20014:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
20015:                                                       $wafproxy{$item}).'</li>';
20016:                             } else {
20017:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
20018:                             }
20019:                         } elsif ($item eq 'trusted') {
20020:                             if ($wafproxy{$item}) {
20021:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
20022:                                                       $wafproxy{$item}).'</li>';
20023:                             } else {
20024:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
20025:                             }
20026:                         } elsif ($item eq 'vpnint') {
20027:                             if ($wafproxy{$item}) {
20028:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
20029:                                                        $wafproxy{$item}).'</li>';
20030:                             } else {
20031:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
20032:                             }
20033:                         } elsif ($item eq 'vpnext') {
20034:                             if ($wafproxy{$item}) {
20035:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
20036:                                                        $wafproxy{$item}).'</li>';
20037:                             } else {
20038:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
20039:                             }
20040:                         }
20041:                     }
20042:                 }
20043:             }
20044:         } else {
20045:             $output = '<span class="LC_error">'.
20046:                       &mt('An error occurred: [_1]',$putresult).'</span>';
20047:         }
20048:     } elsif (keys(%canset)) {
20049:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
20050:     }
20051:     if (@warnings) {
20052:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
20053:                        join("\n",@warnings).'</ul>';
20054:     }
20055:     return $output;
20056: }
20057: 
20058: sub validate_ip_pattern {
20059:     my ($pattern) = @_;
20060:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
20061:         my ($start,$end) = ($1,$2);
20062:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
20063:             return 1;
20064:         }
20065:     } elsif (&Net::CIDR::cidrvalidate($pattern)) {
20066:         return 1;
20067:     }
20068:     return
20069: }
20070: 
20071: sub modify_usersessions {
20072:     my ($dom,$lastactref,%domconfig) = @_;
20073:     my @hostingtypes = ('version','excludedomain','includedomain');
20074:     my @offloadtypes = ('primary','default');
20075:     my %types = (
20076:                   remote => \@hostingtypes,
20077:                   hosted => \@hostingtypes,
20078:                   spares => \@offloadtypes,
20079:                 );
20080:     my @prefixes = ('remote','hosted','spares');
20081:     my @lcversions = &Apache::lonnet::all_loncaparevs();
20082:     my (%by_ip,%by_location,@intdoms,@instdoms);
20083:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20084:     my @locations = sort(keys(%by_location));
20085:     my (%defaultshash,%changes);
20086:     foreach my $prefix (@prefixes) {
20087:         $defaultshash{'usersessions'}{$prefix} = {};
20088:     }
20089:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20090:     my $resulttext;
20091:     my %iphost = &Apache::lonnet::get_iphost();
20092:     foreach my $prefix (@prefixes) {
20093:         next if ($prefix eq 'spares');
20094:         foreach my $type (@{$types{$prefix}}) {
20095:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20096:             if ($type eq 'version') {
20097:                 my $value = $env{'form.'.$prefix.'_'.$type};
20098:                 my $okvalue;
20099:                 if ($value ne '') {
20100:                     if (grep(/^\Q$value\E$/,@lcversions)) {
20101:                         $okvalue = $value;
20102:                     }
20103:                 }
20104:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20105:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20106:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
20107:                             if ($inuse == 0) {
20108:                                 $changes{$prefix}{$type} = 1;
20109:                             } else {
20110:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
20111:                                     $changes{$prefix}{$type} = 1;
20112:                                 }
20113:                                 if ($okvalue ne '') {
20114:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20115:                                 } 
20116:                             }
20117:                         } else {
20118:                             if (($inuse == 1) && ($okvalue ne '')) {
20119:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20120:                                 $changes{$prefix}{$type} = 1;
20121:                             }
20122:                         }
20123:                     } else {
20124:                         if (($inuse == 1) && ($okvalue ne '')) {
20125:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20126:                             $changes{$prefix}{$type} = 1;
20127:                         }
20128:                     }
20129:                 } else {
20130:                     if (($inuse == 1) && ($okvalue ne '')) {
20131:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
20132:                         $changes{$prefix}{$type} = 1;
20133:                     }
20134:                 }
20135:             } else {
20136:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20137:                 my @okvals;
20138:                 foreach my $val (@vals) {
20139:                     if ($val =~ /:/) {
20140:                         my @items = split(/:/,$val);
20141:                         foreach my $item (@items) {
20142:                             if (ref($by_location{$item}) eq 'ARRAY') {
20143:                                 push(@okvals,$item);
20144:                             }
20145:                         }
20146:                     } else {
20147:                         if (ref($by_location{$val}) eq 'ARRAY') {
20148:                             push(@okvals,$val);
20149:                         }
20150:                     }
20151:                 }
20152:                 @okvals = sort(@okvals);
20153:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
20154:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
20155:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20156:                             if ($inuse == 0) {
20157:                                 $changes{$prefix}{$type} = 1; 
20158:                             } else {
20159:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20160:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
20161:                                 if (@changed > 0) {
20162:                                     $changes{$prefix}{$type} = 1;
20163:                                 }
20164:                             }
20165:                         } else {
20166:                             if ($inuse == 1) {
20167:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20168:                                 $changes{$prefix}{$type} = 1;
20169:                             }
20170:                         } 
20171:                     } else {
20172:                         if ($inuse == 1) {
20173:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20174:                             $changes{$prefix}{$type} = 1;
20175:                         }
20176:                     }
20177:                 } else {
20178:                     if ($inuse == 1) {
20179:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
20180:                         $changes{$prefix}{$type} = 1;
20181:                     }
20182:                 }
20183:             }
20184:         }
20185:     }
20186: 
20187:     my @alldoms = &Apache::lonnet::all_domains();
20188:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20189:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
20190:     my $savespares;
20191: 
20192:     foreach my $lonhost (sort(keys(%servers))) {
20193:         my $serverhomeID =
20194:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
20195:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
20196:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
20197:         my %spareschg;
20198:         foreach my $type (@{$types{'spares'}}) {
20199:             my @okspares;
20200:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
20201:             foreach my $server (@checked) {
20202:                 if (&Apache::lonnet::hostname($server) ne '') {
20203:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
20204:                         unless (grep(/^\Q$server\E$/,@okspares)) {
20205:                             push(@okspares,$server);
20206:                         }
20207:                     }
20208:                 }
20209:             }
20210:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
20211:             my $newspare;
20212:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
20213:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
20214:                     $newspare = $new;
20215:                 }
20216:             }
20217:             my @spares;
20218:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
20219:                 @spares = sort(@okspares,$newspare);
20220:             } else {
20221:                 @spares = sort(@okspares);
20222:             }
20223:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
20224:             if (ref($spareid{$lonhost}) eq 'HASH') {
20225:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
20226:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
20227:                     if (@diffs > 0) {
20228:                         $spareschg{$type} = 1;
20229:                     }
20230:                 }
20231:             }
20232:         }
20233:         if (keys(%spareschg) > 0) {
20234:             $changes{'spares'}{$lonhost} = \%spareschg;
20235:         }
20236:     }
20237:     $defaultshash{'usersessions'}{'offloadnow'} = {};
20238:     $defaultshash{'usersessions'}{'offloadoth'} = {};
20239:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
20240:     my @okoffload;
20241:     if (@offloadnow) {
20242:         foreach my $server (@offloadnow) {
20243:             if (&Apache::lonnet::hostname($server) ne '') {
20244:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
20245:                     push(@okoffload,$server);
20246:                 }
20247:             }
20248:         }
20249:         if (@okoffload) {
20250:             foreach my $lonhost (@okoffload) {
20251:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
20252:             }
20253:         }
20254:     }
20255:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
20256:     my @okoffloadoth;
20257:     if (@offloadoth) {
20258:         foreach my $server (@offloadoth) {
20259:             if (&Apache::lonnet::hostname($server) ne '') {
20260:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
20261:                     push(@okoffloadoth,$server);
20262:                 }
20263:             }
20264:         }
20265:         if (@okoffloadoth) {
20266:             foreach my $lonhost (@okoffloadoth) {
20267:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
20268:             }
20269:         }
20270:     }
20271:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
20272:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
20273:             if (ref($changes{'spares'}) eq 'HASH') {
20274:                 if (keys(%{$changes{'spares'}}) > 0) {
20275:                     $savespares = 1;
20276:                 }
20277:             }
20278:         } else {
20279:             $savespares = 1;
20280:         }
20281:         foreach my $offload ('offloadnow','offloadoth') {
20282:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
20283:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
20284:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
20285:                         $changes{$offload} = 1;
20286:                         last;
20287:                     }
20288:                 }
20289:                 unless ($changes{$offload}) {
20290:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
20291:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
20292:                             $changes{$offload} = 1;
20293:                             last;
20294:                         }
20295:                     }
20296:                 }
20297:             } else {
20298:                 if (($offload eq 'offloadnow') && (@okoffload)) {
20299:                      $changes{'offloadnow'} = 1;
20300:                 }
20301:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
20302:                     $changes{'offloadoth'} = 1;
20303:                 }
20304:             } 
20305:         }
20306:     } else {
20307:         if (@okoffload) {
20308:             $changes{'offloadnow'} = 1;
20309:         }
20310:         if (@okoffloadoth) {
20311:             $changes{'offloadoth'} = 1;
20312:         }
20313:     }
20314:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
20315:     if ((keys(%changes) > 0) || ($savespares)) {
20316:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20317:                                                  $dom);
20318:         if ($putresult eq 'ok') {
20319:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20320:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
20321:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
20322:                 }
20323:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
20324:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
20325:                 }
20326:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20327:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
20328:                 }
20329:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20330:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
20331:                 }
20332:             }
20333:             my $cachetime = 24*60*60;
20334:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20335:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
20336:             if (ref($lastactref) eq 'HASH') {
20337:                 $lastactref->{'domdefaults'} = 1;
20338:                 $lastactref->{'usersessions'} = 1;
20339:             }
20340:             if (keys(%changes) > 0) {
20341:                 my %lt = &usersession_titles();
20342:                 $resulttext = &mt('Changes made:').'<ul>';
20343:                 foreach my $prefix (@prefixes) {
20344:                     if (ref($changes{$prefix}) eq 'HASH') {
20345:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
20346:                         if ($prefix eq 'spares') {
20347:                             if (ref($changes{$prefix}) eq 'HASH') {
20348:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
20349:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
20350:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
20351:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
20352:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
20353:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
20354:                                         foreach my $type (@{$types{$prefix}}) {
20355:                                             if ($changes{$prefix}{$lonhost}{$type}) {
20356:                                                 my $offloadto = &mt('None');
20357:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
20358:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
20359:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
20360:                                                     }
20361:                                                 }
20362:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
20363:                                             }
20364:                                         }
20365:                                     }
20366:                                     $resulttext .= '</li>';
20367:                                 }
20368:                             }
20369:                         } else {
20370:                             foreach my $type (@{$types{$prefix}}) {
20371:                                 if (defined($changes{$prefix}{$type})) {
20372:                                     my ($newvalue,$notinuse);
20373:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
20374:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
20375:                                             if ($type eq 'version') {
20376:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
20377:                                             } else {
20378:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
20379:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
20380:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
20381:                                                     }
20382:                                                 } else {
20383:                                                     $notinuse = 1;
20384:                                                 }
20385:                                             }
20386:                                         }
20387:                                     }
20388:                                     if ($newvalue eq '') {
20389:                                         if ($type eq 'version') {
20390:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
20391:                                         } elsif ($notinuse) {
20392:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
20393:                                         } else {
20394:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
20395:                                         }
20396:                                     } else {
20397:                                         if ($type eq 'version') {
20398:                                             $newvalue .= ' '.&mt('(or later)');
20399:                                         }
20400:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
20401:                                     }
20402:                                 }
20403:                             }
20404:                         }
20405:                         $resulttext .= '</ul>';
20406:                     }
20407:                 }
20408:                 if ($changes{'offloadnow'}) {
20409:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
20410:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
20411:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
20412:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
20413:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20414:                             }
20415:                             $resulttext .= '</ul>';
20416:                         } else {
20417:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
20418:                         }
20419:                     } else {
20420:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
20421:                     }
20422:                 }
20423:                 if ($changes{'offloadoth'}) {
20424:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
20425:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
20426:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
20427:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
20428:                                 $resulttext .= '<li>'.$lonhost.'</li>';
20429:                             }
20430:                             $resulttext .= '</ul>';
20431:                         } else {
20432:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
20433:                         }
20434:                     } else {
20435:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
20436:                     }
20437:                 }
20438:                 $resulttext .= '</ul>';
20439:             } else {
20440:                 $resulttext = $nochgmsg;
20441:             }
20442:         } else {
20443:             $resulttext = '<span class="LC_error">'.
20444:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20445:         }
20446:     } else {
20447:         $resulttext = $nochgmsg;
20448:     }
20449:     return $resulttext;
20450: }
20451: 
20452: sub modify_ssl {
20453:     my ($dom,$lastactref,%domconfig) = @_;
20454:     my (%by_ip,%by_location,@intdoms,@instdoms);
20455:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20456:     my @locations = sort(keys(%by_location));
20457:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20458:     my (%defaultshash,%changes);
20459:     my $action = 'ssl';
20460:     my @prefixes = ('connto','connfrom','replication');
20461:     foreach my $prefix (@prefixes) {
20462:         $defaultshash{$action}{$prefix} = {};
20463:     }
20464:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20465:     my $resulttext;
20466:     my %iphost = &Apache::lonnet::get_iphost();
20467:     my @reptypes = ('certreq','nocertreq');
20468:     my @connecttypes = ('dom','intdom','other');
20469:     my %types = (
20470:                   connto      => \@connecttypes,
20471:                   connfrom    => \@connecttypes,
20472:                   replication => \@reptypes,
20473:                 );
20474:     foreach my $prefix (sort(keys(%types))) {
20475:         foreach my $type (@{$types{$prefix}}) {
20476:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
20477:                 my $value = 'yes';
20478:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
20479:                     $value = $env{'form.'.$prefix.'_'.$type};
20480:                 }
20481:                 if (ref($domconfig{$action}) eq 'HASH') {
20482:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
20483:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
20484:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
20485:                                 $changes{$prefix}{$type} = 1;
20486:                             }
20487:                             $defaultshash{$action}{$prefix}{$type} = $value;
20488:                         } else {
20489:                             $defaultshash{$action}{$prefix}{$type} = $value;
20490:                             $changes{$prefix}{$type} = 1;
20491:                         }
20492:                     } else {
20493:                         $defaultshash{$action}{$prefix}{$type} = $value;
20494:                         $changes{$prefix}{$type} = 1;
20495:                     }
20496:                 } else {
20497:                     $defaultshash{$action}{$prefix}{$type} = $value;
20498:                     $changes{$prefix}{$type} = 1;
20499:                 }
20500:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
20501:                     delete($changes{$prefix}{$type});
20502:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
20503:                     delete($changes{$prefix}{$type});
20504:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
20505:                     delete($changes{$prefix}{$type});
20506:                 }
20507:             } elsif ($prefix eq 'replication') {
20508:                 if (@locations > 0) {
20509:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20510:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20511:                     my @okvals;
20512:                     foreach my $val (@vals) {
20513:                         if ($val =~ /:/) {
20514:                             my @items = split(/:/,$val);
20515:                             foreach my $item (@items) {
20516:                                 if (ref($by_location{$item}) eq 'ARRAY') {
20517:                                     push(@okvals,$item);
20518:                                 }
20519:                             }
20520:                         } else {
20521:                             if (ref($by_location{$val}) eq 'ARRAY') {
20522:                                 push(@okvals,$val);
20523:                             }
20524:                         }
20525:                     }
20526:                     @okvals = sort(@okvals);
20527:                     if (ref($domconfig{$action}) eq 'HASH') {
20528:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
20529:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
20530:                                 if ($inuse == 0) {
20531:                                     $changes{$prefix}{$type} = 1;
20532:                                 } else {
20533:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
20534:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
20535:                                     if (@changed > 0) {
20536:                                         $changes{$prefix}{$type} = 1;
20537:                                     }
20538:                                 }
20539:                             } else {
20540:                                 if ($inuse == 1) {
20541:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
20542:                                     $changes{$prefix}{$type} = 1;
20543:                                 }
20544:                             }
20545:                         } else {
20546:                             if ($inuse == 1) {
20547:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
20548:                                 $changes{$prefix}{$type} = 1;
20549:                             }
20550:                         }
20551:                     } else {
20552:                         if ($inuse == 1) {
20553:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
20554:                             $changes{$prefix}{$type} = 1;
20555:                         }
20556:                     }
20557:                 }
20558:             }
20559:         }
20560:     }
20561:     if (keys(%changes)) {
20562:         foreach my $prefix (keys(%changes)) {
20563:             if (ref($changes{$prefix}) eq 'HASH') {
20564:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
20565:                     delete($changes{$prefix});
20566:                 }
20567:             } else {
20568:                 delete($changes{$prefix});
20569:             }
20570:         }
20571:     }
20572:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
20573:     if (keys(%changes) > 0) {
20574:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20575:                                                  $dom);
20576:         if ($putresult eq 'ok') {
20577:             if (ref($defaultshash{$action}) eq 'HASH') {
20578:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
20579:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
20580:                 }
20581:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
20582:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
20583:                 }
20584:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
20585:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
20586:                 }
20587:             }
20588:             my $cachetime = 24*60*60;
20589:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20590:             if (ref($lastactref) eq 'HASH') {
20591:                 $lastactref->{'domdefaults'} = 1;
20592:             }
20593:             if (keys(%changes) > 0) {
20594:                 my %titles = &ssl_titles();
20595:                 $resulttext = &mt('Changes made:').'<ul>';
20596:                 foreach my $prefix (@prefixes) {
20597:                     if (ref($changes{$prefix}) eq 'HASH') {
20598:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
20599:                         foreach my $type (@{$types{$prefix}}) {
20600:                             if (defined($changes{$prefix}{$type})) {
20601:                                 my ($newvalue,$notinuse);
20602:                                 if (ref($defaultshash{$action}) eq 'HASH') {
20603:                                     if (ref($defaultshash{$action}{$prefix})) {
20604:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
20605:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
20606:                                         } else {
20607:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
20608:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
20609:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
20610:                                                 }
20611:                                             } else {
20612:                                                 $notinuse = 1;
20613:                                             }
20614:                                         }
20615:                                     }
20616:                                     if ($notinuse) {
20617:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
20618:                                     } elsif ($newvalue eq '') {
20619:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
20620:                                     } else {
20621:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
20622:                                     }
20623:                                 }
20624:                             }
20625:                         }
20626:                         $resulttext .= '</ul>';
20627:                     }
20628:                 }
20629:             } else {
20630:                 $resulttext = $nochgmsg;
20631:             }
20632:         } else {
20633:             $resulttext = '<span class="LC_error">'.
20634:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20635:         }
20636:     } else {
20637:         $resulttext = $nochgmsg;
20638:     }
20639:     return $resulttext;
20640: }
20641: 
20642: sub modify_trust {
20643:     my ($dom,$lastactref,%domconfig) = @_;
20644:     my (%by_ip,%by_location,@intdoms,@instdoms);
20645:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
20646:     my @locations = sort(keys(%by_location));
20647:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
20648:     my @types = ('exc','inc');
20649:     my (%defaultshash,%changes);
20650:     foreach my $prefix (@prefixes) {
20651:         $defaultshash{'trust'}{$prefix} = {};
20652:     }
20653:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20654:     my $resulttext;
20655:     foreach my $prefix (@prefixes) {
20656:         foreach my $type (@types) {
20657:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
20658:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
20659:             my @okvals;
20660:             foreach my $val (@vals) {
20661:                 if ($val =~ /:/) {
20662:                     my @items = split(/:/,$val);
20663:                     foreach my $item (@items) {
20664:                         if (ref($by_location{$item}) eq 'ARRAY') {
20665:                             push(@okvals,$item);
20666:                         }
20667:                     }
20668:                 } else {
20669:                     if (ref($by_location{$val}) eq 'ARRAY') {
20670:                         push(@okvals,$val);
20671:                     }
20672:                 }
20673:             }
20674:             @okvals = sort(@okvals);
20675:             if (ref($domconfig{'trust'}) eq 'HASH') {
20676:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
20677:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
20678:                         if ($inuse == 0) {
20679:                             $changes{$prefix}{$type} = 1;
20680:                         } else {
20681:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20682:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
20683:                             if (@changed > 0) {
20684:                                 $changes{$prefix}{$type} = 1;
20685:                             }
20686:                         }
20687:                     } else {
20688:                         if ($inuse == 1) {
20689:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20690:                             $changes{$prefix}{$type} = 1;
20691:                         }
20692:                     }
20693:                 } else {
20694:                     if ($inuse == 1) {
20695:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20696:                         $changes{$prefix}{$type} = 1;
20697:                     }
20698:                 }
20699:             } else {
20700:                 if ($inuse == 1) {
20701:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
20702:                     $changes{$prefix}{$type} = 1;
20703:                 }
20704:             }
20705:         }
20706:     }
20707:     my $nochgmsg = &mt('No changes made to trust settings.');
20708:     if (keys(%changes) > 0) {
20709:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
20710:                                                  $dom);
20711:         if ($putresult eq 'ok') {
20712:             if (ref($defaultshash{'trust'}) eq 'HASH') {
20713:                 foreach my $prefix (@prefixes) {
20714:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
20715:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
20716:                     }
20717:                 }
20718:             }
20719:             my $cachetime = 24*60*60;
20720:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20721:             if (ref($lastactref) eq 'HASH') {
20722:                 $lastactref->{'domdefaults'} = 1;
20723:             }
20724:             if (keys(%changes) > 0) {
20725:                 my %lt = &trust_titles();
20726:                 $resulttext = &mt('Changes made:').'<ul>';
20727:                 foreach my $prefix (@prefixes) {
20728:                     if (ref($changes{$prefix}) eq 'HASH') {
20729:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
20730:                         foreach my $type (@types) {
20731:                             if (defined($changes{$prefix}{$type})) {
20732:                                 my ($newvalue,$notinuse);
20733:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
20734:                                     if (ref($defaultshash{'trust'}{$prefix})) {
20735:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
20736:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
20737:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
20738:                                             }
20739:                                         } else {
20740:                                             $notinuse = 1;
20741:                                         }
20742:                                     }
20743:                                 }
20744:                                 if ($notinuse) {
20745:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
20746:                                 } elsif ($newvalue eq '') {
20747:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
20748:                                 } else {
20749:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
20750:                                 }
20751:                             }
20752:                         }
20753:                         $resulttext .= '</ul>';
20754:                     }
20755:                 }
20756:                 $resulttext .= '</ul>';
20757:             } else {
20758:                 $resulttext = $nochgmsg;
20759:             }
20760:         } else {
20761:             $resulttext = '<span class="LC_error">'.
20762:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20763:         }
20764:     } else {
20765:         $resulttext = $nochgmsg;
20766:     }
20767:     return $resulttext;
20768: }
20769: 
20770: sub modify_loadbalancing {
20771:     my ($dom,%domconfig) = @_;
20772:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
20773:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
20774:     my ($othertitle,$usertypes,$types) =
20775:         &Apache::loncommon::sorted_inst_types($dom);
20776:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
20777:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
20778:     my @sparestypes = ('primary','default');
20779:     my %typetitles = &sparestype_titles();
20780:     my $resulttext;
20781:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
20782:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
20783:         %existing = %{$domconfig{'loadbalancing'}};
20784:     }
20785:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
20786:                               \%currtargets,\%currrules,\%currcookies);
20787:     my ($saveloadbalancing,%defaultshash,%changes);
20788:     my ($alltypes,$othertypes,$titles) =
20789:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
20790:     my %ruletitles = &offloadtype_text();
20791:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
20792:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
20793:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
20794:         if ($balancer eq '') {
20795:             next;
20796:         }
20797:         if (!exists($servers{$balancer})) {
20798:             if (exists($currbalancer{$balancer})) {
20799:                 push(@{$changes{'delete'}},$balancer);
20800:             }
20801:             next;
20802:         }
20803:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
20804:             push(@{$changes{'delete'}},$balancer);
20805:             next;
20806:         }
20807:         if (!exists($currbalancer{$balancer})) {
20808:             push(@{$changes{'add'}},$balancer);
20809:         }
20810:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
20811:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
20812:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
20813:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
20814:             $saveloadbalancing = 1;
20815:         }
20816:         foreach my $sparetype (@sparestypes) {
20817:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
20818:             my @offloadto;
20819:             foreach my $target (@targets) {
20820:                 if (($servers{$target}) && ($target ne $balancer)) {
20821:                     if ($sparetype eq 'default') {
20822:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
20823:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
20824:                         }
20825:                     }
20826:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
20827:                         push(@offloadto,$target);
20828:                     }
20829:                 }
20830:             }
20831:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
20832:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
20833:                     push(@offloadto,$balancer);
20834:                 }
20835:             }
20836:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
20837:         }
20838:         if ($env{'form.loadbalancing_cookie_'.$i}) {
20839:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
20840:             if (exists($currbalancer{$balancer})) { 
20841:                 unless ($currcookies{$balancer}) {
20842:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
20843:                 }
20844:             }
20845:         } elsif (exists($currbalancer{$balancer})) {
20846:             if ($currcookies{$balancer}) {
20847:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
20848:             }
20849:         }
20850:         if (ref($currtargets{$balancer}) eq 'HASH') {
20851:             foreach my $sparetype (@sparestypes) {
20852:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
20853:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
20854:                     if (@targetdiffs > 0) {
20855:                         $changes{'curr'}{$balancer}{'targets'} = 1;
20856:                     }
20857:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20858:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
20859:                         $changes{'curr'}{$balancer}{'targets'} = 1;
20860:                     }
20861:                 }
20862:             }
20863:         } else {
20864:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
20865:                 foreach my $sparetype (@sparestypes) {
20866:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20867:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
20868:                             $changes{'curr'}{$balancer}{'targets'} = 1;
20869:                         }
20870:                     }
20871:                 }
20872:             }
20873:         }
20874:         my $ishomedom;
20875:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
20876:             $ishomedom = 1;
20877:         }
20878:         if (ref($alltypes) eq 'ARRAY') {
20879:             foreach my $type (@{$alltypes}) {
20880:                 my $rule;
20881:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
20882:                          (!$ishomedom)) {
20883:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
20884:                 }
20885:                 if ($rule eq 'specific') {
20886:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
20887:                     if (exists($servers{$specifiedhost})) {
20888:                         $rule = $specifiedhost;
20889:                     }
20890:                 }
20891:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
20892:                 if (ref($currrules{$balancer}) eq 'HASH') {
20893:                     if ($rule ne $currrules{$balancer}{$type}) {
20894:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
20895:                     }
20896:                 } elsif ($rule ne '') {
20897:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
20898:                 }
20899:             }
20900:         }
20901:     }
20902:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
20903:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
20904:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
20905:             $defaultshash{'loadbalancing'} = {};
20906:         }
20907:         my $putresult = &Apache::lonnet::put_dom('configuration',
20908:                                                  \%defaultshash,$dom);
20909:         if ($putresult eq 'ok') {
20910:             if (keys(%changes) > 0) {
20911:                 my %toupdate;
20912:                 if (ref($changes{'delete'}) eq 'ARRAY') {
20913:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
20914:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
20915:                         $toupdate{$balancer} = 1;
20916:                     }
20917:                 }
20918:                 if (ref($changes{'add'}) eq 'ARRAY') {
20919:                     foreach my $balancer (sort(@{$changes{'add'}})) {
20920:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
20921:                         $toupdate{$balancer} = 1;
20922:                     }
20923:                 }
20924:                 if (ref($changes{'curr'}) eq 'HASH') {
20925:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
20926:                         $toupdate{$balancer} = 1;
20927:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
20928:                             if ($changes{'curr'}{$balancer}{'targets'}) {
20929:                                 my %offloadstr;
20930:                                 foreach my $sparetype (@sparestypes) {
20931:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20932:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
20933:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
20934:                                         }
20935:                                     }
20936:                                 }
20937:                                 if (keys(%offloadstr) == 0) {
20938:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
20939:                                 } else {
20940:                                     my $showoffload;
20941:                                     foreach my $sparetype (@sparestypes) {
20942:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
20943:                                         if (defined($offloadstr{$sparetype})) {
20944:                                             $showoffload .= $offloadstr{$sparetype};
20945:                                         } else {
20946:                                             $showoffload .= &mt('None');
20947:                                         }
20948:                                         $showoffload .= ('&nbsp;'x3);
20949:                                     }
20950:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
20951:                                 }
20952:                             }
20953:                         }
20954:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
20955:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
20956:                                 foreach my $type (@{$alltypes}) {
20957:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
20958:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
20959:                                         my $balancetext;
20960:                                         if ($rule eq '') {
20961:                                             $balancetext =  $ruletitles{'default'};
20962:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
20963:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
20964:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
20965:                                                 foreach my $sparetype (@sparestypes) {
20966:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
20967:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
20968:                                                     }
20969:                                                 }
20970:                                                 foreach my $item (@{$alltypes}) {
20971:                                                     next if ($item =~  /^_LC_ipchange/);
20972:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
20973:                                                     if ($hasrule eq 'homeserver') {
20974:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
20975:                                                     } else {
20976:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
20977:                                                             if ($servers{$hasrule}) {
20978:                                                                 $toupdate{$hasrule} = 1;
20979:                                                             }
20980:                                                         }
20981:                                                     }
20982:                                                 }
20983:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
20984:                                                     $balancetext =  $ruletitles{$rule};
20985:                                                 } else {
20986:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
20987:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
20988:                                                     if ($receiver) {
20989:                                                         $toupdate{$receiver};
20990:                                                     }
20991:                                                 }
20992:                                             } else {
20993:                                                 $balancetext =  $ruletitles{$rule};
20994:                                             }
20995:                                         } else {
20996:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
20997:                                         }
20998:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
20999:                                     }
21000:                                 }
21001:                             }
21002:                         }
21003:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
21004:                             $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
21005:                                                       $balancer).'</li>'; 
21006:                         }
21007:                     }
21008:                 }
21009:                 if (keys(%toupdate)) {
21010:                     my %thismachine;
21011:                     my $updatedhere;
21012:                     my $cachetime = 60*60*24;
21013:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
21014:                     foreach my $lonhost (keys(%toupdate)) {
21015:                         if ($thismachine{$lonhost}) {
21016:                             unless ($updatedhere) {
21017:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
21018:                                                               $defaultshash{'loadbalancing'},
21019:                                                               $cachetime);
21020:                                 $updatedhere = 1;
21021:                             }
21022:                         } else {
21023:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
21024:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
21025:                         }
21026:                     }
21027:                 }
21028:                 if ($resulttext ne '') {
21029:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
21030:                 } else {
21031:                     $resulttext = $nochgmsg;
21032:                 }
21033:             } else {
21034:                 $resulttext = $nochgmsg;
21035:             }
21036:         } else {
21037:             $resulttext = '<span class="LC_error">'.
21038:                           &mt('An error occurred: [_1]',$putresult).'</span>';
21039:         }
21040:     } else {
21041:         $resulttext = $nochgmsg;
21042:     }
21043:     return $resulttext;
21044: }
21045: 
21046: sub recurse_check {
21047:     my ($chkcats,$categories,$depth,$name) = @_;
21048:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
21049:         my $chg = 0;
21050:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
21051:             my $category = $chkcats->[$depth]{$name}[$j];
21052:             my $item;
21053:             if ($category eq '') {
21054:                 $chg ++;
21055:             } else {
21056:                 my $deeper = $depth + 1;
21057:                 $item = &escape($category).':'.&escape($name).':'.$depth;
21058:                 if ($chg) {
21059:                     $categories->{$item} -= $chg;
21060:                 }
21061:                 &recurse_check($chkcats,$categories,$deeper,$category);
21062:                 $deeper --;
21063:             }
21064:         }
21065:     }
21066:     return;
21067: }
21068: 
21069: sub recurse_cat_deletes {
21070:     my ($item,$coursecategories,$deletions) = @_;
21071:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
21072:     my $subdepth = $depth + 1;
21073:     if (ref($coursecategories) eq 'HASH') {
21074:         foreach my $subitem (keys(%{$coursecategories})) {
21075:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
21076:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
21077:                 delete($coursecategories->{$subitem});
21078:                 $deletions->{$subitem} = 1;
21079:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
21080:             }
21081:         }
21082:     }
21083:     return;
21084: }
21085: 
21086: sub active_dc_picker {
21087:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
21088:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
21089:     my @domcoord = keys(%domcoords);
21090:     if (keys(%currhash)) {
21091:         foreach my $dc (keys(%currhash)) {
21092:             unless (exists($domcoords{$dc})) {
21093:                 push(@domcoord,$dc);
21094:             }
21095:         }
21096:     }
21097:     @domcoord = sort(@domcoord);
21098:     my $numdcs = scalar(@domcoord);
21099:     my $rows = 0;
21100:     my $table;
21101:     if ($numdcs > 1) {
21102:         $table = '<table>';
21103:         for (my $i=0; $i<@domcoord; $i++) {
21104:             my $rem = $i%($numinrow);
21105:             if ($rem == 0) {
21106:                 if ($i > 0) {
21107:                     $table .= '</tr>';
21108:                 }
21109:                 $table .= '<tr>';
21110:                 $rows ++;
21111:             }
21112:             my $check = '';
21113:             if ($inputtype eq 'radio') {
21114:                 if (keys(%currhash) == 0) {
21115:                     if (!$i) {
21116:                         $check = ' checked="checked"';
21117:                     }
21118:                 } elsif (exists($currhash{$domcoord[$i]})) {
21119:                     $check = ' checked="checked"';
21120:                 }
21121:             } else {
21122:                 if (exists($currhash{$domcoord[$i]})) {
21123:                     $check = ' checked="checked"';
21124:                 }
21125:             }
21126:             if ($i == @domcoord - 1) {
21127:                 my $colsleft = $numinrow - $rem;
21128:                 if ($colsleft > 1) {
21129:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
21130:                 } else {
21131:                     $table .= '<td class="LC_left_item">';
21132:                 }
21133:             } else {
21134:                 $table .= '<td class="LC_left_item">';
21135:             }
21136:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
21137:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21138:             $table .= '<span class="LC_nobreak"><label>'.
21139:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
21140:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
21141:             if ($user ne $dcname.':'.$dcdom) {
21142:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21143:             }
21144:             $table .= '</label></span></td>';
21145:         }
21146:         $table .= '</tr></table>';
21147:     } elsif ($numdcs == 1) {
21148:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
21149:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
21150:         if ($inputtype eq 'radio') {
21151:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
21152:             if ($user ne $dcname.':'.$dcdom) {
21153:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21154:             }
21155:         } else {
21156:             my $check;
21157:             if (exists($currhash{$domcoord[0]})) {
21158:                 $check = ' checked="checked"';
21159:             }
21160:             $table = '<span class="LC_nobreak"><label>'.
21161:                      '<input type="checkbox" name="'.$name.'" '.
21162:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
21163:             if ($user ne $dcname.':'.$dcdom) {
21164:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
21165:             }
21166:             $table .= '</label></span>';
21167:             $rows ++;
21168:         }
21169:     }
21170:     return ($numdcs,$table,$rows);
21171: }
21172: 
21173: sub usersession_titles {
21174:     return &Apache::lonlocal::texthash(
21175:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
21176:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
21177:                spares => 'Servers offloaded to, when busy',
21178:                version => 'LON-CAPA version requirement',
21179:                excludedomain => 'Allow all, but exclude specific domains',
21180:                includedomain => 'Deny all, but include specific domains',
21181:                primary => 'Primary (checked first)',
21182:                default => 'Default',
21183:            );
21184: }
21185: 
21186: sub id_for_thisdom {
21187:     my (%servers) = @_;
21188:     my %altids;
21189:     foreach my $server (keys(%servers)) {
21190:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21191:         if ($serverhome ne $server) {
21192:             $altids{$serverhome} = $server;
21193:         }
21194:     }
21195:     return %altids;
21196: }
21197: 
21198: sub count_servers {
21199:     my ($currbalancer,%servers) = @_;
21200:     my (@spares,$numspares);
21201:     foreach my $lonhost (sort(keys(%servers))) {
21202:         next if ($currbalancer eq $lonhost);
21203:         push(@spares,$lonhost);
21204:     }
21205:     if ($currbalancer) {
21206:         $numspares = scalar(@spares);
21207:     } else {
21208:         $numspares = scalar(@spares) - 1;
21209:     }
21210:     return ($numspares,@spares);
21211: }
21212: 
21213: sub lonbalance_targets_js {
21214:     my ($dom,$types,$servers,$settings) = @_;
21215:     my $select = &mt('Select');
21216:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
21217:     if (ref($servers) eq 'HASH') {
21218:         $alltargets = join("','",sort(keys(%{$servers})));
21219:         my @homedoms;
21220:         foreach my $server (sort(keys(%{$servers}))) {
21221:             if (&Apache::lonnet::host_domain($server) eq $dom) {
21222:                 push(@homedoms,'1');
21223:             } else {
21224:                 push(@homedoms,'0');
21225:             }
21226:         }
21227:         $allishome = join("','",@homedoms);
21228:     }
21229:     if (ref($types) eq 'ARRAY') {
21230:         if (@{$types} > 0) {
21231:             @alltypes = @{$types};
21232:         }
21233:     }
21234:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
21235:     $allinsttypes = join("','",@alltypes);
21236:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
21237:     if (ref($settings) eq 'HASH') {
21238:         %existing = %{$settings};
21239:     }
21240:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
21241:                               \%currtargets,\%currrules,\%currcookies);
21242:     my $balancers = join("','",sort(keys(%currbalancer)));
21243:     return <<"END";
21244: 
21245: <script type="text/javascript">
21246: // <![CDATA[
21247: 
21248: currBalancers = new Array('$balancers');
21249: 
21250: function toggleTargets(balnum) {
21251:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21252:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
21253:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
21254:     var prevbalancer = prevhostitem.value;
21255:     var baltotal = document.getElementById('loadbalancing_total').value;
21256:     prevhostitem.value = balancer;
21257:     if (prevbalancer != '') {
21258:         var prevIdx = currBalancers.indexOf(prevbalancer);
21259:         if (prevIdx != -1) {
21260:             currBalancers.splice(prevIdx,1);
21261:         }
21262:     }
21263:     if (balancer == '') {
21264:         hideSpares(balnum);
21265:     } else {
21266:         var currIdx = currBalancers.indexOf(balancer);
21267:         if (currIdx == -1) {
21268:             currBalancers.push(balancer);
21269:         }
21270:         var homedoms = new Array('$allishome');
21271:         var ishomedom = homedoms[lonhostitem.selectedIndex];
21272:         showSpares(balancer,ishomedom,balnum);
21273:     }
21274:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
21275:     return;
21276: }
21277: 
21278: function showSpares(balancer,ishomedom,balnum) {
21279:     var alltargets = new Array('$alltargets');
21280:     var insttypes = new Array('$allinsttypes');
21281:     var offloadtypes = new Array('primary','default');
21282: 
21283:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
21284:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
21285:  
21286:     for (var i=0; i<offloadtypes.length; i++) {
21287:         var count = 0;
21288:         for (var j=0; j<alltargets.length; j++) {
21289:             if (alltargets[j] != balancer) {
21290:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
21291:                 item.value = alltargets[j];
21292:                 item.style.textAlign='left';
21293:                 item.style.textFace='normal';
21294:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
21295:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
21296:                     item.disabled = '';
21297:                 } else {
21298:                     item.disabled = 'disabled';
21299:                     item.checked = false;
21300:                 }
21301:                 count ++;
21302:             }
21303:         }
21304:     }
21305:     for (var k=0; k<insttypes.length; k++) {
21306:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
21307:             if (ishomedom == 1) {
21308:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21309:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21310:             } else {
21311:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21312:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21313:             }
21314:         } else {
21315:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
21316:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
21317:         }
21318:         if ((insttypes[k] != '_LC_external') && 
21319:             ((insttypes[k] != '_LC_internetdom') ||
21320:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
21321:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
21322:             item.options.length = 0;
21323:             item.options[0] = new Option("","",true,true);
21324:             var idx = 0;
21325:             for (var m=0; m<alltargets.length; m++) {
21326:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
21327:                     idx ++;
21328:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
21329:                 }
21330:             }
21331:         }
21332:     }
21333:     return;
21334: }
21335: 
21336: function hideSpares(balnum) {
21337:     var alltargets = new Array('$alltargets');
21338:     var insttypes = new Array('$allinsttypes');
21339:     var offloadtypes = new Array('primary','default');
21340: 
21341:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
21342:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
21343: 
21344:     var total = alltargets.length - 1;
21345:     for (var i=0; i<offloadtypes; i++) {
21346:         for (var j=0; j<total; j++) {
21347:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
21348:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
21349:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
21350:         }
21351:     }
21352:     for (var k=0; k<insttypes.length; k++) {
21353:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
21354:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
21355:         if (insttypes[k] != '_LC_external') {
21356:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
21357:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
21358:         }
21359:     }
21360:     return;
21361: }
21362: 
21363: function checkOffloads(item,balnum,type) {
21364:     var alltargets = new Array('$alltargets');
21365:     var offloadtypes = new Array('primary','default');
21366:     if (item.checked) {
21367:         var total = alltargets.length - 1;
21368:         var other;
21369:         if (type == offloadtypes[0]) {
21370:             other = offloadtypes[1];
21371:         } else {
21372:             other = offloadtypes[0];
21373:         }
21374:         for (var i=0; i<total; i++) {
21375:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
21376:             if (server == item.value) {
21377:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
21378:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
21379:                 }
21380:             }
21381:         }
21382:     }
21383:     return;
21384: }
21385: 
21386: function singleServerToggle(balnum,type) {
21387:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
21388:     if (offloadtoSelIdx == 0) {
21389:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
21390:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21391: 
21392:     } else {
21393:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
21394:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21395:     }
21396:     return;
21397: }
21398: 
21399: function balanceruleChange(formname,balnum,type) {
21400:     if (type == '_LC_external') {
21401:         return;
21402:     }
21403:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
21404:     for (var i=0; i<typesRules.length; i++) {
21405:         if (formname.elements[typesRules[i]].checked) {
21406:             if (formname.elements[typesRules[i]].value != 'specific') {
21407:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
21408:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
21409:             } else {
21410:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
21411:             }
21412:         }
21413:     }
21414:     return;
21415: }
21416: 
21417: function balancerDeleteChange(balnum) {
21418:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
21419:     var baltotal = document.getElementById('loadbalancing_total').value;
21420:     var addtarget;
21421:     var removetarget;
21422:     var action = 'delete';
21423:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
21424:         var lonhost = hostitem.value;
21425:         var currIdx = currBalancers.indexOf(lonhost);
21426:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
21427:             if (currIdx != -1) {
21428:                 currBalancers.splice(currIdx,1);
21429:             }
21430:             addtarget = lonhost;
21431:         } else {
21432:             if (currIdx == -1) {
21433:                 currBalancers.push(lonhost);
21434:             }
21435:             removetarget = lonhost;
21436:             action = 'undelete';
21437:         }
21438:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
21439:     }
21440:     return;
21441: }
21442: 
21443: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
21444:     if (baltotal > 1) {
21445:         var offloadtypes = new Array('primary','default');
21446:         var alltargets = new Array('$alltargets');
21447:         var insttypes = new Array('$allinsttypes');
21448:         for (var i=0; i<baltotal; i++) {
21449:             if (i != balnum) {
21450:                 for (var j=0; j<offloadtypes.length; j++) {
21451:                     var total = alltargets.length - 1;
21452:                     for (var k=0; k<total; k++) {
21453:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
21454:                         var server = serveritem.value;
21455:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
21456:                             if (server == addtarget) {
21457:                                 serveritem.disabled = '';
21458:                             }
21459:                         }
21460:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
21461:                             if (server == removetarget) {
21462:                                 serveritem.disabled = 'disabled';
21463:                                 serveritem.checked = false;
21464:                             }
21465:                         }
21466:                     }
21467:                 }
21468:                 for (var j=0; j<insttypes.length; j++) {
21469:                     if (insttypes[j] != '_LC_external') {
21470:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
21471:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
21472:                             var currSel = singleserver.selectedIndex;
21473:                             var currVal = singleserver.options[currSel].value;
21474:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
21475:                                 var numoptions = singleserver.options.length;
21476:                                 var needsnew = 1;
21477:                                 for (var k=0; k<numoptions; k++) {
21478:                                     if (singleserver.options[k] == addtarget) {
21479:                                         needsnew = 0;
21480:                                         break;
21481:                                     }
21482:                                 }
21483:                                 if (needsnew == 1) {
21484:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
21485:                                 }
21486:                             }
21487:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
21488:                                 singleserver.options.length = 0;
21489:                                 if ((currVal) && (currVal != removetarget)) {
21490:                                     singleserver.options[0] = new Option("","",false,false);
21491:                                 } else {
21492:                                     singleserver.options[0] = new Option("","",true,true);
21493:                                 }
21494:                                 var idx = 0;
21495:                                 for (var m=0; m<alltargets.length; m++) {
21496:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
21497:                                         idx ++;
21498:                                         if (currVal == alltargets[m]) {
21499:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
21500:                                         } else {
21501:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
21502:                                         }
21503:                                     }
21504:                                 }
21505:                             }
21506:                         }
21507:                     }
21508:                 }
21509:             }
21510:         }
21511:     }
21512:     return;
21513: }
21514: 
21515: // ]]>
21516: </script>
21517: 
21518: END
21519: }
21520: 
21521: 
21522: sub new_spares_js {
21523:     my @sparestypes = ('primary','default');
21524:     my $types = join("','",@sparestypes);
21525:     my $select = &mt('Select');
21526:     return <<"END";
21527: 
21528: <script type="text/javascript">
21529: // <![CDATA[
21530: 
21531: function updateNewSpares(formname,lonhost) {
21532:     var types = new Array('$types');
21533:     var include = new Array();
21534:     var exclude = new Array();
21535:     for (var i=0; i<types.length; i++) {
21536:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
21537:         for (var j=0; j<spareboxes.length; j++) {
21538:             if (formname.elements[spareboxes[j]].checked) {
21539:                 exclude.push(formname.elements[spareboxes[j]].value);
21540:             } else {
21541:                 include.push(formname.elements[spareboxes[j]].value);
21542:             }
21543:         }
21544:     }
21545:     for (var i=0; i<types.length; i++) {
21546:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
21547:         var selIdx = newSpare.selectedIndex;
21548:         var currnew = newSpare.options[selIdx].value;
21549:         var okSpares = new Array();
21550:         for (var j=0; j<newSpare.options.length; j++) {
21551:             var possible = newSpare.options[j].value;
21552:             if (possible != '') {
21553:                 if (exclude.indexOf(possible) == -1) {
21554:                     okSpares.push(possible);
21555:                 } else {
21556:                     if (currnew == possible) {
21557:                         selIdx = 0;
21558:                     }
21559:                 }
21560:             }
21561:         }
21562:         for (var k=0; k<include.length; k++) {
21563:             if (okSpares.indexOf(include[k]) == -1) {
21564:                 okSpares.push(include[k]);
21565:             }
21566:         }
21567:         okSpares.sort();
21568:         newSpare.options.length = 0;
21569:         if (selIdx == 0) {
21570:             newSpare.options[0] = new Option("$select","",true,true);
21571:         } else {
21572:             newSpare.options[0] = new Option("$select","",false,false);
21573:         }
21574:         for (var m=0; m<okSpares.length; m++) {
21575:             var idx = m+1;
21576:             var selThis = 0;
21577:             if (selIdx != 0) {
21578:                 if (okSpares[m] == currnew) {
21579:                     selThis = 1;
21580:                 }
21581:             }
21582:             if (selThis == 1) {
21583:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
21584:             } else {
21585:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
21586:             }
21587:         }
21588:     }
21589:     return;
21590: }
21591: 
21592: function checkNewSpares(lonhost,type) {
21593:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
21594:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
21595:     if (chosen != '') {
21596:         var othertype;
21597:         var othernewSpare;
21598:         if (type == 'primary') {
21599:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
21600:         }
21601:         if (type == 'default') {
21602:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
21603:         }
21604:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
21605:             othernewSpare.selectedIndex = 0;
21606:         }
21607:     }
21608:     return;
21609: }
21610: 
21611: // ]]>
21612: </script>
21613: 
21614: END
21615: 
21616: }
21617: 
21618: sub common_domprefs_js {
21619:     return <<"END";
21620: 
21621: <script type="text/javascript">
21622: // <![CDATA[
21623: 
21624: function getIndicesByName(formname,item) {
21625:     var group = new Array();
21626:     for (var i=0;i<formname.elements.length;i++) {
21627:         if (formname.elements[i].name == item) {
21628:             group.push(formname.elements[i].id);
21629:         }
21630:     }
21631:     return group;
21632: }
21633: 
21634: // ]]>
21635: </script>
21636: 
21637: END
21638: 
21639: }
21640: 
21641: sub recaptcha_js {
21642:     my %lt = &captcha_phrases();
21643:     return <<"END";
21644: 
21645: <script type="text/javascript">
21646: // <![CDATA[
21647: 
21648: function updateCaptcha(caller,context) {
21649:     var privitem;
21650:     var pubitem;
21651:     var privtext;
21652:     var pubtext;
21653:     var versionitem;
21654:     var versiontext;
21655:     if (document.getElementById(context+'_recaptchapub')) {
21656:         pubitem = document.getElementById(context+'_recaptchapub');
21657:     } else {
21658:         return;
21659:     }
21660:     if (document.getElementById(context+'_recaptchapriv')) {
21661:         privitem = document.getElementById(context+'_recaptchapriv');
21662:     } else {
21663:         return;
21664:     }
21665:     if (document.getElementById(context+'_recaptchapubtxt')) {
21666:         pubtext = document.getElementById(context+'_recaptchapubtxt');
21667:     } else {
21668:         return;
21669:     }
21670:     if (document.getElementById(context+'_recaptchaprivtxt')) {
21671:         privtext = document.getElementById(context+'_recaptchaprivtxt');
21672:     } else {
21673:         return;
21674:     }
21675:     if (document.getElementById(context+'_recaptchaversion')) {
21676:         versionitem = document.getElementById(context+'_recaptchaversion');
21677:     } else {
21678:         return;
21679:     }
21680:     if (document.getElementById(context+'_recaptchavertxt')) {
21681:         versiontext = document.getElementById(context+'_recaptchavertxt');
21682:     } else {
21683:         return;
21684:     }
21685:     if (caller.checked) {
21686:         if (caller.value == 'recaptcha') {
21687:             pubitem.type = 'text';
21688:             privitem.type = 'text';
21689:             pubitem.size = '40';
21690:             privitem.size = '40';
21691:             pubtext.innerHTML = "$lt{'pub'}";
21692:             privtext.innerHTML = "$lt{'priv'}";
21693:             versionitem.type = 'text';
21694:             versionitem.size = '3';
21695:             versiontext.innerHTML = "$lt{'ver'}";
21696:         } else {
21697:             pubitem.type = 'hidden';
21698:             privitem.type = 'hidden';
21699:             versionitem.type = 'hidden';
21700:             pubtext.innerHTML = '';
21701:             privtext.innerHTML = '';
21702:             versiontext.innerHTML = '';
21703:         }
21704:     }
21705:     return;
21706: }
21707: 
21708: // ]]>
21709: </script>
21710: 
21711: END
21712: 
21713: }
21714: 
21715: sub toggle_display_js {
21716:     return <<"END";
21717: 
21718: <script type="text/javascript">
21719: // <![CDATA[
21720: 
21721: function toggleDisplay(domForm,caller) {
21722:     if (document.getElementById(caller)) {
21723:         var divitem = document.getElementById(caller);
21724:         var optionsElement = domForm.coursecredits;
21725:         var checkval = 1;
21726:         var dispval = 'block';
21727:         var selfcreateRegExp = /^cancreate_emailverified/;
21728:         if (caller == 'emailoptions') {
21729:             optionsElement = domForm.cancreate_email;
21730:         }
21731:         if (caller == 'studentsubmission') {
21732:             optionsElement = domForm.postsubmit;
21733:         }
21734:         if (caller == 'cloneinstcode') {
21735:             optionsElement = domForm.canclone;
21736:             checkval = 'instcode';
21737:         }
21738:         if (selfcreateRegExp.test(caller)) {
21739:             optionsElement = domForm.elements[caller];
21740:             checkval = 'other';
21741:             dispval = 'inline'
21742:         }
21743:         if (optionsElement.length) {
21744:             var currval;
21745:             for (var i=0; i<optionsElement.length; i++) {
21746:                 if (optionsElement[i].checked) {
21747:                    currval = optionsElement[i].value;
21748:                 }
21749:             }
21750:             if (currval == checkval) {
21751:                 divitem.style.display = dispval;
21752:             } else {
21753:                 divitem.style.display = 'none';
21754:             }
21755:         }
21756:     }
21757:     return;
21758: }
21759: 
21760: // ]]>
21761: </script>
21762: 
21763: END
21764: 
21765: }
21766: 
21767: sub captcha_phrases {
21768:     return &Apache::lonlocal::texthash (
21769:                  priv => 'Private key',
21770:                  pub  => 'Public key',
21771:                  original  => 'original (CAPTCHA)',
21772:                  recaptcha => 'successor (ReCAPTCHA)',
21773:                  notused   => 'unused',
21774:                  ver => 'ReCAPTCHA version (1 or 2)',
21775:     );
21776: }
21777: 
21778: sub devalidate_remote_domconfs {
21779:     my ($dom,$cachekeys) = @_;
21780:     return unless (ref($cachekeys) eq 'HASH');
21781:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21782:     my %thismachine;
21783:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
21784:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
21785:                       'directorysrch','passwdconf','cats','proxyalias');
21786:     if (keys(%servers)) {
21787:         foreach my $server (keys(%servers)) {
21788:             next if ($thismachine{$server});
21789:             my @cached;
21790:             foreach my $name (@posscached) {
21791:                 if ($cachekeys->{$name}) {
21792:                     if ($name eq 'proxyalias') {
21793:                         if (ref($cachekeys->{$name}) eq 'HASH') {  
21794:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
21795:                                 push(@cached,&escape($name).':'.&escape($key));
21796:                             }
21797:                         }
21798:                     } else {
21799:                         push(@cached,&escape($name).':'.&escape($dom));
21800:                     }
21801:                 }
21802:             }
21803:             if (@cached) {
21804:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
21805:             }
21806:         }
21807:     }
21808:     return;
21809: }
21810: 
21811: 1;

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