File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.407: download - view: text, annotated - select for diffs
Wed Feb 16 04:33:43 2022 UTC (2 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907.
  - Devalidate domain defaults when changes made to ltisec config in domain.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.407 2022/02/16 04:33:43 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','ltisec','privacy','passwords',
  224:                 'proctoring','wafproxy','ipaccess'],$dom);
  225:     my %encconfig =
  226:         &Apache::lonnet::get_dom('encconfig',['ltitools','lti','proctoring','linkprot'],$dom,undef,1);
  227:     if (ref($domconfig{'ltitools'}) eq 'HASH') {
  228:         if (ref($encconfig{'ltitools'}) eq 'HASH') {
  229:             foreach my $id (keys(%{$domconfig{'ltitools'}})) {
  230:                 if ((ref($domconfig{'ltitools'}{$id}) eq 'HASH') &&
  231:                     (ref($encconfig{'ltitools'}{$id}) eq 'HASH')) {
  232:                     foreach my $item ('key','secret') {
  233:                         $domconfig{'ltitools'}{$id}{$item} = $encconfig{'ltitools'}{$id}{$item};
  234:                     }
  235:                 }
  236:             }
  237:         }
  238:     }
  239:     if (ref($domconfig{'lti'}) eq 'HASH') {
  240:         if (ref($encconfig{'lti'}) eq 'HASH') {
  241:             foreach my $id (keys(%{$domconfig{'lti'}})) {
  242:                 if ((ref($domconfig{'lti'}{$id}) eq 'HASH') &&
  243:                     (ref($encconfig{'lti'}{$id}) eq 'HASH')) {
  244:                     foreach my $item ('key','secret') {
  245:                         $domconfig{'lti'}{$id}{$item} = $encconfig{'lti'}{$id}{$item};
  246:                     }
  247:                 }
  248:             }
  249:         }
  250:     }
  251:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
  252:         if (ref($domconfig{'ltisec'}{'linkprot'}) eq 'HASH') {
  253:             if (ref($encconfig{'linkprot'}) eq 'HASH') {
  254:                 foreach my $id (keys(%{$domconfig{'ltisec'}{'linkprot'}})) {
  255:                     unless ($id =~ /^\d+$/) {
  256:                         delete($domconfig{'ltisec'}{'linkprot'}{$id});
  257:                     }
  258:                     if ((ref($domconfig{'ltisec'}{'linkprot'}{$id}) eq 'HASH') &&
  259:                         (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
  260:                         foreach my $item ('key','secret') {
  261:                             $domconfig{'ltisec'}{'linkprot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
  262:                         }
  263:                     }
  264:                 }
  265:             }
  266:         }
  267:     }
  268:     if (ref($domconfig{'proctoring'}) eq 'HASH') {
  269:         if (ref($encconfig{'proctoring'}) eq 'HASH') {
  270:             foreach my $provider (keys(%{$domconfig{'proctoring'}})) {
  271:                 if ((ref($domconfig{'proctoring'}{$provider}) eq 'HASH') &&
  272:                     (ref($encconfig{'proctoring'}{$provider}) eq 'HASH')) {
  273:                     foreach my $item ('key','secret') {
  274:                         $domconfig{'proctoring'}{$provider}{$item} = $encconfig{'proctoring'}{$provider}{$item};
  275:                     }
  276:                 }
  277:             }
  278:         }
  279:     }
  280:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  281:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  282:                        'contacts','privacy','usercreation','selfcreation',
  283:                        'usermodification','scantron','requestcourses','requestauthor',
  284:                        'coursecategories','serverstatuses','helpsettings','coursedefaults',
  285:                        'ltitools','proctoring','selfenrollment','usersessions','ssl',
  286:                        'trust','lti');
  287:     my %existing;
  288:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  289:         %existing = %{$domconfig{'loadbalancing'}};
  290:     }
  291:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  292:         push(@prefs_order,'loadbalancing');
  293:     }
  294:     my %prefs = (
  295:         'rolecolors' =>
  296:                    { text => 'Default color schemes',
  297:                      help => 'Domain_Configuration_Color_Schemes',
  298:                      header => [{col1 => 'Student Settings',
  299:                                  col2 => '',},
  300:                                 {col1 => 'Coordinator Settings',
  301:                                  col2 => '',},
  302:                                 {col1 => 'Author Settings',
  303:                                  col2 => '',},
  304:                                 {col1 => 'Administrator Settings',
  305:                                  col2 => '',}],
  306:                       print => \&print_rolecolors,
  307:                       modify => \&modify_rolecolors,
  308:                     },
  309:         'login' =>
  310:                     { text => 'Log-in page options',
  311:                       help => 'Domain_Configuration_Login_Page',
  312:                       header => [{col1 => 'Log-in Page Items',
  313:                                   col2 => '',},
  314:                                  {col1 => 'Log-in Help',
  315:                                   col2 => 'Value'},
  316:                                  {col1 => 'Custom HTML in document head',
  317:                                   col2 => 'Value'},
  318:                                  {col1 => 'SSO',
  319:                                   col2 => 'Dual login: SSO and non-SSO options'},
  320:                                 ],
  321:                       print => \&print_login,
  322:                       modify => \&modify_login,
  323:                     },
  324:         'defaults' => 
  325:                     { text => 'Default authentication/language/timezone/portal/types',
  326:                       help => 'Domain_Configuration_LangTZAuth',
  327:                       header => [{col1 => 'Setting',
  328:                                   col2 => 'Value'},
  329:                                  {col1 => 'Institutional user types',
  330:                                   col2 => 'Name displayed'}],
  331:                       print => \&print_defaults,
  332:                       modify => \&modify_defaults,
  333:                     },
  334:         'wafproxy' =>
  335:                     { text => 'Web Application Firewall/Reverse Proxy',
  336:                       help => 'Domain_Configuration_WAF_Proxy',
  337:                       header => [{col1 => 'Domain(s)',
  338:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  339:                                  },
  340:                                  {col1 => 'Domain(s)',
  341:                                   col2 => 'WAF Configuration',}],
  342:                       print => \&print_wafproxy,
  343:                       modify => \&modify_wafproxy,
  344:                     },
  345:         'passwords' =>
  346:                     { text => 'Passwords (Internal authentication)',
  347:                       help => 'Domain_Configuration_Passwords',
  348:                       header => [{col1 => 'Resetting Forgotten Password',
  349:                                   col2 => 'Settings'},
  350:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  351:                                   col2 => 'Settings'},
  352:                                  {col1 => 'Rules for LON-CAPA Passwords',
  353:                                   col2 => 'Settings'},
  354:                                  {col1 => 'Course Owner Changing Student Passwords',
  355:                                   col2 => 'Settings'}],
  356:                       print => \&print_passwords,
  357:                       modify => \&modify_passwords,
  358:                     },
  359:         'quotas' => 
  360:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  361:                       help => 'Domain_Configuration_Quotas',
  362:                       header => [{col1 => 'User affiliation',
  363:                                   col2 => 'Available tools',
  364:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  365:                       print => \&print_quotas,
  366:                       modify => \&modify_quotas,
  367:                     },
  368:         'autoenroll' =>
  369:                    { text => 'Auto-enrollment settings',
  370:                      help => 'Domain_Configuration_Auto_Enrollment',
  371:                      header => [{col1 => 'Configuration setting',
  372:                                  col2 => 'Value(s)'}],
  373:                      print => \&print_autoenroll,
  374:                      modify => \&modify_autoenroll,
  375:                    },
  376:         'autoupdate' => 
  377:                    { text => 'Auto-update settings',
  378:                      help => 'Domain_Configuration_Auto_Updates',
  379:                      header => [{col1 => 'Setting',
  380:                                  col2 => 'Value',},
  381:                                 {col1 => 'Setting',
  382:                                  col2 => 'Affiliation'},
  383:                                 {col1 => 'User population',
  384:                                  col2 => 'Updatable user data'}],
  385:                      print => \&print_autoupdate,
  386:                      modify => \&modify_autoupdate,
  387:                   },
  388:         'autocreate' => 
  389:                   { text => 'Auto-course creation settings',
  390:                      help => 'Domain_Configuration_Auto_Creation',
  391:                      header => [{col1 => 'Configuration Setting',
  392:                                  col2 => 'Value',}],
  393:                      print => \&print_autocreate,
  394:                      modify => \&modify_autocreate,
  395:                   },
  396:         'directorysrch' => 
  397:                   { text => 'Directory searches',
  398:                     help => 'Domain_Configuration_InstDirectory_Search',
  399:                     header => [{col1 => 'Institutional Directory Setting',
  400:                                 col2 => 'Value',},
  401:                                {col1 => 'LON-CAPA Directory Setting',
  402:                                 col2 => 'Value',}],
  403:                     print => \&print_directorysrch,
  404:                     modify => \&modify_directorysrch,
  405:                   },
  406:         'contacts' =>
  407:                   { text => 'E-mail addresses and helpform',
  408:                     help => 'Domain_Configuration_Contact_Info',
  409:                     header => [{col1 => 'Default e-mail addresses',
  410:                                 col2 => 'Value',},
  411:                                {col1 => 'Recipient(s) for notifications',
  412:                                 col2 => 'Value',},
  413:                                {col1 => 'Nightly status check e-mail',
  414:                                 col2 => 'Settings',},
  415:                                {col1 => 'Ask helpdesk form settings',
  416:                                 col2 => 'Value',},],
  417:                     print => \&print_contacts,
  418:                     modify => \&modify_contacts,
  419:                   },
  420:         'usercreation' => 
  421:                   { text => 'User creation',
  422:                     help => 'Domain_Configuration_User_Creation',
  423:                     header => [{col1 => 'Format rule type',
  424:                                 col2 => 'Format rules in force'},
  425:                                {col1 => 'User account creation',
  426:                                 col2 => 'Usernames which may be created',},
  427:                                {col1 => 'Context',
  428:                                 col2 => 'Assignable authentication types'}],
  429:                     print => \&print_usercreation,
  430:                     modify => \&modify_usercreation,
  431:                   },
  432:         'selfcreation' => 
  433:                   { text => 'Users self-creating accounts',
  434:                     help => 'Domain_Configuration_Self_Creation', 
  435:                     header => [{col1 => 'Self-creation with institutional username',
  436:                                 col2 => 'Enabled?'},
  437:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  438:                                 col2 => 'Information user can enter'},
  439:                                {col1 => 'Self-creation with e-mail verification',
  440:                                 col2 => 'Settings'}],
  441:                     print => \&print_selfcreation,
  442:                     modify => \&modify_selfcreation,
  443:                   },
  444:         'usermodification' =>
  445:                   { text => 'User modification',
  446:                     help => 'Domain_Configuration_User_Modification',
  447:                     header => [{col1 => 'Target user has role',
  448:                                 col2 => 'User information updatable in author context'},
  449:                                {col1 => 'Target user has role',
  450:                                 col2 => 'User information updatable in course context'}],
  451:                     print => \&print_usermodification,
  452:                     modify => \&modify_usermodification,
  453:                   },
  454:         'scantron' =>
  455:                   { text => 'Bubblesheet format',
  456:                     help => 'Domain_Configuration_Scantron_Format',
  457:                     header => [ {col1 => 'Bubblesheet format file',
  458:                                  col2 => ''},
  459:                                 {col1 => 'Bubblesheet data upload formats',
  460:                                  col2 => 'Settings'}],
  461:                     print => \&print_scantron,
  462:                     modify => \&modify_scantron,
  463:                   },
  464:         'requestcourses' => 
  465:                  {text => 'Request creation of courses',
  466:                   help => 'Domain_Configuration_Request_Courses',
  467:                   header => [{col1 => 'User affiliation',
  468:                               col2 => 'Availability/Processing of requests',},
  469:                              {col1 => 'Setting',
  470:                               col2 => 'Value'},
  471:                              {col1 => 'Available textbooks',
  472:                               col2 => ''},
  473:                              {col1 => 'Available templates',
  474:                               col2 => ''},
  475:                              {col1 => 'Validation (not official courses)',
  476:                               col2 => 'Value'},],
  477:                   print => \&print_quotas,
  478:                   modify => \&modify_quotas,
  479:                  },
  480:         'requestauthor' =>
  481:                  {text => 'Request Authoring Space',
  482:                   help => 'Domain_Configuration_Request_Author',
  483:                   header => [{col1 => 'User affiliation',
  484:                               col2 => 'Availability/Processing of requests',},
  485:                              {col1 => 'Setting',
  486:                               col2 => 'Value'}],
  487:                   print => \&print_quotas,
  488:                   modify => \&modify_quotas,
  489:                  },
  490:         'coursecategories' =>
  491:                   { text => 'Cataloging of courses/communities',
  492:                     help => 'Domain_Configuration_Cataloging_Courses',
  493:                     header => [{col1 => 'Catalog type/availability',
  494:                                 col2 => '',},
  495:                                {col1 => 'Category settings for standard catalog',
  496:                                 col2 => '',},
  497:                                {col1 => 'Categories',
  498:                                 col2 => '',
  499:                                }],
  500:                     print => \&print_coursecategories,
  501:                     modify => \&modify_coursecategories,
  502:                   },
  503:         'serverstatuses' =>
  504:                  {text   => 'Access to server status pages',
  505:                   help   => 'Domain_Configuration_Server_Status',
  506:                   header => [{col1 => 'Status Page',
  507:                               col2 => 'Other named users',
  508:                               col3 => 'Specific IPs',
  509:                             }],
  510:                   print => \&print_serverstatuses,
  511:                   modify => \&modify_serverstatuses,
  512:                  },
  513:         'helpsettings' =>
  514:                  {text   => 'Support settings',
  515:                   help   => 'Domain_Configuration_Help_Settings',
  516:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  517:                               col2 => 'Value'},
  518:                              {col1 => 'Helpdesk Roles',
  519:                               col2 => 'Settings'},],
  520:                   print  => \&print_helpsettings,
  521:                   modify => \&modify_helpsettings,
  522:                  },
  523:         'coursedefaults' => 
  524:                  {text => 'Course/Community defaults',
  525:                   help => 'Domain_Configuration_Course_Defaults',
  526:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  527:                               col2 => 'Value',},
  528:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  529:                               col2 => 'Value',},],
  530:                   print => \&print_coursedefaults,
  531:                   modify => \&modify_coursedefaults,
  532:                  },
  533:         'selfenrollment' => 
  534:                  {text   => 'Self-enrollment in Course/Community',
  535:                   help   => 'Domain_Configuration_Selfenrollment',
  536:                   header => [{col1 => 'Configuration Rights',
  537:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  538:                              {col1 => 'Defaults',
  539:                               col2 => 'Value'},
  540:                              {col1 => 'Self-enrollment validation (optional)',
  541:                               col2 => 'Value'},],
  542:                   print => \&print_selfenrollment,
  543:                   modify => \&modify_selfenrollment,
  544:                  },
  545:         'privacy' => 
  546:                  {text   => 'Availability of User Information',
  547:                   help   => 'Domain_Configuration_User_Privacy',
  548:                   header => [{col1 => 'Role assigned in different domain',
  549:                               col2 => 'Approval options'},
  550:                              {col1 => 'Role assigned in different domain to user of type',
  551:                               col2 => 'User information available in that domain'},
  552:                              {col1 => "Role assigned in user's domain",
  553:                               col2 => 'Information viewable by privileged user'},
  554:                              {col1 => "Role assigned in user's domain",
  555:                               col2 => 'Information viewable by unprivileged user'}],
  556:                   print => \&print_privacy,
  557:                   modify => \&modify_privacy,
  558:                  },
  559:         'usersessions' =>
  560:                  {text  => 'User session hosting/offloading',
  561:                   help  => 'Domain_Configuration_User_Sessions',
  562:                   header => [{col1 => 'Domain server',
  563:                               col2 => 'Servers to offload sessions to when busy'},
  564:                              {col1 => 'Hosting of users from other domains',
  565:                               col2 => 'Rules'},
  566:                              {col1 => "Hosting domain's own users elsewhere",
  567:                               col2 => 'Rules'}],
  568:                   print => \&print_usersessions,
  569:                   modify => \&modify_usersessions,
  570:                  },
  571:         'loadbalancing' =>
  572:                  {text  => 'Dedicated Load Balancer(s)',
  573:                   help  => 'Domain_Configuration_Load_Balancing',
  574:                   header => [{col1 => 'Balancers',
  575:                               col2 => 'Default destinations',
  576:                               col3 => 'User affiliation',
  577:                               col4 => 'Overrides'},
  578:                             ],
  579:                   print => \&print_loadbalancing,
  580:                   modify => \&modify_loadbalancing,
  581:                  },
  582:         'ltitools' => 
  583:                  {text => 'External Tools (LTI)',
  584:                   help => 'Domain_Configuration_LTI_Tools',
  585:                   header => [{col1 => 'Setting',
  586:                               col2 => 'Value',}],
  587:                   print => \&print_ltitools,
  588:                   modify => \&modify_ltitools,
  589:                  },
  590:         'proctoring' =>
  591:                  {text => 'Remote Proctoring Integration',
  592:                   help => 'Domain_Configuration_Proctoring',
  593:                   header => [{col1 => 'Name',
  594:                               col2 => 'Configuration'}],
  595:                   print => \&print_proctoring,
  596:                   modify => \&modify_proctoring,
  597:                  },
  598:         'ssl' =>
  599:                  {text  => 'LON-CAPA Network (SSL)',
  600:                   help  => 'Domain_Configuration_Network_SSL',
  601:                   header => [{col1 => 'Server',
  602:                               col2 => 'Certificate Status'},
  603:                              {col1 => 'Connections to other servers',
  604:                               col2 => 'Rules'},
  605:                              {col1 => 'Connections from other servers',
  606:                               col2 => 'Rules'},
  607:                              {col1 => "Replicating domain's published content",
  608:                               col2 => 'Rules'}],
  609:                   print => \&print_ssl,
  610:                   modify => \&modify_ssl,
  611:                  },
  612:         'trust' =>
  613:                  {text   => 'Trust Settings',
  614:                   help   => 'Domain_Configuration_Trust',
  615:                   header => [{col1 => "Access to this domain's content by others",
  616:                               col2 => 'Rules'},
  617:                              {col1 => "Access to other domain's content by this domain",
  618:                               col2 => 'Rules'},
  619:                              {col1 => "Enrollment in this domain's courses by others",
  620:                               col2 => 'Rules',},
  621:                              {col1 => "Co-author roles in this domain for others",
  622:                               col2 => 'Rules',},
  623:                              {col1 => "Co-author roles for this domain's users elsewhere",
  624:                               col2 => 'Rules',},
  625:                              {col1 => "Domain roles in this domain assignable to others",
  626:                               col2 => 'Rules'},
  627:                              {col1 => "Course catalog for this domain displayed elsewhere",
  628:                               col2 => 'Rules'},
  629:                              {col1 => "Requests for creation of courses in this domain by others",
  630:                               col2 => 'Rules'},
  631:                              {col1 => "Users in other domains can send messages to this domain",
  632:                               col2 => 'Rules'},],
  633:                   print => \&print_trust,
  634:                   modify => \&modify_trust,
  635:                  },
  636:           'lti' =>
  637:                  {text => 'LTI Link Protection and LTI Consumers',
  638:                   help => 'Domain_Configuration_LTI_Provider',
  639:                   header => [{col1 => 'Encryption of shared secrets',
  640:                               col2 => 'Settings'},
  641:                              {col1 => 'Rules for shared secrets', 
  642:                               col2 => 'Settings'},
  643:                              {col1 => 'Link Protectors',
  644:                               col2 => 'Settings'},
  645:                              {col1 => 'Consumers',
  646:                               col2 => 'Settings'},],
  647:                   print => \&print_lti,
  648:                   modify => \&modify_lti,
  649:                  },
  650:            'ipaccess' =>
  651:                        {text => 'IP-based access control',
  652:                         help => 'Domain_Configuration_IP_Access',
  653:                         header => [{col1 => 'Setting',
  654:                                     col2 => 'Value'},],
  655:                         print  => \&print_ipaccess,
  656:                         modify => \&modify_ipaccess,
  657:                        },
  658:     );
  659:     if (keys(%servers) > 1) {
  660:         $prefs{'login'}  = { text   => 'Log-in page options',
  661:                              help   => 'Domain_Configuration_Login_Page',
  662:                             header => [{col1 => 'Log-in Service',
  663:                                         col2 => 'Server Setting',},
  664:                                        {col1 => 'Log-in Page Items',
  665:                                         col2 => 'Settings'},
  666:                                        {col1 => 'Log-in Help',
  667:                                         col2 => 'Value'},
  668:                                        {col1 => 'Custom HTML in document head',
  669:                                         col2 => 'Value'},
  670:                                        {col1 => 'SSO',
  671:                                         col2 => 'Dual login: SSO and non-SSO options'},
  672:                                       ],
  673:                             print => \&print_login,
  674:                             modify => \&modify_login,
  675:                            };
  676:     }
  677: 
  678:     my @roles = ('student','coordinator','author','admin');
  679:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  680:     &Apache::lonhtmlcommon::add_breadcrumb
  681:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  682:       text=>"Settings to display/modify"});
  683:     my $confname = $dom.'-domainconfig';
  684: 
  685:     if ($phase eq 'process') {
  686:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  687:                                                               \%prefs,\%domconfig,$confname,\@roles);
  688:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  689:             $r->rflush();
  690:             &devalidate_remote_domconfs($dom,$result);
  691:         }
  692:     } elsif ($phase eq 'display') {
  693:         my $js = &recaptcha_js().
  694:                  &toggle_display_js();
  695:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  696:             my ($othertitle,$usertypes,$types) =
  697:                 &Apache::loncommon::sorted_inst_types($dom);
  698:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  699:                                           $domconfig{'loadbalancing'}).
  700:                    &new_spares_js().
  701:                    &common_domprefs_js().
  702:                    &Apache::loncommon::javascript_array_indexof();
  703:         }
  704:         if (grep(/^requestcourses$/,@actions)) {
  705:             my $javascript_validations;
  706:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  707:             $js .= <<END;
  708: <script type="text/javascript">
  709: $javascript_validations
  710: </script>
  711: $coursebrowserjs
  712: END
  713:         } elsif (grep(/^ipaccess$/,@actions)) {
  714:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  715:         }
  716:         if (grep(/^selfcreation$/,@actions)) {
  717:             $js .= &selfcreate_javascript();
  718:         }
  719:         if (grep(/^contacts$/,@actions)) {
  720:             $js .= &contacts_javascript();
  721:         }
  722:         if (grep(/^scantron$/,@actions)) {
  723:             $js .= &scantron_javascript();
  724:         }
  725:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  726:     } else {
  727: # check if domconfig user exists for the domain.
  728:         my $servadm = $r->dir_config('lonAdmEMail');
  729:         my ($configuserok,$author_ok,$switchserver) =
  730:             &config_check($dom,$confname,$servadm);
  731:         unless ($configuserok eq 'ok') {
  732:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  733:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  734:                           $confname).
  735:                       '<br />'
  736:             );
  737:             if ($switchserver) {
  738:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  739:                           '<br />'.
  740:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  741:                           '<br />'.
  742:                           &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).
  743:                           '<br />'.
  744:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  745:                 );
  746:             } else {
  747:                 $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.').
  748:                           '<br />'.
  749:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  750:                 );
  751:             }
  752:             $r->print(&Apache::loncommon::end_page());
  753:             return OK;
  754:         }
  755:         if (keys(%domconfig) == 0) {
  756:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  757:             my @ids=&Apache::lonnet::current_machine_ids();
  758:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  759:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  760:                 my @loginimages = ('img','logo','domlogo','login');
  761:                 my $custom_img_count = 0;
  762:                 foreach my $img (@loginimages) {
  763:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  764:                         $custom_img_count ++;
  765:                     }
  766:                 }
  767:                 foreach my $role (@roles) {
  768:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  769:                         $custom_img_count ++;
  770:                     }
  771:                 }
  772:                 if ($custom_img_count > 0) {
  773:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  774:                     my $switch_server = &check_switchserver($dom,$confname);
  775:                     $r->print(
  776:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  777:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  778:     &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 />'.
  779:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  780:                     if ($switch_server) {
  781:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  782:                     }
  783:                     $r->print(&Apache::loncommon::end_page());
  784:                     return OK;
  785:                 }
  786:             }
  787:         }
  788:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  789:     }
  790:     return OK;
  791: }
  792: 
  793: sub process_changes {
  794:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  795:     my %domconfig;
  796:     if (ref($values) eq 'HASH') {
  797:         %domconfig = %{$values};
  798:     }
  799:     my $output;
  800:     if ($action eq 'login') {
  801:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  802:     } elsif ($action eq 'rolecolors') {
  803:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  804:                                      $lastactref,%domconfig);
  805:     } elsif ($action eq 'quotas') {
  806:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  807:     } elsif ($action eq 'autoenroll') {
  808:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  809:     } elsif ($action eq 'autoupdate') {
  810:         $output = &modify_autoupdate($dom,%domconfig);
  811:     } elsif ($action eq 'autocreate') {
  812:         $output = &modify_autocreate($dom,%domconfig);
  813:     } elsif ($action eq 'directorysrch') {
  814:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  815:     } elsif ($action eq 'usercreation') {
  816:         $output = &modify_usercreation($dom,%domconfig);
  817:     } elsif ($action eq 'selfcreation') {
  818:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  819:     } elsif ($action eq 'usermodification') {
  820:         $output = &modify_usermodification($dom,%domconfig);
  821:     } elsif ($action eq 'contacts') {
  822:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  823:     } elsif ($action eq 'defaults') {
  824:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  825:     } elsif ($action eq 'scantron') {
  826:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  827:     } elsif ($action eq 'coursecategories') {
  828:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  829:     } elsif ($action eq 'serverstatuses') {
  830:         $output = &modify_serverstatuses($dom,%domconfig);
  831:     } elsif ($action eq 'requestcourses') {
  832:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  833:     } elsif ($action eq 'requestauthor') {
  834:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  835:     } elsif ($action eq 'helpsettings') {
  836:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  837:     } elsif ($action eq 'coursedefaults') {
  838:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  839:     } elsif ($action eq 'selfenrollment') {
  840:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  841:     } elsif ($action eq 'usersessions') {
  842:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  843:     } elsif ($action eq 'loadbalancing') {
  844:         $output = &modify_loadbalancing($dom,%domconfig);
  845:     } elsif ($action eq 'ltitools') {
  846:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  847:     } elsif ($action eq 'proctoring') {
  848:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  849:     } elsif ($action eq 'ssl') {
  850:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  851:     } elsif ($action eq 'trust') {
  852:         $output = &modify_trust($dom,$lastactref,%domconfig);
  853:     } elsif ($action eq 'lti') {
  854:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  855:     } elsif ($action eq 'privacy') {
  856:         $output = &modify_privacy($dom,%domconfig);
  857:     } elsif ($action eq 'passwords') {
  858:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  859:     } elsif ($action eq 'wafproxy') {
  860:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  861:     } elsif ($action eq 'ipaccess') {
  862:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  863:     }
  864:     return $output;
  865: }
  866: 
  867: sub print_config_box {
  868:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  869:     my $rowtotal = 0;
  870:     my $output;
  871:     if ($action eq 'coursecategories') {
  872:         $output = &coursecategories_javascript($settings);
  873:     } elsif ($action eq 'defaults') {
  874:         $output = &defaults_javascript($settings); 
  875:     } elsif ($action eq 'passwords') {
  876:         $output = &passwords_javascript($action);
  877:     } elsif ($action eq 'helpsettings') {
  878:         my (%privs,%levelscurrent);
  879:         my %full=();
  880:         my %levels=(
  881:                      course => {},
  882:                      domain => {},
  883:                      system => {},
  884:                    );
  885:         my $context = 'domain';
  886:         my $crstype = 'Course';
  887:         my $formname = 'display';
  888:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  889:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  890:         $output =
  891:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  892:                                                       \@templateroles);
  893:     } elsif ($action eq 'ltitools') {
  894:         $output .= &ltitools_javascript($settings);
  895:     } elsif ($action eq 'lti') {
  896:         $output .= &passwords_javascript('secrets')."\n".
  897:                    &lti_javascript($dom,$settings);
  898:     } elsif ($action eq 'proctoring') {
  899:         $output .= &proctoring_javascript($settings);
  900:     } elsif ($action eq 'wafproxy') {
  901:         $output .= &wafproxy_javascript($dom);
  902:     } elsif ($action eq 'autoupdate') {
  903:         $output .= &autoupdate_javascript();
  904:     } elsif ($action eq 'autoenroll') {
  905:         $output .= &autoenroll_javascript();
  906:     } elsif ($action eq 'login') {
  907:         $output .= &saml_javascript();
  908:     } elsif ($action eq 'ipaccess') {
  909:         $output .= &ipaccess_javascript($settings);
  910:     }
  911:     $output .=
  912:          '<table class="LC_nested_outer">
  913:           <tr>
  914:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  915:            &mt($item->{text}).'&nbsp;'.
  916:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  917:           '</tr>';
  918:     $rowtotal ++;
  919:     my $numheaders = 1;
  920:     if (ref($item->{'header'}) eq 'ARRAY') {
  921:         $numheaders = scalar(@{$item->{'header'}});
  922:     }
  923:     if ($numheaders > 1) {
  924:         my $colspan = '';
  925:         my $rightcolspan = '';
  926:         my $leftnobr = '';
  927:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  928:             ($action eq 'directorysrch') ||
  929:             (($action eq 'login') && ($numheaders < 5))) {
  930:             $colspan = ' colspan="2"';
  931:         }
  932:         if ($action eq 'usersessions') {
  933:             $rightcolspan = ' colspan="3"'; 
  934:         }
  935:         if ($action eq 'passwords') {
  936:             $leftnobr = ' LC_nobreak';
  937:         }
  938:         $output .= '
  939:           <tr>
  940:            <td>
  941:             <table class="LC_nested">
  942:              <tr class="LC_info_row">
  943:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  944:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  945:              </tr>';
  946:         $rowtotal ++;
  947:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  948:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  949:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  950:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  951:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') || ($action eq 'lti')) {
  952:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  953:         } elsif ($action eq 'passwords') {
  954:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  955:         } elsif ($action eq 'coursecategories') {
  956:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  957:         } elsif ($action eq 'scantron') {
  958:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  959:         } elsif ($action eq 'login') {
  960:             if ($numheaders == 5) {
  961:                 $colspan = ' colspan="2"';
  962:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  963:             } else {
  964:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  965:             }
  966:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  967:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  968:         } elsif ($action eq 'rolecolors') {
  969:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  970:         }
  971:         $output .= '
  972:            </table>
  973:           </td>
  974:          </tr>
  975:          <tr>
  976:            <td>
  977:             <table class="LC_nested">
  978:              <tr class="LC_info_row">
  979:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  980:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  981:              </tr>';
  982:             $rowtotal ++;
  983:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  984:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  985:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  986:             ($action eq 'trust') || ($action eq 'contacts') ||
  987:             ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti')) {
  988:             if ($action eq 'coursecategories') {
  989:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  990:                 $colspan = ' colspan="2"';
  991:             } elsif ($action eq 'trust') {
  992:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  993:             } elsif ($action eq 'passwords') {
  994:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  995:             } else {
  996:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  997:             }
  998:             if ($action eq 'trust') {
  999:                 $output .= '
 1000:             </table>
 1001:           </td>
 1002:          </tr>';
 1003:                 my @trusthdrs = qw(2 3 4 5 6 7);
 1004:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
 1005:                 for (my $i=0; $i<@trusthdrs; $i++) {
 1006:                     $output .= '
 1007:          <tr>
 1008:            <td>
 1009:             <table class="LC_nested">
 1010:              <tr class="LC_info_row">
 1011:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
 1012:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
 1013:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
 1014:             </table>
 1015:           </td>
 1016:          </tr>';
 1017:                 }
 1018:                 $output .= '
 1019:          <tr>
 1020:            <td>
 1021:             <table class="LC_nested">
 1022:              <tr class="LC_info_row">
 1023:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
 1024:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
 1025:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1026:             } else {
 1027:                 $output .= '
 1028:            </table>
 1029:           </td>
 1030:          </tr>
 1031:          <tr>
 1032:            <td>
 1033:             <table class="LC_nested">
 1034:              <tr class="LC_info_row">
 1035:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1036:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1037:              </tr>'."\n";
 1038:                 if ($action eq 'coursecategories') {
 1039:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
 1040:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || 
 1041:                          ($action eq 'passwords') || ($action eq 'lti')) {
 1042:                     if ($action eq 'passwords') {
 1043:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
 1044:                     } else {
 1045:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
 1046:                     }
 1047:                     $output .= '
 1048:              </tr>
 1049:             </table>
 1050:            </td>
 1051:           </tr>
 1052:           <tr>
 1053:            <td>
 1054:             <table class="LC_nested">
 1055:              <tr class="LC_info_row">
 1056:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1057:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1058:                     if ($action eq 'passwords') {
 1059:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1060:                     } else {
 1061:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1062:                     }
 1063:                     $output .= '
 1064:             </table>
 1065:           </td>
 1066:          </tr>
 1067:          <tr>';
 1068:                 } else {
 1069:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1070:                 }
 1071:             }
 1072:             $rowtotal ++;
 1073:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1074:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
 1075:                  ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
 1076:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1077:         } elsif ($action eq 'scantron') {
 1078:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1079:         } elsif ($action eq 'ssl') {
 1080:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1081:             </table>
 1082:           </td>
 1083:          </tr>
 1084:          <tr>
 1085:            <td>
 1086:             <table class="LC_nested">
 1087:              <tr class="LC_info_row">
 1088:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1089:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1090:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
 1091:             </table>
 1092:           </td>
 1093:          </tr>
 1094:          <tr>
 1095:            <td>
 1096:             <table class="LC_nested">
 1097:              <tr class="LC_info_row">
 1098:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1099:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1100:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1101:         } elsif ($action eq 'login') {
 1102:             if ($numheaders == 5) {
 1103:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1104:            </table>
 1105:           </td>
 1106:          </tr>
 1107:          <tr>
 1108:            <td>
 1109:             <table class="LC_nested">
 1110:              <tr class="LC_info_row">
 1111:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1112:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1113:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1114:                 $rowtotal ++;
 1115:             } else {
 1116:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1117:             }
 1118:             $output .= '
 1119:            </table>
 1120:           </td>
 1121:          </tr>
 1122:          <tr>
 1123:            <td>
 1124:             <table class="LC_nested">
 1125:              <tr class="LC_info_row">';
 1126:             if ($numheaders == 5) {
 1127:                 $output .= '
 1128:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1129:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1130:              </tr>';
 1131:             } else {
 1132:                 $output .= '
 1133:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1134:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1135:              </tr>';
 1136:             }
 1137:             $rowtotal ++;
 1138:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1139:            </table>
 1140:           </td>
 1141:          </tr>
 1142:          <tr>
 1143:            <td>
 1144:             <table class="LC_nested">
 1145:              <tr class="LC_info_row">';
 1146:             if ($numheaders == 5) {
 1147:                 $output .= '
 1148:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1149:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1150:              </tr>';
 1151:             } else {
 1152:                 $output .= '
 1153:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1154:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1155:              </tr>';
 1156:             }
 1157:             $rowtotal ++;
 1158:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1159:         } elsif ($action eq 'requestcourses') {
 1160:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1161:             $rowtotal ++;
 1162:             $output .= &print_studentcode($settings,\$rowtotal).'
 1163:            </table>
 1164:           </td>
 1165:          </tr>
 1166:          <tr>
 1167:            <td>
 1168:             <table class="LC_nested">
 1169:              <tr class="LC_info_row">
 1170:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1171:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1172:                        &textbookcourses_javascript($settings).
 1173:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1174:             </table>
 1175:            </td>
 1176:           </tr>
 1177:          <tr>
 1178:            <td>
 1179:             <table class="LC_nested">
 1180:              <tr class="LC_info_row">
 1181:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1182:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1183:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1184:             </table>
 1185:            </td>
 1186:           </tr>
 1187:           <tr>
 1188:            <td>
 1189:             <table class="LC_nested">
 1190:              <tr class="LC_info_row">
 1191:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1192:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1193:              </tr>'.
 1194:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1195:         } elsif ($action eq 'requestauthor') {
 1196:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1197:             $rowtotal ++;
 1198:         } elsif ($action eq 'rolecolors') {
 1199:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1200:            </table>
 1201:           </td>
 1202:          </tr>
 1203:          <tr>
 1204:            <td>
 1205:             <table class="LC_nested">
 1206:              <tr class="LC_info_row">
 1207:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1208:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1209:               <td class="LC_right_item" style="vertical-align: top">'.
 1210:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1211:              </tr>'.
 1212:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1213:            </table>
 1214:           </td>
 1215:          </tr>
 1216:          <tr>
 1217:            <td>
 1218:             <table class="LC_nested">
 1219:              <tr class="LC_info_row">
 1220:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1221:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1222:              </tr>'.
 1223:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1224:             $rowtotal += 2;
 1225:         }
 1226:     } else {
 1227:         $output .= '
 1228:           <tr>
 1229:            <td>
 1230:             <table class="LC_nested">
 1231:              <tr class="LC_info_row">';
 1232:         if ($action eq 'login') {
 1233:             $output .= '  
 1234:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1235:         } elsif ($action eq 'serverstatuses') {
 1236:             $output .= '
 1237:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1238:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1239: 
 1240:         } else {
 1241:             $output .= '
 1242:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1243:         }
 1244:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1245:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1246:                        &mt($item->{'header'}->[0]->{'col2'});
 1247:             if ($action eq 'serverstatuses') {
 1248:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1249:             } 
 1250:         } else {
 1251:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1252:                        &mt($item->{'header'}->[0]->{'col2'});
 1253:         }
 1254:         $output .= '</td>';
 1255:         if ($item->{'header'}->[0]->{'col3'}) {
 1256:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1257:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1258:                             &mt($item->{'header'}->[0]->{'col3'});
 1259:             } else {
 1260:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1261:                            &mt($item->{'header'}->[0]->{'col3'});
 1262:             }
 1263:             if ($action eq 'serverstatuses') {
 1264:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1265:             }
 1266:             $output .= '</td>';
 1267:         }
 1268:         if ($item->{'header'}->[0]->{'col4'}) {
 1269:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1270:                        &mt($item->{'header'}->[0]->{'col4'});
 1271:         }
 1272:         $output .= '</tr>';
 1273:         $rowtotal ++;
 1274:         if ($action eq 'quotas') {
 1275:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1276:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1277:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1278:                  ($action eq 'ltitools') || ($action eq 'proctoring') ||
 1279:                  ($action eq 'ipaccess')) {
 1280:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1281:         }
 1282:     }
 1283:     $output .= '
 1284:    </table>
 1285:   </td>
 1286:  </tr>
 1287: </table><br />';
 1288:     return ($output,$rowtotal);
 1289: }
 1290: 
 1291: sub print_login {
 1292:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1293:     my ($css_class,$datatable,$switchserver,%lt);
 1294:     my %choices = &login_choices();
 1295:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1296:         %lt = &login_file_options();
 1297:         $switchserver = &check_switchserver($dom,$confname);
 1298:     }
 1299:     if ($caller eq 'service') {
 1300:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1301:         my $choice = $choices{'disallowlogin'};
 1302:         $css_class = ' class="LC_odd_row"';
 1303:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1304:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1305:                       '<th>'.$choices{'server'}.'</th>'.
 1306:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1307:                       '<th>'.$choices{'custompath'}.'</th>'.
 1308:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1309:         my %disallowed;
 1310:         if (ref($settings) eq 'HASH') {
 1311:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1312:                %disallowed = %{$settings->{'loginvia'}};
 1313:             }
 1314:         }
 1315:         foreach my $lonhost (sort(keys(%servers))) {
 1316:             my $direct = 'selected="selected"';
 1317:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1318:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1319:                     $direct = '';
 1320:                 }
 1321:             }
 1322:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1323:                           '<td><select name="'.$lonhost.'_server">'.
 1324:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1325:                           '</option>';
 1326:             foreach my $hostid (sort(keys(%servers))) {
 1327:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1328:                 my $selected = '';
 1329:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1330:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1331:                         $selected = 'selected="selected"';
 1332:                     }
 1333:                 }
 1334:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1335:                               $servers{$hostid}.'</option>';
 1336:             }
 1337:             $datatable .= '</select></td>'.
 1338:                           '<td><select name="'.$lonhost.'_serverpath">';
 1339:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1340:                 my $pathname = $path;
 1341:                 if ($path eq 'custom') {
 1342:                     $pathname = &mt('Custom Path').' ->';
 1343:                 }
 1344:                 my $selected = '';
 1345:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1346:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1347:                         $selected = 'selected="selected"';
 1348:                     }
 1349:                 } elsif ($path eq '') {
 1350:                     $selected = 'selected="selected"';
 1351:                 }
 1352:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1353:             }
 1354:             $datatable .= '</select></td>';
 1355:             my ($custom,$exempt);
 1356:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1357:                 $custom = $disallowed{$lonhost}{'custompath'};
 1358:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1359:             }
 1360:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1361:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1362:                           '</tr>';
 1363:         }
 1364:         $datatable .= '</table></td></tr>';
 1365:         return $datatable;
 1366:     } elsif ($caller eq 'page') {
 1367:         my %defaultchecked = ( 
 1368:                                'coursecatalog' => 'on',
 1369:                                'helpdesk'      => 'on',
 1370:                                'adminmail'     => 'off',
 1371:                                'newuser'       => 'off',
 1372:                              );
 1373:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1374:         my (%checkedon,%checkedoff);
 1375:         foreach my $item (@toggles) {
 1376:             if ($defaultchecked{$item} eq 'on') { 
 1377:                 $checkedon{$item} = ' checked="checked" ';
 1378:                 $checkedoff{$item} = ' ';
 1379:             } elsif ($defaultchecked{$item} eq 'off') {
 1380:                 $checkedoff{$item} = ' checked="checked" ';
 1381:                 $checkedon{$item} = ' ';
 1382:             }
 1383:         }
 1384:         my @images = ('img','logo','domlogo','login');
 1385:         my @alttext = ('img','logo','domlogo');
 1386:         my @logintext = ('textcol','bgcol');
 1387:         my @bgs = ('pgbg','mainbg','sidebg');
 1388:         my @links = ('link','alink','vlink');
 1389:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1390:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1391:         my (%is_custom,%designs);
 1392:         my %defaults = (
 1393:                        font => $defaultdesign{'login.font'},
 1394:                        );
 1395:         foreach my $item (@images) {
 1396:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1397:             $defaults{'showlogo'}{$item} = 1;
 1398:         }
 1399:         foreach my $item (@bgs) {
 1400:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1401:         }
 1402:         foreach my $item (@logintext) {
 1403:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1404:         }
 1405:         foreach my $item (@links) {
 1406:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1407:         }
 1408:         if (ref($settings) eq 'HASH') {
 1409:             foreach my $item (@toggles) {
 1410:                 if ($settings->{$item} eq '1') {
 1411:                     $checkedon{$item} =  ' checked="checked" ';
 1412:                     $checkedoff{$item} = ' ';
 1413:                 } elsif ($settings->{$item} eq '0') {
 1414:                     $checkedoff{$item} =  ' checked="checked" ';
 1415:                     $checkedon{$item} = ' ';
 1416:                 }
 1417:             }
 1418:             foreach my $item (@images) {
 1419:                 if (defined($settings->{$item})) {
 1420:                     $designs{$item} = $settings->{$item};
 1421:                     $is_custom{$item} = 1;
 1422:                 }
 1423:                 if (defined($settings->{'showlogo'}{$item})) {
 1424:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1425:                 }
 1426:             }
 1427:             foreach my $item (@alttext) {
 1428:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1429:                     if ($settings->{'alttext'}->{$item} ne '') {
 1430:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1431:                     }
 1432:                 }
 1433:             }
 1434:             foreach my $item (@logintext) {
 1435:                 if ($settings->{$item} ne '') {
 1436:                     $designs{'logintext'}{$item} = $settings->{$item};
 1437:                     $is_custom{$item} = 1;
 1438:                 }
 1439:             }
 1440:             if ($settings->{'font'} ne '') {
 1441:                 $designs{'font'} = $settings->{'font'};
 1442:                 $is_custom{'font'} = 1;
 1443:             }
 1444:             foreach my $item (@bgs) {
 1445:                 if ($settings->{$item} ne '') {
 1446:                     $designs{'bgs'}{$item} = $settings->{$item};
 1447:                     $is_custom{$item} = 1;
 1448:                 }
 1449:             }
 1450:             foreach my $item (@links) {
 1451:                 if ($settings->{$item} ne '') {
 1452:                     $designs{'links'}{$item} = $settings->{$item};
 1453:                     $is_custom{$item} = 1;
 1454:                 }
 1455:             }
 1456:         } else {
 1457:             if ($designhash{$dom.'.login.font'} ne '') {
 1458:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1459:                 $is_custom{'font'} = 1;
 1460:             }
 1461:             foreach my $item (@images) {
 1462:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1463:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1464:                     $is_custom{$item} = 1;
 1465:                 }
 1466:             }
 1467:             foreach my $item (@bgs) {
 1468:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1469:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1470:                     $is_custom{$item} = 1;
 1471:                 }
 1472:             }
 1473:             foreach my $item (@links) {
 1474:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1475:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1476:                     $is_custom{$item} = 1;
 1477:                 }
 1478:             }
 1479:         }
 1480:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1481:                                                       logo => 'Institution Logo',
 1482:                                                       domlogo => 'Domain Logo',
 1483:                                                       login => 'Login box');
 1484:         my $itemcount = 1;
 1485:         foreach my $item (@toggles) {
 1486:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1487:             $datatable .=  
 1488:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1489:                 '</td><td>'.
 1490:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1491:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1492:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1493:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1494:                 '</tr>';
 1495:             $itemcount ++;
 1496:         }
 1497:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1498:         $datatable .= '</tr></table></td></tr>';
 1499:     } elsif ($caller eq 'help') {
 1500:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1501:         my $itemcount = 1;
 1502:         $defaulturl = '/adm/loginproblems.html';
 1503:         $defaulttype = 'default';
 1504:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1505:         my @currlangs;
 1506:         if (ref($settings) eq 'HASH') {
 1507:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1508:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1509:                     next if ($settings->{'helpurl'}{$key} eq '');
 1510:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1511:                     $type{$key} = 'custom';
 1512:                     unless ($key eq 'nolang') {
 1513:                         push(@currlangs,$key);
 1514:                     }
 1515:                 }
 1516:             } elsif ($settings->{'helpurl'} ne '') {
 1517:                 $type{'nolang'} = 'custom';
 1518:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1519:             }
 1520:         }
 1521:         foreach my $lang ('nolang',sort(@currlangs)) {
 1522:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1523:             $datatable .= '<tr'.$css_class.'>';
 1524:             if ($url{$lang} eq '') {
 1525:                 $url{$lang} = $defaulturl;
 1526:             }
 1527:             if ($type{$lang} eq '') {
 1528:                 $type{$lang} = $defaulttype;
 1529:             }
 1530:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1531:             if ($lang eq 'nolang') {
 1532:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1533:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1534:             } else {
 1535:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1536:                                   $langchoices{$lang},
 1537:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1538:             }
 1539:             $datatable .= '</span></td>'."\n".
 1540:                           '<td class="LC_left_item">';
 1541:             if ($type{$lang} eq 'custom') {
 1542:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1543:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1544:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1545:             } else {
 1546:                 $datatable .= $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="loginhelpurl_'.$lang.'" />';
 1553:             }
 1554:             $datatable .= '</td></tr>';
 1555:             $itemcount ++;
 1556:         }
 1557:         my @addlangs;
 1558:         foreach my $lang (sort(keys(%langchoices))) {
 1559:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1560:             push(@addlangs,$lang);
 1561:         }
 1562:         if (@addlangs > 0) {
 1563:             my %toadd;
 1564:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1565:             $toadd{''} = &mt('Select');
 1566:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1567:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1568:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1569:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1570:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1571:             if ($switchserver) {
 1572:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1573:             } else {
 1574:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1575:             }
 1576:             $datatable .= '</td></tr>';
 1577:             $itemcount ++;
 1578:         }
 1579:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1580:     } elsif ($caller eq 'headtag') {
 1581:         my %domservers = &Apache::lonnet::get_servers($dom);
 1582:         my $choice = $choices{'headtag'};
 1583:         $css_class = ' class="LC_odd_row"';
 1584:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1585:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1586:                       '<th>'.$choices{'current'}.'</th>'.
 1587:                       '<th>'.$choices{'action'}.'</th>'.
 1588:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1589:         my (%currurls,%currexempt);
 1590:         if (ref($settings) eq 'HASH') {
 1591:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1592:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1593:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1594:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1595:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1596:                     }
 1597:                 }
 1598:             }
 1599:         }
 1600:         foreach my $lonhost (sort(keys(%domservers))) {
 1601:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1602:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1603:             if ($currurls{$lonhost}) {
 1604:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1605:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1606:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1607:                               '">'.$lt{'curr'}.'</a></td>'.
 1608:                               '<td><span class="LC_nobreak"><label>'.
 1609:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1610:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1611:             } else {
 1612:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1613:             }
 1614:             $datatable .='<br />';
 1615:             if ($switchserver) {
 1616:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1617:             } else {
 1618:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1619:             }
 1620:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1621:         }
 1622:         $datatable .= '</table></td></tr>';
 1623:     } elsif ($caller eq 'saml') {
 1624:         my %domservers = &Apache::lonnet::get_servers($dom);
 1625:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1626:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1627:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1628:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1629:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1630:         foreach my $lonhost (keys(%domservers)) {
 1631:             $samlurl{$lonhost} = '/adm/sso';
 1632:             $styleon{$lonhost} = 'display:none';
 1633:             $styleoff{$lonhost} = '';
 1634:         }
 1635:         if (ref($settings->{'saml'}) eq 'HASH') {
 1636:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1637:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1638:                     $saml{$lonhost} = 1;
 1639:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1640:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1641:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1642:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1643:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1644:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1645:                     $styleon{$lonhost} = '';
 1646:                     $styleoff{$lonhost} = 'display:none';
 1647:                 } else {
 1648:                     $styleon{$lonhost} = 'display:none';
 1649:                     $styleoff{$lonhost} = '';
 1650:                 }
 1651:             }
 1652:         }
 1653:         my $itemcount = 1;
 1654:         foreach my $lonhost (sort(keys(%domservers))) {
 1655:             my $samlon = ' ';
 1656:             my $samloff = ' checked="checked" ';
 1657:             if ($saml{$lonhost}) {
 1658:                 $samlon = $samloff;
 1659:                 $samloff = ' ';
 1660:             }
 1661:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1662:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1663:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1664:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1665:                           &mt('No').'</label>'.('&nbsp;'x2).
 1666:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1667:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1668:                           &mt('Yes').'</label></span></td>'.
 1669:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1670:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1671:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1672:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1673:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1674:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1675:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1676:                           $samltext{$lonhost}.'" /></td><td>';
 1677:             if ($samlimg{$lonhost}) {
 1678:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1679:                               '<span class="LC_nobreak"><label>'.
 1680:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1681:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1682:             } else {
 1683:                 $datatable .= $lt{'upl'};
 1684:             }
 1685:             $datatable .='<br />';
 1686:             if ($switchserver) {
 1687:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1688:             } else {
 1689:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1690:             }
 1691:             $datatable .= '</td>'.
 1692:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1693:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1694:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1695:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1696:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1697:                           $samltitle{$lonhost}.'</textarea></td>'.
 1698:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1699:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1700:                           '</table></td>'.
 1701:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1702:            $itemcount ++;
 1703:         }
 1704:         $datatable .= '</table></td></tr>';
 1705:     }
 1706:     return $datatable;
 1707: }
 1708: 
 1709: sub login_choices {
 1710:     my %choices =
 1711:         &Apache::lonlocal::texthash (
 1712:             coursecatalog => 'Display Course/Community Catalog link?',
 1713:             adminmail     => "Display Administrator's E-mail Address?",
 1714:             helpdesk      => 'Display "Contact Helpdesk" link',
 1715:             disallowlogin => "Login page requests redirected",
 1716:             hostid        => "Server",
 1717:             server        => "Redirect to:",
 1718:             serverpath    => "Path",
 1719:             custompath    => "Custom", 
 1720:             exempt        => "Exempt IP(s)",
 1721:             directlogin   => "No redirect",
 1722:             newuser       => "Link to create a user account",
 1723:             img           => "Header",
 1724:             logo          => "Main Logo",
 1725:             domlogo       => "Domain Logo",
 1726:             login         => "Log-in Header", 
 1727:             textcol       => "Text color",
 1728:             bgcol         => "Box color",
 1729:             bgs           => "Background colors",
 1730:             links         => "Link colors",
 1731:             font          => "Font color",
 1732:             pgbg          => "Header",
 1733:             mainbg        => "Page",
 1734:             sidebg        => "Login box",
 1735:             link          => "Link",
 1736:             alink         => "Active link",
 1737:             vlink         => "Visited link",
 1738:             headtag       => "Custom markup",
 1739:             action        => "Action",
 1740:             current       => "Current",
 1741:             samllanding   => "Dual login?",
 1742:             samloptions   => "Options",
 1743:             alttext       => "Alt text",
 1744:         );
 1745:     return %choices;
 1746: }
 1747: 
 1748: sub login_file_options {
 1749:       return &Apache::lonlocal::texthash(
 1750:                                            del     => 'Delete?',
 1751:                                            rep     => 'Replace:',
 1752:                                            upl     => 'Upload:',
 1753:                                            curr    => 'View contents',
 1754:                                            default => 'Default',
 1755:                                            custom  => 'Custom',
 1756:                                            none    => 'None',
 1757:       );
 1758: }
 1759: 
 1760: sub print_ipaccess {
 1761:     my ($dom,$settings,$rowtotal) = @_;
 1762:     my $css_class;
 1763:     my $itemcount = 0;
 1764:     my $datatable;
 1765:     my %ordered;
 1766:     if (ref($settings) eq 'HASH') {
 1767:         foreach my $item (keys(%{$settings})) {
 1768:             if (ref($settings->{$item}) eq 'HASH') {
 1769:                 my $num = $settings->{$item}{'order'};
 1770:                 if ($num eq '') {
 1771:                     $num = scalar(keys(%{$settings}));
 1772:                 }
 1773:                 $ordered{$num} = $item;
 1774:             }
 1775:         }
 1776:     }
 1777:     my $maxnum = scalar(keys(%ordered));
 1778:     if (keys(%ordered)) {
 1779:         my @items = sort { $a <=> $b } keys(%ordered);
 1780:         for (my $i=0; $i<@items; $i++) {
 1781:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1782:             my $item = $ordered{$items[$i]};
 1783:             my ($name,$ipranges,%commblocks,%courses);
 1784:             if (ref($settings->{$item}) eq 'HASH') {
 1785:                 $name = $settings->{$item}->{'name'};
 1786:                 $ipranges = $settings->{$item}->{'ip'};
 1787:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1788:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1789:                 }
 1790:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1791:                     %courses = %{$settings->{$item}->{'courses'}};
 1792:                 }
 1793:             }
 1794:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1795:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1796:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1797:             for (my $k=0; $k<=$maxnum; $k++) {
 1798:                 my $vpos = $k+1;
 1799:                 my $selstr;
 1800:                 if ($k == $i) {
 1801:                     $selstr = ' selected="selected" ';
 1802:                 }
 1803:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1804:             }
 1805:             $datatable .= '</select>'.('&nbsp;'x2).
 1806:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1807:                 &mt('Delete?').'</label></span></td>'.
 1808:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1809:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1810:                 '</td></tr>';
 1811:             $itemcount ++;
 1812:         }
 1813:     }
 1814:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1815:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1816:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1817:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1818:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1819:     for (my $k=0; $k<$maxnum+1; $k++) {
 1820:         my $vpos = $k+1;
 1821:         my $selstr;
 1822:         if ($k == $maxnum) {
 1823:             $selstr = ' selected="selected" ';
 1824:         }
 1825:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1826:     }
 1827:     $datatable .= '</select>&nbsp;'."\n".
 1828:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1829:                   '<td colspan="2">'.
 1830:                   &ipaccess_options('add',$itemcount,$dom).
 1831:                   '</td>'."\n".
 1832:                   '</tr>'."\n";
 1833:     $$rowtotal ++;
 1834:     return $datatable;
 1835: }
 1836: 
 1837: sub ipaccess_options {
 1838:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1839:     my (%currblocks,%currcourses,$output);
 1840:     if (ref($blocksref) eq 'HASH') {
 1841:         %currblocks = %{$blocksref};
 1842:     }
 1843:     if (ref($coursesref) eq 'HASH') {
 1844:         %currcourses = %{$coursesref};
 1845:     }
 1846:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1847:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1848:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1849:               '</span></fieldset>'.
 1850:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1851:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1852:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1853:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1854:               $ipranges.'</textarea></fieldset>'.
 1855:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1856:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1857:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1858:               '<table>';
 1859:     foreach my $cid (sort(keys(%currcourses))) {
 1860:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1861:         $output .= '<tr><td><span class="LC_nobreak">'.
 1862:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1863:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1864:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1865:     }
 1866:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1867:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1868:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1869:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1870:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1871:                '</span></td></tr></table>'."\n".
 1872:                '</fieldset>';
 1873:     return $output;
 1874: }
 1875: 
 1876: sub blocker_checkboxes {
 1877:     my ($num,$blocks) = @_;
 1878:     my ($typeorder,$types) = &commblocktype_text();
 1879:     my $numinrow = 6;
 1880:     my $output = '<table>';
 1881:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1882:         my $block = $typeorder->[$i];
 1883:         my $blockstatus;
 1884:         if (ref($blocks) eq 'HASH') {
 1885:             if ($blocks->{$block} eq 'on') {
 1886:                 $blockstatus = 'checked="checked"';
 1887:             }
 1888:         }
 1889:         my $rem = $i%($numinrow);
 1890:         if ($rem == 0) {
 1891:             if ($i > 0) {
 1892:                 $output .= '</tr>';
 1893:             }
 1894:             $output .= '<tr>';
 1895:         }
 1896:         if ($i == scalar(@{$typeorder})-1) {
 1897:             my $colsleft = $numinrow-$rem;
 1898:             if ($colsleft > 1) {
 1899:                 $output .= '<td colspan="'.$colsleft.'">';
 1900:             } else {
 1901:                 $output .= '<td>';
 1902:             }
 1903:         } else {
 1904:             $output .= '<td>';
 1905:         }
 1906:         my $item = 'ipaccess_block_'.$num;
 1907:         if ($blockstatus) {
 1908:             $blockstatus = ' '.$blockstatus;
 1909:         }
 1910:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1911:                    '<input type="checkbox" name="'.$item.'"'.
 1912:                    $blockstatus.' value="'.$block.'"'.' />'.
 1913:                    $types->{$block}.'</label></span>'."\n".
 1914:                    '<br /></td>';
 1915:     }
 1916:     $output .= '</tr></table>';
 1917:     return $output;
 1918: }
 1919: 
 1920: sub commblocktype_text {
 1921:     my %types = &Apache::lonlocal::texthash(
 1922:         'com' => 'Messaging',
 1923:         'chat' => 'Chat Room',
 1924:         'boards' => 'Discussion',
 1925:         'port' => 'Portfolio',
 1926:         'groups' => 'Groups',
 1927:         'blogs' => 'Blogs',
 1928:         'about' => 'User Information',
 1929:         'printout' => 'Printouts',
 1930:         'passwd' => 'Change Password',
 1931:         'grades' => 'Gradebook',
 1932:         'search' => 'Course search',
 1933:         'wishlist' => 'Stored links',
 1934:         'annotate' => 'Annotations',
 1935:     );
 1936:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1937:     return ($typeorder,\%types);
 1938: }
 1939: 
 1940: sub print_rolecolors {
 1941:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1942:     my %choices = &color_font_choices();
 1943:     my @bgs = ('pgbg','tabbg','sidebg');
 1944:     my @links = ('link','alink','vlink');
 1945:     my @images = ('img');
 1946:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1947:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1948:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1949:     my (%is_custom,%designs);
 1950:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1951:     if (ref($settings) eq 'HASH') {
 1952:         if (ref($settings->{$role}) eq 'HASH') {
 1953:             if ($settings->{$role}->{'img'} ne '') {
 1954:                 $designs{'img'} = $settings->{$role}->{'img'};
 1955:                 $is_custom{'img'} = 1;
 1956:             }
 1957:             if ($settings->{$role}->{'font'} ne '') {
 1958:                 $designs{'font'} = $settings->{$role}->{'font'};
 1959:                 $is_custom{'font'} = 1;
 1960:             }
 1961:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1962:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1963:                 $is_custom{'fontmenu'} = 1;
 1964:             }
 1965:             foreach my $item (@bgs) {
 1966:                 if ($settings->{$role}->{$item} ne '') {
 1967:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1968:                     $is_custom{$item} = 1;
 1969:                 }
 1970:             }
 1971:             foreach my $item (@links) {
 1972:                 if ($settings->{$role}->{$item} ne '') {
 1973:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1974:                     $is_custom{$item} = 1;
 1975:                 }
 1976:             }
 1977:         }
 1978:     } else {
 1979:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1980:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1981:             $is_custom{'img'} = 1;
 1982:         }
 1983:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1984:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1985:             $is_custom{'fontmenu'} = 1; 
 1986:         }
 1987:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1988:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1989:             $is_custom{'font'} = 1;
 1990:         }
 1991:         foreach my $item (@bgs) {
 1992:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1993:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1994:                 $is_custom{$item} = 1;
 1995:             
 1996:             }
 1997:         }
 1998:         foreach my $item (@links) {
 1999:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2000:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2001:                 $is_custom{$item} = 1;
 2002:             }
 2003:         }
 2004:     }
 2005:     my $itemcount = 1;
 2006:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 2007:     $datatable .= '</tr></table></td></tr>';
 2008:     return $datatable;
 2009: }
 2010: 
 2011: sub role_defaults {
 2012:     my ($role,$bgs,$links,$images,$logintext) = @_;
 2013:     my %defaults;
 2014:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 2015:         return %defaults;
 2016:     }
 2017:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 2018:     if ($role eq 'login') {
 2019:         %defaults = (
 2020:                        font => $defaultdesign{$role.'.font'},
 2021:                     );
 2022:         if (ref($logintext) eq 'ARRAY') {
 2023:             foreach my $item (@{$logintext}) {
 2024:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 2025:             }
 2026:         }
 2027:         foreach my $item (@{$images}) {
 2028:             $defaults{'showlogo'}{$item} = 1;
 2029:         }
 2030:     } else {
 2031:         %defaults = (
 2032:                        img => $defaultdesign{$role.'.img'},
 2033:                        font => $defaultdesign{$role.'.font'},
 2034:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 2035:                     );
 2036:     }
 2037:     foreach my $item (@{$bgs}) {
 2038:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 2039:     }
 2040:     foreach my $item (@{$links}) {
 2041:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 2042:     }
 2043:     foreach my $item (@{$images}) {
 2044:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 2045:     }
 2046:     return %defaults;
 2047: }
 2048: 
 2049: sub display_color_options {
 2050:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 2051:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 2052:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2053:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2054:     my $datatable = '<tr'.$css_class.'>'.
 2055:         '<td>'.$choices->{'font'}.'</td>';
 2056:     if (!$is_custom->{'font'}) {
 2057:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 2058:     } else {
 2059:         $datatable .= '<td>&nbsp;</td>';
 2060:     }
 2061:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 2062: 
 2063:     $datatable .= '<td><span class="LC_nobreak">'.
 2064:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 2065:                   ' value="'.$current_color.'" />&nbsp;'.
 2066:                   '&nbsp;</span></td></tr>';
 2067:     unless ($role eq 'login') { 
 2068:         $datatable .= '<tr'.$css_class.'>'.
 2069:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 2070:         if (!$is_custom->{'fontmenu'}) {
 2071:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 2072:         } else {
 2073:             $datatable .= '<td>&nbsp;</td>';
 2074:         }
 2075: 	$current_color = $designs->{'fontmenu'} ?
 2076: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 2077:         $datatable .= '<td><span class="LC_nobreak">'.
 2078:                       '<input class="colorchooser" type="text" size="10" name="'
 2079: 		      .$role.'_fontmenu"'.
 2080:                       ' value="'.$current_color.'" />&nbsp;'.
 2081:                       '&nbsp;</span></td></tr>';
 2082:     }
 2083:     my $switchserver = &check_switchserver($dom,$confname);
 2084:     foreach my $img (@{$images}) {
 2085: 	$itemcount ++;
 2086:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2087:         $datatable .= '<tr'.$css_class.'>'.
 2088:                       '<td>'.$choices->{$img};
 2089:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 2090:         if ($role eq 'login') {
 2091:             if ($img eq 'login') {
 2092:                 $login_hdr_pick =
 2093:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 2094:                 $logincolors =
 2095:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 2096:                                        $designs,$defaults);
 2097:             } else {
 2098:                 if ($img ne 'domlogo') {
 2099:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 2100:                 }
 2101:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 2102:                     $alttext = $designs->{'alttext'}{$img};
 2103:                 }
 2104:             }
 2105:         }
 2106:         $datatable .= '</td>';
 2107:         if ($designs->{$img} ne '') {
 2108:             $imgfile = $designs->{$img};
 2109: 	    $img_import = ($imgfile =~ m{^/adm/});
 2110:         } else {
 2111:             $imgfile = $defaults->{$img};
 2112:         }
 2113:         if ($imgfile) {
 2114:             my ($showfile,$fullsize);
 2115:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 2116:                 my $urldir = $1;
 2117:                 my $filename = $2;
 2118:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 2119:                 if (@info) {
 2120:                     my $thumbfile = 'tn-'.$filename;
 2121:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 2122:                     if (@thumb) {
 2123:                         $showfile = $urldir.'/'.$thumbfile;
 2124:                     } else {
 2125:                         $showfile = $imgfile;
 2126:                     }
 2127:                 } else {
 2128:                     $showfile = '';
 2129:                 }
 2130:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 2131:                 $showfile = $imgfile;
 2132:                 my $imgdir = $1;
 2133:                 my $filename = $2;
 2134:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 2135:                     $showfile = "/$imgdir/tn-".$filename;
 2136:                 } else {
 2137:                     my $input = $londocroot.$imgfile;
 2138:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 2139:                     if (!-e $output) {
 2140:                         my ($width,$height) = &thumb_dimensions();
 2141:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 2142:                         if ($fullwidth ne '' && $fullheight ne '') {
 2143:                             if ($fullwidth > $width && $fullheight > $height) { 
 2144:                                 my $size = $width.'x'.$height;
 2145:                                 my @args = ('convert','-sample',$size,$input,$output);
 2146:                                 system({$args[0]} @args);
 2147:                                 $showfile = "/$imgdir/tn-".$filename;
 2148:                             }
 2149:                         }
 2150:                     }
 2151:                 }
 2152:             }
 2153:             if ($showfile) {
 2154:                 if ($showfile =~ m{^/(adm|res)/}) {
 2155:                     if ($showfile =~ m{^/res/}) {
 2156:                         my $local_showfile =
 2157:                             &Apache::lonnet::filelocation('',$showfile);
 2158:                         &Apache::lonnet::repcopy($local_showfile);
 2159:                     }
 2160:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2161:                 }
 2162:                 if ($imgfile) {
 2163:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2164:                         if ($imgfile =~ m{^/res/}) {
 2165:                             my $local_imgfile =
 2166:                                 &Apache::lonnet::filelocation('',$imgfile);
 2167:                             &Apache::lonnet::repcopy($local_imgfile);
 2168:                         }
 2169:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2170:                     } else {
 2171:                         $fullsize = $imgfile;
 2172:                     }
 2173:                 }
 2174:                 $datatable .= '<td>';
 2175:                 if ($img eq 'login') {
 2176:                     $datatable .= $login_hdr_pick;
 2177:                 } 
 2178:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2179:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2180:             } else {
 2181:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2182:                               &mt('Upload:').'<br />';
 2183:             }
 2184:         } else {
 2185:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2186:                           &mt('Upload:').'<br />';
 2187:         }
 2188:         if ($switchserver) {
 2189:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2190:         } else {
 2191:             if ($img ne 'login') { # suppress file selection for Log-in header
 2192:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2193:             }
 2194:         }
 2195:         if (($role eq 'login') && ($img ne 'login')) {
 2196:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2197:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2198:                           '</label></span>';
 2199:         }
 2200:         $datatable .= '</td></tr>';
 2201:     }
 2202:     $itemcount ++;
 2203:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2204:     $datatable .= '<tr'.$css_class.'>'.
 2205:                   '<td>'.$choices->{'bgs'}.'</td>';
 2206:     my $bgs_def;
 2207:     foreach my $item (@{$bgs}) {
 2208:         if (!$is_custom->{$item}) {
 2209:             $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>';
 2210:         }
 2211:     }
 2212:     if ($bgs_def) {
 2213:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2214:     } else {
 2215:         $datatable .= '<td>&nbsp;</td>';
 2216:     }
 2217:     $datatable .= '<td class="LC_right_item">'.
 2218:                   '<table border="0"><tr>';
 2219: 
 2220:     foreach my $item (@{$bgs}) {
 2221:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 2222: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2223:         if ($designs->{'bgs'}{$item}) {
 2224:             $datatable .= '&nbsp;';
 2225:         }
 2226:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2227:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2228:     }
 2229:     $datatable .= '</tr></table></td></tr>';
 2230:     $itemcount ++;
 2231:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2232:     $datatable .= '<tr'.$css_class.'>'.
 2233:                   '<td>'.$choices->{'links'}.'</td>';
 2234:     my $links_def;
 2235:     foreach my $item (@{$links}) {
 2236:         if (!$is_custom->{$item}) {
 2237:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2238:         }
 2239:     }
 2240:     if ($links_def) {
 2241:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2242:     } else {
 2243:         $datatable .= '<td>&nbsp;</td>';
 2244:     }
 2245:     $datatable .= '<td class="LC_right_item">'.
 2246:                   '<table border="0"><tr>';
 2247:     foreach my $item (@{$links}) {
 2248: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2249:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 2250:         if ($designs->{'links'}{$item}) {
 2251:             $datatable.='&nbsp;';
 2252:         }
 2253:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2254:                       '" /></td>';
 2255:     }
 2256:     $$rowtotal += $itemcount;
 2257:     return $datatable;
 2258: }
 2259: 
 2260: sub logo_display_options {
 2261:     my ($img,$defaults,$designs) = @_;
 2262:     my $checkedon;
 2263:     if (ref($defaults) eq 'HASH') {
 2264:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2265:             if ($defaults->{'showlogo'}{$img}) {
 2266:                 $checkedon = 'checked="checked" ';     
 2267:             }
 2268:         } 
 2269:     }
 2270:     if (ref($designs) eq 'HASH') {
 2271:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2272:             if (defined($designs->{'showlogo'}{$img})) {
 2273:                 if ($designs->{'showlogo'}{$img} == 0) {
 2274:                     $checkedon = '';
 2275:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2276:                     $checkedon = 'checked="checked" ';
 2277:                 }
 2278:             }
 2279:         }
 2280:     }
 2281:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2282:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2283:            &mt('show').'</label>'."\n";
 2284: }
 2285: 
 2286: sub login_header_options  {
 2287:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2288:     my $output = '';
 2289:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2290:         $output .= &mt('Text default(s):').'<br />';
 2291:         if (!$is_custom->{'textcol'}) {
 2292:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2293:                        '&nbsp;&nbsp;&nbsp;';
 2294:         }
 2295:         if (!$is_custom->{'bgcol'}) {
 2296:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2297:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2298:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2299:         }
 2300:         $output .= '<br />';
 2301:     }
 2302:     $output .='<br />';
 2303:     return $output;
 2304: }
 2305: 
 2306: sub login_text_colors {
 2307:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2308:     my $color_menu = '<table border="0"><tr>';
 2309:     foreach my $item (@{$logintext}) {
 2310:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 2311:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2312:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2313:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2314:     }
 2315:     $color_menu .= '</tr></table><br />';
 2316:     return $color_menu;
 2317: }
 2318: 
 2319: sub image_changes {
 2320:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2321:     my $output;
 2322:     if ($img eq 'login') {
 2323:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2324:     } elsif (!$is_custom) {
 2325:         if ($img ne 'domlogo') {
 2326:             $output = &mt('Default image:').'<br />';
 2327:         } else {
 2328:             $output = &mt('Default in use:').'<br />';
 2329:         }
 2330:     }
 2331:     if ($img ne 'login') {
 2332:         if ($img_import) {
 2333:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2334:         }
 2335:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2336:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2337:         if ($is_custom) {
 2338:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2339:                        '<input type="checkbox" name="'.
 2340:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2341:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2342:         } else {
 2343:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 2344:         }
 2345:     }
 2346:     return $output;
 2347: }
 2348: 
 2349: sub print_quotas {
 2350:     my ($dom,$settings,$rowtotal,$action) = @_;
 2351:     my $context;
 2352:     if ($action eq 'quotas') {
 2353:         $context = 'tools';
 2354:     } else {
 2355:         $context = $action;
 2356:     }
 2357:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2358:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2359:     my $typecount = 0;
 2360:     my ($css_class,%titles);
 2361:     if ($context eq 'requestcourses') {
 2362:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2363:         @options =('norequest','approval','validate','autolimit');
 2364:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2365:         %titles = &courserequest_titles();
 2366:     } elsif ($context eq 'requestauthor') {
 2367:         @usertools = ('author');
 2368:         @options = ('norequest','approval','automatic');
 2369:         %titles = &authorrequest_titles();
 2370:     } else {
 2371:         @usertools = ('aboutme','blog','webdav','portfolio');
 2372:         %titles = &tool_titles();
 2373:     }
 2374:     if (ref($types) eq 'ARRAY') {
 2375:         foreach my $type (@{$types}) {
 2376:             my ($currdefquota,$currauthorquota);
 2377:             unless (($context eq 'requestcourses') ||
 2378:                     ($context eq 'requestauthor')) {
 2379:                 if (ref($settings) eq 'HASH') {
 2380:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2381:                         $currdefquota = $settings->{defaultquota}->{$type};
 2382:                     } else {
 2383:                         $currdefquota = $settings->{$type};
 2384:                     }
 2385:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2386:                         $currauthorquota = $settings->{authorquota}->{$type};
 2387:                     }
 2388:                 }
 2389:             }
 2390:             if (defined($usertypes->{$type})) {
 2391:                 $typecount ++;
 2392:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2393:                 $datatable .= '<tr'.$css_class.'>'.
 2394:                               '<td>'.$usertypes->{$type}.'</td>'.
 2395:                               '<td class="LC_left_item">';
 2396:                 if ($context eq 'requestcourses') {
 2397:                     $datatable .= '<table><tr>';
 2398:                 }
 2399:                 my %cell;  
 2400:                 foreach my $item (@usertools) {
 2401:                     if ($context eq 'requestcourses') {
 2402:                         my ($curroption,$currlimit);
 2403:                         if (ref($settings) eq 'HASH') {
 2404:                             if (ref($settings->{$item}) eq 'HASH') {
 2405:                                 $curroption = $settings->{$item}->{$type};
 2406:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2407:                                     $currlimit = $1; 
 2408:                                 }
 2409:                             }
 2410:                         }
 2411:                         if (!$curroption) {
 2412:                             $curroption = 'norequest';
 2413:                         }
 2414:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2415:                         foreach my $option (@options) {
 2416:                             my $val = $option;
 2417:                             if ($option eq 'norequest') {
 2418:                                 $val = 0;  
 2419:                             }
 2420:                             if ($option eq 'validate') {
 2421:                                 my $canvalidate = 0;
 2422:                                 if (ref($validations{$item}) eq 'HASH') { 
 2423:                                     if ($validations{$item}{$type}) {
 2424:                                         $canvalidate = 1;
 2425:                                     }
 2426:                                 }
 2427:                                 next if (!$canvalidate);
 2428:                             }
 2429:                             my $checked = '';
 2430:                             if ($option eq $curroption) {
 2431:                                 $checked = ' checked="checked"';
 2432:                             } elsif ($option eq 'autolimit') {
 2433:                                 if ($curroption =~ /^autolimit/) {
 2434:                                     $checked = ' checked="checked"';
 2435:                                 }                       
 2436:                             } 
 2437:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2438:                                   '<input type="radio" name="crsreq_'.$item.
 2439:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2440:                                   $titles{$option}.'</label>';
 2441:                             if ($option eq 'autolimit') {
 2442:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2443:                                                 $item.'_limit_'.$type.'" size="1" '.
 2444:                                                 'value="'.$currlimit.'" />';
 2445:                             }
 2446:                             $cell{$item} .= '</span> ';
 2447:                             if ($option eq 'autolimit') {
 2448:                                 $cell{$item} .= $titles{'unlimited'};
 2449:                             }
 2450:                         }
 2451:                     } elsif ($context eq 'requestauthor') {
 2452:                         my $curroption;
 2453:                         if (ref($settings) eq 'HASH') {
 2454:                             $curroption = $settings->{$type};
 2455:                         }
 2456:                         if (!$curroption) {
 2457:                             $curroption = 'norequest';
 2458:                         }
 2459:                         foreach my $option (@options) {
 2460:                             my $val = $option;
 2461:                             if ($option eq 'norequest') {
 2462:                                 $val = 0;
 2463:                             }
 2464:                             my $checked = '';
 2465:                             if ($option eq $curroption) {
 2466:                                 $checked = ' checked="checked"';
 2467:                             }
 2468:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2469:                                   '<input type="radio" name="authorreq_'.$type.
 2470:                                   '" value="'.$val.'"'.$checked.' />'.
 2471:                                   $titles{$option}.'</label></span>&nbsp; ';
 2472:                         }
 2473:                     } else {
 2474:                         my $checked = 'checked="checked" ';
 2475:                         if (ref($settings) eq 'HASH') {
 2476:                             if (ref($settings->{$item}) eq 'HASH') {
 2477:                                 if ($settings->{$item}->{$type} == 0) {
 2478:                                     $checked = '';
 2479:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2480:                                     $checked =  'checked="checked" ';
 2481:                                 }
 2482:                             }
 2483:                         }
 2484:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2485:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2486:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2487:                                       '</label></span>&nbsp; ';
 2488:                     }
 2489:                 }
 2490:                 if ($context eq 'requestcourses') {
 2491:                     $datatable .= '</tr><tr>';
 2492:                     foreach my $item (@usertools) {
 2493:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2494:                     }
 2495:                     $datatable .= '</tr></table>';
 2496:                 }
 2497:                 $datatable .= '</td>';
 2498:                 unless (($context eq 'requestcourses') ||
 2499:                         ($context eq 'requestauthor')) {
 2500:                     $datatable .= 
 2501:                               '<td class="LC_right_item">'.
 2502:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2503:                               '<input type="text" name="quota_'.$type.
 2504:                               '" value="'.$currdefquota.
 2505:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2506:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2507:                               '<input type="text" name="authorquota_'.$type.
 2508:                               '" value="'.$currauthorquota.
 2509:                               '" size="5" /></span></td>';
 2510:                 }
 2511:                 $datatable .= '</tr>';
 2512:             }
 2513:         }
 2514:     }
 2515:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2516:         $defaultquota = '20';
 2517:         $authorquota = '500';
 2518:         if (ref($settings) eq 'HASH') {
 2519:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2520:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2521:             } elsif (defined($settings->{'default'})) {
 2522:                 $defaultquota = $settings->{'default'};
 2523:             }
 2524:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2525:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2526:             }
 2527:         }
 2528:     }
 2529:     $typecount ++;
 2530:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2531:     $datatable .= '<tr'.$css_class.'>'.
 2532:                   '<td>'.$othertitle.'</td>'.
 2533:                   '<td class="LC_left_item">';
 2534:     if ($context eq 'requestcourses') {
 2535:         $datatable .= '<table><tr>';
 2536:     }
 2537:     my %defcell;
 2538:     foreach my $item (@usertools) {
 2539:         if ($context eq 'requestcourses') {
 2540:             my ($curroption,$currlimit);
 2541:             if (ref($settings) eq 'HASH') {
 2542:                 if (ref($settings->{$item}) eq 'HASH') {
 2543:                     $curroption = $settings->{$item}->{'default'};
 2544:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2545:                         $currlimit = $1;
 2546:                     }
 2547:                 }
 2548:             }
 2549:             if (!$curroption) {
 2550:                 $curroption = 'norequest';
 2551:             }
 2552:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2553:             foreach my $option (@options) {
 2554:                 my $val = $option;
 2555:                 if ($option eq 'norequest') {
 2556:                     $val = 0;
 2557:                 }
 2558:                 if ($option eq 'validate') {
 2559:                     my $canvalidate = 0;
 2560:                     if (ref($validations{$item}) eq 'HASH') {
 2561:                         if ($validations{$item}{'default'}) {
 2562:                             $canvalidate = 1;
 2563:                         }
 2564:                     }
 2565:                     next if (!$canvalidate);
 2566:                 }
 2567:                 my $checked = '';
 2568:                 if ($option eq $curroption) {
 2569:                     $checked = ' checked="checked"';
 2570:                 } elsif ($option eq 'autolimit') {
 2571:                     if ($curroption =~ /^autolimit/) {
 2572:                         $checked = ' checked="checked"';
 2573:                     }
 2574:                 }
 2575:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2576:                                   '<input type="radio" name="crsreq_'.$item.
 2577:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2578:                                   $titles{$option}.'</label>';
 2579:                 if ($option eq 'autolimit') {
 2580:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2581:                                        $item.'_limit_default" size="1" '.
 2582:                                        'value="'.$currlimit.'" />';
 2583:                 }
 2584:                 $defcell{$item} .= '</span> ';
 2585:                 if ($option eq 'autolimit') {
 2586:                     $defcell{$item} .= $titles{'unlimited'};
 2587:                 }
 2588:             }
 2589:         } elsif ($context eq 'requestauthor') {
 2590:             my $curroption;
 2591:             if (ref($settings) eq 'HASH') {
 2592:                 $curroption = $settings->{'default'};
 2593:             }
 2594:             if (!$curroption) {
 2595:                 $curroption = 'norequest';
 2596:             }
 2597:             foreach my $option (@options) {
 2598:                 my $val = $option;
 2599:                 if ($option eq 'norequest') {
 2600:                     $val = 0;
 2601:                 }
 2602:                 my $checked = '';
 2603:                 if ($option eq $curroption) {
 2604:                     $checked = ' checked="checked"';
 2605:                 }
 2606:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2607:                               '<input type="radio" name="authorreq_default"'.
 2608:                               ' value="'.$val.'"'.$checked.' />'.
 2609:                               $titles{$option}.'</label></span>&nbsp; ';
 2610:             }
 2611:         } else {
 2612:             my $checked = 'checked="checked" ';
 2613:             if (ref($settings) eq 'HASH') {
 2614:                 if (ref($settings->{$item}) eq 'HASH') {
 2615:                     if ($settings->{$item}->{'default'} == 0) {
 2616:                         $checked = '';
 2617:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2618:                         $checked = 'checked="checked" ';
 2619:                     }
 2620:                 }
 2621:             }
 2622:             $datatable .= '<span class="LC_nobreak"><label>'.
 2623:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2624:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2625:                           '</label></span>&nbsp; ';
 2626:         }
 2627:     }
 2628:     if ($context eq 'requestcourses') {
 2629:         $datatable .= '</tr><tr>';
 2630:         foreach my $item (@usertools) {
 2631:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2632:         }
 2633:         $datatable .= '</tr></table>';
 2634:     }
 2635:     $datatable .= '</td>';
 2636:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2637:         $datatable .= '<td class="LC_right_item">'.
 2638:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2639:                       '<input type="text" name="defaultquota" value="'.
 2640:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2641:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2642:                       '<input type="text" name="authorquota" value="'.
 2643:                       $authorquota.'" size="5" /></span></td>';
 2644:     }
 2645:     $datatable .= '</tr>';
 2646:     $typecount ++;
 2647:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2648:     $datatable .= '<tr'.$css_class.'>'.
 2649:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2650:     if ($context eq 'requestcourses') {
 2651:         $datatable .= &mt('(overrides affiliation, if set)').
 2652:                       '</td>'.
 2653:                       '<td class="LC_left_item">'.
 2654:                       '<table><tr>';
 2655:     } else {
 2656:         $datatable .= &mt('(overrides affiliation, if checked)').
 2657:                       '</td>'.
 2658:                       '<td class="LC_left_item" colspan="2">'.
 2659:                       '<br />';
 2660:     }
 2661:     my %advcell;
 2662:     foreach my $item (@usertools) {
 2663:         if ($context eq 'requestcourses') {
 2664:             my ($curroption,$currlimit);
 2665:             if (ref($settings) eq 'HASH') {
 2666:                 if (ref($settings->{$item}) eq 'HASH') {
 2667:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2668:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2669:                         $currlimit = $1;
 2670:                     }
 2671:                 }
 2672:             }
 2673:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2674:             my $checked = '';
 2675:             if ($curroption eq '') {
 2676:                 $checked = ' checked="checked"';
 2677:             }
 2678:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2679:                                '<input type="radio" name="crsreq_'.$item.
 2680:                                '__LC_adv" value=""'.$checked.' />'.
 2681:                                &mt('No override set').'</label></span>&nbsp; ';
 2682:             foreach my $option (@options) {
 2683:                 my $val = $option;
 2684:                 if ($option eq 'norequest') {
 2685:                     $val = 0;
 2686:                 }
 2687:                 if ($option eq 'validate') {
 2688:                     my $canvalidate = 0;
 2689:                     if (ref($validations{$item}) eq 'HASH') {
 2690:                         if ($validations{$item}{'_LC_adv'}) {
 2691:                             $canvalidate = 1;
 2692:                         }
 2693:                     }
 2694:                     next if (!$canvalidate);
 2695:                 }
 2696:                 my $checked = '';
 2697:                 if ($val eq $curroption) {
 2698:                     $checked = ' checked="checked"';
 2699:                 } elsif ($option eq 'autolimit') {
 2700:                     if ($curroption =~ /^autolimit/) {
 2701:                         $checked = ' checked="checked"';
 2702:                     }
 2703:                 }
 2704:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2705:                                   '<input type="radio" name="crsreq_'.$item.
 2706:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2707:                                   $titles{$option}.'</label>';
 2708:                 if ($option eq 'autolimit') {
 2709:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2710:                                        $item.'_limit__LC_adv" size="1" '.
 2711:                                        'value="'.$currlimit.'" />';
 2712:                 }
 2713:                 $advcell{$item} .= '</span> ';
 2714:                 if ($option eq 'autolimit') {
 2715:                     $advcell{$item} .= $titles{'unlimited'};
 2716:                 }
 2717:             }
 2718:         } elsif ($context eq 'requestauthor') {
 2719:             my $curroption;
 2720:             if (ref($settings) eq 'HASH') {
 2721:                 $curroption = $settings->{'_LC_adv'};
 2722:             }
 2723:             my $checked = '';
 2724:             if ($curroption eq '') {
 2725:                 $checked = ' checked="checked"';
 2726:             }
 2727:             $datatable .= '<span class="LC_nobreak"><label>'.
 2728:                           '<input type="radio" name="authorreq__LC_adv"'.
 2729:                           ' value=""'.$checked.' />'.
 2730:                           &mt('No override set').'</label></span>&nbsp; ';
 2731:             foreach my $option (@options) {
 2732:                 my $val = $option;
 2733:                 if ($option eq 'norequest') {
 2734:                     $val = 0;
 2735:                 }
 2736:                 my $checked = '';
 2737:                 if ($val eq $curroption) {
 2738:                     $checked = ' checked="checked"';
 2739:                 }
 2740:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2741:                               '<input type="radio" name="authorreq__LC_adv"'.
 2742:                               ' value="'.$val.'"'.$checked.' />'.
 2743:                               $titles{$option}.'</label></span>&nbsp; ';
 2744:             }
 2745:         } else {
 2746:             my $checked = 'checked="checked" ';
 2747:             if (ref($settings) eq 'HASH') {
 2748:                 if (ref($settings->{$item}) eq 'HASH') {
 2749:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2750:                         $checked = '';
 2751:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2752:                         $checked = 'checked="checked" ';
 2753:                     }
 2754:                 }
 2755:             }
 2756:             $datatable .= '<span class="LC_nobreak"><label>'.
 2757:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2758:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2759:                           '</label></span>&nbsp; ';
 2760:         }
 2761:     }
 2762:     if ($context eq 'requestcourses') {
 2763:         $datatable .= '</tr><tr>';
 2764:         foreach my $item (@usertools) {
 2765:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2766:         }
 2767:         $datatable .= '</tr></table>';
 2768:     }
 2769:     $datatable .= '</td></tr>';
 2770:     $$rowtotal += $typecount;
 2771:     return $datatable;
 2772: }
 2773: 
 2774: sub print_requestmail {
 2775:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2776:     my ($now,$datatable,%currapp);
 2777:     $now = time;
 2778:     if (ref($settings) eq 'HASH') {
 2779:         if (ref($settings->{'notify'}) eq 'HASH') {
 2780:             if ($settings->{'notify'}{'approval'} ne '') {
 2781:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2782:             }
 2783:         }
 2784:     }
 2785:     my $numinrow = 2;
 2786:     my $css_class;
 2787:     if ($$rowtotal%2) {
 2788:         $css_class = 'LC_odd_row';
 2789:     }
 2790:     if ($customcss) {
 2791:         $css_class .= " $customcss";
 2792:     }
 2793:     $css_class =~ s/^\s+//;
 2794:     if ($css_class) {
 2795:         $css_class = ' class="'.$css_class.'"';
 2796:     }
 2797:     if ($rowstyle) {
 2798:         $css_class .= ' style="'.$rowstyle.'"';
 2799:     }
 2800:     my $text;
 2801:     if ($action eq 'requestcourses') {
 2802:         $text = &mt('Receive notification of course requests requiring approval');
 2803:     } elsif ($action eq 'requestauthor') {
 2804:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2805:     } else {
 2806:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2807:     }
 2808:     $datatable = '<tr'.$css_class.'>'.
 2809:                  ' <td>'.$text.'</td>'.
 2810:                  ' <td class="LC_left_item">';
 2811:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2812:                                                  $action.'notifyapproval',%currapp);
 2813:     if ($numdc > 0) {
 2814:         $datatable .= $table;
 2815:     } else {
 2816:         $datatable .= &mt('There are no active Domain Coordinators');
 2817:     }
 2818:     $datatable .='</td></tr>';
 2819:     return $datatable;
 2820: }
 2821: 
 2822: sub print_studentcode {
 2823:     my ($settings,$rowtotal) = @_;
 2824:     my $rownum = 0; 
 2825:     my ($output,%current);
 2826:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2827:     if (ref($settings) eq 'HASH') {
 2828:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2829:             foreach my $type (@crstypes) {
 2830:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2831:             }
 2832:         }
 2833:     }
 2834:     $output .= '<tr>'.
 2835:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2836:                '<td class="LC_left_item">';
 2837:     foreach my $type (@crstypes) {
 2838:         my $check = ' ';
 2839:         if ($current{$type}) {
 2840:             $check = ' checked="checked" ';
 2841:         }
 2842:         $output .= '<span class="LC_nobreak"><label>'.
 2843:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2844:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2845:     }
 2846:     $output .= '</td></tr>';
 2847:     $$rowtotal ++;
 2848:     return $output;
 2849: }
 2850: 
 2851: sub print_textbookcourses {
 2852:     my ($dom,$type,$settings,$rowtotal) = @_;
 2853:     my $rownum = 0;
 2854:     my $css_class;
 2855:     my $itemcount = 1;
 2856:     my $maxnum = 0;
 2857:     my $bookshash;
 2858:     if (ref($settings) eq 'HASH') {
 2859:         $bookshash = $settings->{$type};
 2860:     }
 2861:     my %ordered;
 2862:     if (ref($bookshash) eq 'HASH') {
 2863:         foreach my $item (keys(%{$bookshash})) {
 2864:             if (ref($bookshash->{$item}) eq 'HASH') {
 2865:                 my $num = $bookshash->{$item}{'order'};
 2866:                 $ordered{$num} = $item;
 2867:             }
 2868:         }
 2869:     }
 2870:     my $confname = $dom.'-domainconfig';
 2871:     my $switchserver = &check_switchserver($dom,$confname);
 2872:     my $maxnum = scalar(keys(%ordered));
 2873:     my $datatable;
 2874:     if (keys(%ordered)) {
 2875:         my @items = sort { $a <=> $b } keys(%ordered);
 2876:         for (my $i=0; $i<@items; $i++) {
 2877:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2878:             my $key = $ordered{$items[$i]};
 2879:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2880:             my $coursetitle = $coursehash{'description'};
 2881:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2882:             if (ref($bookshash->{$key}) eq 'HASH') {
 2883:                 $subject = $bookshash->{$key}->{'subject'};
 2884:                 $title = $bookshash->{$key}->{'title'};
 2885:                 if ($type eq 'textbooks') {
 2886:                     $publisher = $bookshash->{$key}->{'publisher'};
 2887:                     $author = $bookshash->{$key}->{'author'};
 2888:                     $image = $bookshash->{$key}->{'image'};
 2889:                     if ($image ne '') {
 2890:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2891:                         my $imagethumb = "$path/tn-".$imagefile;
 2892:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2893:                     }
 2894:                 }
 2895:             }
 2896:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2897:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2898:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2899:             for (my $k=0; $k<=$maxnum; $k++) {
 2900:                 my $vpos = $k+1;
 2901:                 my $selstr;
 2902:                 if ($k == $i) {
 2903:                     $selstr = ' selected="selected" ';
 2904:                 }
 2905:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2906:             }
 2907:             $datatable .= '</select>'.('&nbsp;'x2).
 2908:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2909:                 &mt('Delete?').'</label></span></td>'.
 2910:                 '<td colspan="2">'.
 2911:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2912:                 ('&nbsp;'x2).
 2913:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2914:             if ($type eq 'textbooks') {
 2915:                 $datatable .= ('&nbsp;'x2).
 2916:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2917:                               ('&nbsp;'x2).
 2918:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2919:                               ('&nbsp;'x2).
 2920:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2921:                 if ($image) {
 2922:                     $datatable .= $imgsrc.
 2923:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2924:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2925:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2926:                 }
 2927:                 if ($switchserver) {
 2928:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2929:                 } else {
 2930:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2931:                 }
 2932:             }
 2933:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2934:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2935:                           $coursetitle.'</span></td></tr>'."\n";
 2936:             $itemcount ++;
 2937:         }
 2938:     }
 2939:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2940:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2941:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2942:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2943:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2944:     for (my $k=0; $k<$maxnum+1; $k++) {
 2945:         my $vpos = $k+1;
 2946:         my $selstr;
 2947:         if ($k == $maxnum) {
 2948:             $selstr = ' selected="selected" ';
 2949:         }
 2950:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2951:     }
 2952:     $datatable .= '</select>&nbsp;'."\n".
 2953:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2954:                   '<td colspan="2">'.
 2955:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2956:                   ('&nbsp;'x2).
 2957:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2958:                   ('&nbsp;'x2);
 2959:     if ($type eq 'textbooks') {
 2960:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2961:                       ('&nbsp;'x2).
 2962:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2963:                       ('&nbsp;'x2).
 2964:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2965:         if ($switchserver) {
 2966:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2967:         } else {
 2968:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2969:         }
 2970:         $datatable .= '</span>'."\n";
 2971:     }
 2972:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2973:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2974:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2975:                   &Apache::loncommon::selectcourse_link
 2976:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2977:                   '</span></td>'."\n".
 2978:                   '</tr>'."\n";
 2979:     $itemcount ++;
 2980:     return $datatable;
 2981: }
 2982: 
 2983: sub textbookcourses_javascript {
 2984:     my ($settings) = @_;
 2985:     return unless(ref($settings) eq 'HASH');
 2986:     my (%ordered,%total,%jstext);
 2987:     foreach my $type ('textbooks','templates') {
 2988:         $total{$type} = 0;
 2989:         if (ref($settings->{$type}) eq 'HASH') {
 2990:             foreach my $item (keys(%{$settings->{$type}})) {
 2991:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2992:                     my $num = $settings->{$type}->{$item}{'order'};
 2993:                     $ordered{$type}{$num} = $item;
 2994:                 }
 2995:             }
 2996:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2997:         }
 2998:         my @jsarray = ();
 2999:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 3000:             push(@jsarray,$ordered{$type}{$item});
 3001:         }
 3002:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 3003:     }
 3004:     return <<"ENDSCRIPT";
 3005: <script type="text/javascript">
 3006: // <![CDATA[
 3007: function reorderBooks(form,item,caller) {
 3008:     var changedVal;
 3009: $jstext{'textbooks'};
 3010: $jstext{'templates'};
 3011:     var newpos;
 3012:     var maxh;
 3013:     if (caller == 'textbooks') {  
 3014:         newpos = 'textbooks_addbook_pos';
 3015:         maxh = 1 + $total{'textbooks'};
 3016:     } else {
 3017:         newpos = 'templates_addbook_pos';
 3018:         maxh = 1 + $total{'templates'};
 3019:     }
 3020:     var current = new Array;
 3021:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3022:     if (item == newpos) {
 3023:         changedVal = newitemVal;
 3024:     } else {
 3025:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3026:         current[newitemVal] = newpos;
 3027:     }
 3028:     if (caller == 'textbooks') {
 3029:         for (var i=0; i<textbooks.length; i++) {
 3030:             var elementName = 'textbooks_'+textbooks[i];
 3031:             if (elementName != item) {
 3032:                 if (form.elements[elementName]) {
 3033:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3034:                     current[currVal] = elementName;
 3035:                 }
 3036:             }
 3037:         }
 3038:     }
 3039:     if (caller == 'templates') {
 3040:         for (var i=0; i<templates.length; i++) {
 3041:             var elementName = 'templates_'+templates[i];
 3042:             if (elementName != item) {
 3043:                 if (form.elements[elementName]) {
 3044:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3045:                     current[currVal] = elementName;
 3046:                 }
 3047:             }
 3048:         }
 3049:     }
 3050:     var oldVal;
 3051:     for (var j=0; j<maxh; j++) {
 3052:         if (current[j] == undefined) {
 3053:             oldVal = j;
 3054:         }
 3055:     }
 3056:     if (oldVal < changedVal) {
 3057:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3058:            var elementName = current[k];
 3059:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3060:         }
 3061:     } else {
 3062:         for (var k=changedVal; k<oldVal; k++) {
 3063:             var elementName = current[k];
 3064:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3065:         }
 3066:     }
 3067:     return;
 3068: }
 3069: 
 3070: // ]]>
 3071: </script>
 3072: 
 3073: ENDSCRIPT
 3074: }
 3075: 
 3076: sub ltitools_javascript {
 3077:     my ($settings) = @_;
 3078:     my $togglejs = &ltitools_toggle_js();
 3079:     unless (ref($settings) eq 'HASH') {
 3080:         return $togglejs;
 3081:     }
 3082:     my (%ordered,$total,%jstext);
 3083:     $total = 0;
 3084:     foreach my $item (keys(%{$settings})) {
 3085:         if (ref($settings->{$item}) eq 'HASH') {
 3086:             my $num = $settings->{$item}{'order'};
 3087:             $ordered{$num} = $item;
 3088:         }
 3089:     }
 3090:     $total = scalar(keys(%{$settings}));
 3091:     my @jsarray = ();
 3092:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3093:         push(@jsarray,$ordered{$item});
 3094:     }
 3095:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 3096:     return <<"ENDSCRIPT";
 3097: <script type="text/javascript">
 3098: // <![CDATA[
 3099: function reorderLTITools(form,item) {
 3100:     var changedVal;
 3101: $jstext
 3102:     var newpos = 'ltitools_add_pos';
 3103:     var maxh = 1 + $total;
 3104:     var current = new Array;
 3105:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3106:     if (item == newpos) {
 3107:         changedVal = newitemVal;
 3108:     } else {
 3109:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3110:         current[newitemVal] = newpos;
 3111:     }
 3112:     for (var i=0; i<ltitools.length; i++) {
 3113:         var elementName = 'ltitools_'+ltitools[i];
 3114:         if (elementName != item) {
 3115:             if (form.elements[elementName]) {
 3116:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3117:                 current[currVal] = elementName;
 3118:             }
 3119:         }
 3120:     }
 3121:     var oldVal;
 3122:     for (var j=0; j<maxh; j++) {
 3123:         if (current[j] == undefined) {
 3124:             oldVal = j;
 3125:         }
 3126:     }
 3127:     if (oldVal < changedVal) {
 3128:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3129:            var elementName = current[k];
 3130:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3131:         }
 3132:     } else {
 3133:         for (var k=changedVal; k<oldVal; k++) {
 3134:             var elementName = current[k];
 3135:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3136:         }
 3137:     }
 3138:     return;
 3139: }
 3140: 
 3141: // ]]>
 3142: </script>
 3143: 
 3144: $togglejs
 3145: 
 3146: ENDSCRIPT
 3147: }
 3148: 
 3149: sub ltitools_toggle_js {
 3150:     return <<"ENDSCRIPT";
 3151: <script type="text/javascript">
 3152: // <![CDATA[
 3153: 
 3154: function toggleLTITools(form,setting,item) {
 3155:     var radioname = '';
 3156:     var divid = '';
 3157:     if ((setting == 'passback') || (setting == 'roster')) {
 3158:         radioname = 'ltitools_'+setting+'_'+item;
 3159:         divid = 'ltitools_'+setting+'time_'+item;
 3160:         var num = form.elements[radioname].length;
 3161:         if (num) {
 3162:             var setvis = '';
 3163:             for (var i=0; i<num; i++) {
 3164:                 if (form.elements[radioname][i].checked) {
 3165:                     if (form.elements[radioname][i].value == '1') {
 3166:                         if (document.getElementById(divid)) {
 3167:                             document.getElementById(divid).style.display = 'inline-block';
 3168:                         }
 3169:                         setvis = 1;
 3170:                     }
 3171:                     break;
 3172:                 }
 3173:             }
 3174:         }
 3175:         if (!setvis) {
 3176:             if (document.getElementById(divid)) {
 3177:                 document.getElementById(divid).style.display = 'none';
 3178:             }
 3179:         }
 3180:     }
 3181:     if (setting == 'user') {
 3182:         divid = 'ltitools_'+setting+'_div_'+item;
 3183:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3184:         if (document.getElementById(divid)) {
 3185:             if (document.getElementById(checkid)) {
 3186:                 if (document.getElementById(checkid).checked) {
 3187:                     document.getElementById(divid).style.display = 'inline-block';
 3188:                 } else {
 3189:                     document.getElementById(divid).style.display = 'none';
 3190:                 }
 3191:             }
 3192:         }
 3193:     }
 3194:     return;
 3195: }
 3196: // ]]>
 3197: </script>
 3198: 
 3199: ENDSCRIPT
 3200: }
 3201: 
 3202: sub wafproxy_javascript {
 3203:     my ($dom) = @_;
 3204:     return <<"ENDSCRIPT";
 3205: <script type="text/javascript">
 3206: // <![CDATA[
 3207: function updateWAF() {
 3208:     if (document.getElementById('wafproxy_remoteip')) {
 3209:         var wafremote = 0;
 3210:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3211:             wafremote = 1;
 3212:         }
 3213:         var fields = new Array('header','trust');
 3214:         for (var i=0; i<fields.length; i++) {
 3215:             if (document.getElementById('wafproxy_'+fields[i])) {
 3216:                 if (wafremote == 1) {
 3217:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3218:                 }
 3219:                 else {
 3220:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3221:                 }
 3222:             }
 3223:         }
 3224:         if (document.getElementById('wafproxyranges_$dom')) {
 3225:             if (wafremote == 1) {
 3226:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3227:             } else {
 3228:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3229:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3230:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3231:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3232:                         }
 3233:                     }
 3234:                 }
 3235:             }
 3236:         }
 3237:     }
 3238:     return;
 3239: }
 3240: 
 3241: function checkWAF() {
 3242:     if (document.getElementById('wafproxy_remoteip')) {
 3243:         var wafvpn = 0;
 3244:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3245:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3246:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3247:                     wafvpn = 1;
 3248:                 }
 3249:                 break;
 3250:             }
 3251:         }
 3252:         var vpn = new Array('vpnint','vpnext');
 3253:         for (var i=0; i<vpn.length; i++) {
 3254:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3255:                 if (wafvpn == 1) {
 3256:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3257:                 }
 3258:                 else {
 3259:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3260:                 }
 3261:             }
 3262:         }
 3263:         if (document.getElementById('wafproxyranges_$dom')) {
 3264:             if (wafvpn == 1) {
 3265:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3266:             }
 3267:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3268:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3269:             }
 3270:         }
 3271:     }
 3272:     return;
 3273: }
 3274: 
 3275: function toggleWAF() {
 3276:     if (document.getElementById('wafproxy_table')) {
 3277:         var wafproxy = 0;
 3278:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3279:              if (document.display.wafproxy_${dom}[i].checked) {
 3280:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3281:                      wafproxy = 1;
 3282:                      break;
 3283:                 }
 3284:             }
 3285:         }
 3286:         if (wafproxy == 1) {
 3287:             document.getElementById('wafproxy_table').style.display='inline';
 3288:         }
 3289:         else {
 3290:            document.getElementById('wafproxy_table').style.display='none';
 3291:         }
 3292:         if (document.getElementById('wafproxyrow_${dom}')) {
 3293:             if (wafproxy == 1) {
 3294:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3295:             }
 3296:             else {
 3297:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3298:             }
 3299:         }
 3300:         if (document.getElementById('nowafproxyrow_$dom')) {
 3301:             if (wafproxy == 1) {
 3302:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3303:             }
 3304:             else {
 3305:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3306:             }
 3307:         }
 3308:     }
 3309:     return;
 3310: }
 3311: // ]]>
 3312: </script>
 3313: 
 3314: ENDSCRIPT
 3315: }
 3316: 
 3317: sub proctoring_javascript {
 3318:     my ($settings) = @_;
 3319:     my (%ordered,$total,%jstext);
 3320:     $total = 0;
 3321:     if (ref($settings) eq 'HASH') {
 3322:         foreach my $item (keys(%{$settings})) {
 3323:             if (ref($settings->{$item}) eq 'HASH') {
 3324:                 my $num = $settings->{$item}{'order'};
 3325:                 $ordered{$num} = $item;
 3326:             }
 3327:         }
 3328:         $total = scalar(keys(%{$settings}));
 3329:     } else {
 3330:         %ordered = (
 3331:                        0 => 'proctorio',
 3332:                        1 => 'examity',
 3333:                    );
 3334:         $total = 2; 
 3335:     }
 3336:     my @jsarray = ();
 3337:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3338:         push(@jsarray,$ordered{$item});
 3339:     }
 3340:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 3341:     return <<"ENDSCRIPT";
 3342: <script type="text/javascript">
 3343: // <![CDATA[
 3344: function reorderProctoring(form,item) {
 3345:     var changedVal;
 3346: $jstext
 3347:     var maxh = $total;
 3348:     var current = new Array;
 3349:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3350:     for (var i=0; i<proctors.length; i++) {
 3351:         var elementName = 'proctoring_pos_'+proctors[i];
 3352:         if (elementName != item) {
 3353:             if (form.elements[elementName]) {
 3354:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3355:                 current[currVal] = elementName;
 3356:             }
 3357:         }
 3358:     }
 3359:     var oldVal;
 3360:     for (var j=0; j<maxh; j++) {
 3361:         if (current[j] == undefined) {
 3362:             oldVal = j;
 3363:         }
 3364:     }
 3365:     if (oldVal < changedVal) {
 3366:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3367:            var elementName = current[k];
 3368:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3369:         }
 3370:     } else {
 3371:         for (var k=changedVal; k<oldVal; k++) {
 3372:             var elementName = current[k];
 3373:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3374:         }
 3375:     }
 3376:     return;
 3377: }
 3378: 
 3379: function toggleProctoring(form,item) {
 3380:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3381:     if (fieldsets.length) {
 3382:         var radioname = 'proctoring_available_'+item;
 3383:         var num = form.elements[radioname].length;
 3384:         if (num) {
 3385:             var setvis = '';
 3386:             for (var i=0; i<num; i++) {
 3387:                 if (form.elements[radioname][i].checked) {
 3388:                     if (form.elements[radioname][i].value == '1') {
 3389:                        setvis = 1;
 3390:                        break;
 3391:                     }
 3392:                 }
 3393:             }
 3394:             for (var j=0; j<fieldsets.length; j++) {
 3395:                 if (setvis) {
 3396:                     fieldsets[j].style.display = 'block';
 3397:                 } else {
 3398:                     fieldsets[j].style.display = 'none';
 3399:                 }
 3400:             }
 3401:         }
 3402:     }
 3403:     return;
 3404: }
 3405: 
 3406: // ]]>
 3407: </script>
 3408: 
 3409: ENDSCRIPT
 3410: }
 3411: 
 3412: 
 3413: sub lti_javascript {
 3414:     my ($dom,$settings) = @_;
 3415:     my $togglejs = &lti_toggle_js($dom);
 3416:     unless (ref($settings) eq 'HASH') {
 3417:         return $togglejs;
 3418:     }
 3419:     my (%ordered,$total,%jstext);
 3420:     $total = scalar(keys(%{$settings}));
 3421:     foreach my $item (keys(%{$settings})) {
 3422:         if (ref($settings->{$item}) eq 'HASH') {
 3423:             my $num = $settings->{$item}{'order'};
 3424:             if ($num eq '') {
 3425:                 $num = $total - 1;
 3426:             }
 3427:             $ordered{$num} = $item;
 3428:         }
 3429:     }
 3430:     my @jsarray = ();
 3431:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3432:         push(@jsarray,$ordered{$item});
 3433:     }
 3434:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3435:     my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
 3436:     return <<"ENDSCRIPT";
 3437: <script type="text/javascript">
 3438: // <![CDATA[
 3439: function reorderLTI(form,item) {
 3440:     var changedVal;
 3441: $jstext
 3442:     var newpos = 'lti_pos_add';
 3443:     var maxh = 1 + $total;
 3444:     var current = new Array;
 3445:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3446:     if (item == newpos) {
 3447:         changedVal = newitemVal;
 3448:     } else {
 3449:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3450:         current[newitemVal] = newpos;
 3451:     }
 3452:     for (var i=0; i<lti.length; i++) {
 3453:         var elementName = 'lti_pos_'+lti[i];
 3454:         if (elementName != item) {
 3455:             if (form.elements[elementName]) {
 3456:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3457:                 current[currVal] = elementName;
 3458:             }
 3459:         }
 3460:     }
 3461:     var oldVal;
 3462:     for (var j=0; j<maxh; j++) {
 3463:         if (current[j] == undefined) {
 3464:             oldVal = j;
 3465:         }
 3466:     }
 3467:     if (oldVal < changedVal) {
 3468:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3469:            var elementName = current[k];
 3470:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3471:         }
 3472:     } else {
 3473:         for (var k=changedVal; k<oldVal; k++) {
 3474:             var elementName = current[k];
 3475:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3476:         }
 3477:     }
 3478:     return;
 3479: }
 3480: 
 3481: $linkprot_js
 3482: 
 3483: // ]]>
 3484: </script>
 3485: 
 3486: $togglejs
 3487: 
 3488: ENDSCRIPT
 3489: }
 3490: 
 3491: sub lti_toggle_js {
 3492:     my ($dom) = @_;
 3493:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3494:                             localauth => 'Local auth argument',
 3495:                             krb       => 'Kerberos domain',
 3496:                          );
 3497:     my $crsincalert = &mt('"User\'s identity sent" needs to be set to "Yes" first,[_1] before setting "Course\'s identity sent" to "Yes"',"\n");
 3498:     &js_escape(\$crsincalert);
 3499:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3500:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3501:     my $course_servers = "'".join("','",keys(%servers))."'";
 3502: 
 3503:     return <<"ENDSCRIPT";
 3504: <script type="text/javascript">
 3505: // <![CDATA[
 3506: 
 3507: function toggleLTI(form,setting,item) {
 3508:     if ((setting == 'requser') || (setting == 'crsinc')) {
 3509:         var usrfieldsets = document.getElementsByClassName('ltioption_usr_'+item);
 3510:         var setvis = '';
 3511:         var radioname = 'lti_requser_'+item;
 3512:         var num = form.elements[radioname].length;
 3513:         if (num) {
 3514:             for (var i=0; i<num; i++) {
 3515:                 if (form.elements[radioname][i].checked) {
 3516:                     if (form.elements[radioname][i].value == '1') {
 3517:                         setvis = 1;
 3518:                         break;
 3519:                     }
 3520:                 }
 3521:             }
 3522:         }
 3523:         if (usrfieldsets.length) {
 3524:             for (var j=0; j<usrfieldsets.length; j++) {
 3525:                 if (setvis) {
 3526:                     usrfieldsets[j].style.display = 'block';
 3527:                 } else {
 3528:                     usrfieldsets[j].style.display = 'none';
 3529:                 }
 3530:             }
 3531:         }
 3532:         var crsfieldsets = document.getElementsByClassName('ltioption_crs_'+item);
 3533:         if (crsfieldsets.length) {
 3534:             radioname = 'lti_crsinc_'+item;
 3535:             var num = form.elements[radioname].length;
 3536:             if (num) {
 3537:                 var crsvis = '';
 3538:                 for (var i=0; i<num; i++) {
 3539:                     if (form.elements[radioname][i].checked) {
 3540:                         if (form.elements[radioname][i].value == '1') {
 3541:                             if (setvis == '') {
 3542:                                 if (setting == 'crsinc'){
 3543:                                     alert("$crsincalert");
 3544:                                     form.elements[radioname][0].checked = true;
 3545:                                 }
 3546:                             } else {
 3547:                                 crsvis = 1;
 3548:                             }
 3549:                             break;
 3550:                         }
 3551:                     }
 3552:                 }
 3553:                 setvis = crsvis;
 3554:             }
 3555:             for (var j=0; j<crsfieldsets.length; j++) {
 3556:                 if (setvis) {
 3557:                     crsfieldsets[j].style.display = 'block';
 3558:                 } else {
 3559:                     crsfieldsets[j].style.display = 'none';
 3560:                 }
 3561:             }
 3562:         }
 3563:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3564:         var radioname = '';
 3565:         var divid = '';
 3566:         if (setting == 'user') {
 3567:             radioname = 'lti_mapuser_'+item;
 3568:             divid = 'lti_userfield_'+item;
 3569:         } else if (setting == 'crs') {
 3570:             radioname = 'lti_mapcrs_'+item;
 3571:             divid = 'lti_crsfield_'+item;
 3572:         } else if (setting == 'callback') {
 3573:             radioname = 'lti_callback_'+item;
 3574:             divid = 'lti_callbackfield_'+item;
 3575:         } else {
 3576:             radioname = 'lti_passback_'+item;
 3577:             divid =  'lti_passback_'+item;
 3578:         }
 3579:         var num = form.elements[radioname].length;
 3580:         if (num) {
 3581:             var setvis = '';
 3582:             for (var i=0; i<num; i++) {
 3583:                if (form.elements[radioname][i].checked) {
 3584:                    if ((setting == 'passback') || (setting == 'callback')) {
 3585:                        if (form.elements[radioname][i].value == '1') {
 3586:                            if (document.getElementById(divid)) {
 3587:                                document.getElementById(divid).style.display = 'inline-block';
 3588:                            }
 3589:                            setvis = 1;
 3590:                            break;
 3591:                        }
 3592:                    } else {
 3593:                        if (form.elements[radioname][i].value == 'other') {
 3594:                            if (document.getElementById(divid)) {
 3595:                                document.getElementById(divid).style.display = 'inline-block';
 3596:                            }
 3597:                            setvis = 1;
 3598:                            break;
 3599:                        }
 3600:                    }
 3601:                } 
 3602:             }
 3603:             if (!setvis) {
 3604:                 if (document.getElementById(divid)) {
 3605:                     document.getElementById(divid).style.display = 'none';
 3606:                 }
 3607:             }
 3608:         }
 3609:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3610:         var numsec = form.elements['lti_crssec_'+item].length;
 3611:         if (numsec) {
 3612:             var setvis = '';
 3613:             for (var i=0; i<numsec; i++) {
 3614:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3615:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3616:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3617:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3618:                             setvis = 1;
 3619:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3620:                             if (numsrcsec) {
 3621:                                 var setsrcvis = '';
 3622:                                 for (var j=0; j<numsrcsec; j++) {
 3623:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3624:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3625:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3626:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3627:                                                 setsrcvis = 1;
 3628:                                             }
 3629:                                         }
 3630:                                     }
 3631:                                 }
 3632:                                 if (!setsrcvis) {
 3633:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3634:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3635:                                     }
 3636:                                 }
 3637:                             }
 3638:                         }
 3639:                     }
 3640:                 }
 3641:             }
 3642:             if (!setvis) {
 3643:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3644:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3645:                 }
 3646:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3647:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3648:                 }
 3649:             }
 3650:         }
 3651:     } else if (setting == 'lcauth') {
 3652:         var numauth = form.elements['lti_lcauth_'+item].length;
 3653:         if (numauth) {
 3654:             for (var i=0; i<numauth; i++) {
 3655:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3656:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3657:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3658:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3659:                         } else {
 3660:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3661:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3662:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3663:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3664:                                 } else {
 3665:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3666:                                 }
 3667:                             }
 3668:                         }
 3669:                     }
 3670:                 }
 3671:             }
 3672:         }
 3673:     } else if (setting == 'lcmenu') {
 3674:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3675:         var divid = 'lti_menufield_'+item;
 3676:         var setvis = '';
 3677:         for (var i=0; i<menus.length; i++) {
 3678:             var radioname = menus[i];  
 3679:             var num = form.elements[radioname].length;
 3680:             if (num) {
 3681:                 for (var j=0; j<num; j++) {
 3682:                     if (form.elements[radioname][j].checked) {
 3683:                         if (form.elements[radioname][j].value == '1') {
 3684:                             if (document.getElementById(divid)) {
 3685:                                 document.getElementById(divid).style.display = 'inline-block';
 3686:                             }
 3687:                             setvis = 1;
 3688:                             break;
 3689:                         }
 3690:                     }
 3691:                 }
 3692:             }
 3693:             if (setvis == 1) {
 3694:                 break;
 3695:             }
 3696:         }
 3697:         if (!setvis) {
 3698:             if (document.getElementById(divid)) {
 3699:                 document.getElementById(divid).style.display = 'none';
 3700:             }
 3701:         }
 3702:     }
 3703:     return;
 3704: }
 3705: 
 3706: function toggleLTIEncKey(form) {
 3707:     var shownhosts = new Array();
 3708:     var hiddenhosts = new Array();
 3709:     var forcourse = new Array($course_servers);
 3710:     var fromdomain = '$primary';
 3711:     var crsradio = form.elements['ltisec_crslinkprot'];
 3712:     if (crsradio.length) {
 3713:         for (var i=0; i<crsradio.length; i++) {
 3714:             if (crsradio[i].checked) {
 3715:                 if (crsradio[i].value == 1) {
 3716:                     if (forcourse.length > 0) {
 3717:                         for (var j=0; j<forcourse.length; j++) {
 3718:                             if (!shownhosts.includes(forcourse[j])) {
 3719:                                 shownhosts.push(forcourse[j]);
 3720:                             }
 3721:                         }
 3722:                     }
 3723:                 } else {
 3724:                     if (forcourse.length > 0) {
 3725:                         for (var j=0; j<forcourse.length; j++) {
 3726:                             if (!hiddenhosts.includes(forcourse[j])) { 
 3727:                                 hiddenhosts.push(forcourse[j]);
 3728:                             }
 3729:                         }
 3730:                     } 
 3731:                 }
 3732:             }
 3733:         }
 3734:     }
 3735:     var domradio = form.elements['ltisec_domlinkprot'];
 3736:     if (domradio.length) {
 3737:         for (var i=0; i<domradio.length; i++) {
 3738:             if (domradio[i].checked) {
 3739:                 if (domradio[i].value == 1) {
 3740:                     if (!shownhosts.includes(fromdomain)) { 
 3741:                         shownhosts.push(fromdomain);
 3742:                     }
 3743:                 } else {
 3744:                     if (!hiddenhosts.includes(fromdomain)) {
 3745:                         hiddenhosts.push(fromdomain);
 3746:                     }
 3747:                 }
 3748:             }
 3749:         }
 3750:     }
 3751:     var consumersradio = form.elements['ltisec_consumers'];
 3752:     if (consumersradio.length) {
 3753:         for (var i=0; i<consumersradio.length; i++) {
 3754:             if (consumersradio[i].checked) {
 3755:                 if (consumersradio[i].value == 1) {
 3756:                     if (!shownhosts.includes(fromdomain)) {     
 3757:                         shownhosts.push(fromdomain);
 3758:                     }
 3759:                 } else {
 3760:                     if (!hiddenhosts.includes(fromdomain)) {
 3761:                         hiddenhosts.push(fromdomain);
 3762:                     }
 3763:                 }
 3764:             }
 3765:         }
 3766:     }
 3767:     if (shownhosts.length > 0) {
 3768:         for (var i=0; i<shownhosts.length; i++) {
 3769:             if (document.getElementById('ltisec_info_'+shownhosts[i])) {
 3770:                 document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';                 
 3771:             }
 3772:         }
 3773:         if (document.getElementById('ltisec_noprivkey')) {
 3774:             document.getElementById('ltisec_noprivkey').style.display = 'none';
 3775:         }
 3776:     } else {
 3777:         if (document.getElementById('ltisec_noprivkey')) {
 3778:             document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
 3779:         }
 3780:     }
 3781:     if (hiddenhosts.length > 0) {
 3782:         for (var i=0; i<hiddenhosts.length; i++) {
 3783:             if (!shownhosts.includes(hiddenhosts[i])) {
 3784:                 if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
 3785:                     document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
 3786:                 }
 3787:             }
 3788:         }
 3789:     }
 3790:     return;
 3791: }
 3792: 
 3793: function togglePrivKey(form,hostid) {
 3794:     var radioname = '';
 3795:     var currdivid = '';
 3796:     var newdivid = '';
 3797:     if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
 3798:         (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
 3799:         currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
 3800:         newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
 3801:         radioname = form.elements['ltisec_changeprivkey_'+hostid];
 3802:         if (radioname) {
 3803:             if (radioname.length > 0) {
 3804:                 var setvis;
 3805:                 for (var i=0; i<radioname.length; i++) {
 3806:                     if (radioname[i].checked == true) {
 3807:                         if (radioname[i].value == 1) {
 3808:                             newdivid.style.display = 'inline-block';
 3809:                             currdivid.style.display = 'none';
 3810:                             setvis = 1;
 3811:                         }
 3812:                         break;
 3813:                     }
 3814:                 }
 3815:                 if (!setvis) {
 3816:                     newdivid.style.display = 'none';
 3817:                     currdivid.style.display = 'inline-block';
 3818:                 }
 3819:             }
 3820:         }
 3821:     }
 3822: }
 3823: 
 3824: // ]]>
 3825: </script>
 3826: 
 3827: ENDSCRIPT
 3828: }
 3829: 
 3830: sub autoupdate_javascript {
 3831:     return <<"ENDSCRIPT";
 3832: <script type="text/javascript">
 3833: // <![CDATA[
 3834: function toggleLastActiveDays(form) {
 3835:     var radioname = 'lastactive';
 3836:     var divid = 'lastactive_div';
 3837:     var num = form.elements[radioname].length;
 3838:     if (num) {
 3839:         var setvis = '';
 3840:         for (var i=0; i<num; i++) {
 3841:             if (form.elements[radioname][i].checked) {
 3842:                 if (form.elements[radioname][i].value == '1') {
 3843:                     if (document.getElementById(divid)) {
 3844:                         document.getElementById(divid).style.display = 'inline-block';
 3845:                     }
 3846:                     setvis = 1;
 3847:                 }
 3848:                 break;
 3849:             }
 3850:         }
 3851:         if (!setvis) {
 3852:             if (document.getElementById(divid)) {
 3853:                 document.getElementById(divid).style.display = 'none';
 3854:             }
 3855:         }
 3856:     }
 3857:     return;
 3858: }
 3859: // ]]>
 3860: </script>
 3861: 
 3862: ENDSCRIPT
 3863: }
 3864: 
 3865: sub autoenroll_javascript {
 3866:     return <<"ENDSCRIPT";
 3867: <script type="text/javascript">
 3868: // <![CDATA[
 3869: function toggleFailsafe(form) {
 3870:     var radioname = 'autoenroll_failsafe';
 3871:     var divid = 'autoenroll_failsafe_div';
 3872:     var num = form.elements[radioname].length;
 3873:     if (num) {
 3874:         var setvis = '';
 3875:         for (var i=0; i<num; i++) {
 3876:             if (form.elements[radioname][i].checked) {
 3877:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3878:                     if (document.getElementById(divid)) {
 3879:                         document.getElementById(divid).style.display = 'inline-block';
 3880:                     }
 3881:                     setvis = 1;
 3882:                 }
 3883:                 break;
 3884:             }
 3885:         }
 3886:         if (!setvis) {
 3887:             if (document.getElementById(divid)) {
 3888:                 document.getElementById(divid).style.display = 'none';
 3889:             }
 3890:         }
 3891:     }
 3892:     return;
 3893: }
 3894: // ]]>
 3895: </script>
 3896: 
 3897: ENDSCRIPT
 3898: }
 3899: 
 3900: sub saml_javascript {
 3901:     return <<"ENDSCRIPT";
 3902: <script type="text/javascript">
 3903: // <![CDATA[
 3904: function toggleSamlOptions(form,hostid) { 
 3905:     var radioname = 'saml_'+hostid;
 3906:     var tablecellon = 'samloptionson_'+hostid;
 3907:     var tablecelloff = 'samloptionsoff_'+hostid;
 3908:     var num = form.elements[radioname].length;
 3909:     if (num) {
 3910:         var setvis = ''; 
 3911:         for (var i=0; i<num; i++) {
 3912:             if (form.elements[radioname][i].checked) {
 3913:                 if (form.elements[radioname][i].value == '1') { 
 3914:                     if (document.getElementById(tablecellon)) {
 3915:                         document.getElementById(tablecellon).style.display='';
 3916:                     }
 3917:                     if (document.getElementById(tablecelloff)) {
 3918:                         document.getElementById(tablecelloff).style.display='none';
 3919:                     }
 3920:                     setvis = 1;
 3921:                 }
 3922:                 break;
 3923:             }
 3924:         }
 3925:         if (!setvis) {
 3926:             if (document.getElementById(tablecellon)) {
 3927:                 document.getElementById(tablecellon).style.display='none';
 3928:             }
 3929:             if (document.getElementById(tablecelloff)) {
 3930:                 document.getElementById(tablecelloff).style.display='';
 3931:             }
 3932:         }
 3933:     }
 3934:     return;
 3935: }
 3936: // ]]>
 3937: </script>
 3938: 
 3939: ENDSCRIPT
 3940: }
 3941: 
 3942: sub ipaccess_javascript {
 3943:     my ($settings) = @_;
 3944:     my (%ordered,$total,%jstext);
 3945:     $total = 0;
 3946:     if (ref($settings) eq 'HASH') {
 3947:         foreach my $item (keys(%{$settings})) {
 3948:             if (ref($settings->{$item}) eq 'HASH') {
 3949:                 my $num = $settings->{$item}{'order'};
 3950:                 $ordered{$num} = $item;
 3951:             }
 3952:         }
 3953:         $total = scalar(keys(%{$settings}));
 3954:     }
 3955:     my @jsarray = ();
 3956:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3957:         push(@jsarray,$ordered{$item});
 3958:     }
 3959:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3960:     return <<"ENDSCRIPT";
 3961: <script type="text/javascript">
 3962: // <![CDATA[
 3963: function reorderIPaccess(form,item) {
 3964:     var changedVal;
 3965: $jstext
 3966:     var newpos = 'ipaccess_pos_add';
 3967:     var maxh = 1 + $total;
 3968:     var current = new Array;
 3969:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3970:     if (item == newpos) {
 3971:         changedVal = newitemVal;
 3972:     } else {
 3973:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3974:         current[newitemVal] = newpos;
 3975:     }
 3976:     for (var i=0; i<ipaccess.length; i++) {
 3977:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3978:         if (elementName != item) {
 3979:             if (form.elements[elementName]) {
 3980:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3981:                 current[currVal] = elementName;
 3982:             }
 3983:         }
 3984:     }
 3985:     var oldVal;
 3986:     for (var j=0; j<maxh; j++) {
 3987:         if (current[j] == undefined) {
 3988:             oldVal = j;
 3989:         }
 3990:     }
 3991:     if (oldVal < changedVal) {
 3992:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3993:            var elementName = current[k];
 3994:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3995:         }
 3996:     } else {
 3997:         for (var k=changedVal; k<oldVal; k++) {
 3998:             var elementName = current[k];
 3999:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4000:         }
 4001:     }
 4002:     return;
 4003: }
 4004: // ]]>
 4005: </script>
 4006: 
 4007: ENDSCRIPT
 4008: }
 4009: 
 4010: sub print_autoenroll {
 4011:     my ($dom,$settings,$rowtotal) = @_;
 4012:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 4013:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 4014:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 4015:     $failsafesty = 'none';
 4016:     %failsafechecked = (
 4017:         off => ' checked="checked"',
 4018:     );
 4019:     if (ref($settings) eq 'HASH') {
 4020:         if (exists($settings->{'run'})) {
 4021:             if ($settings->{'run'} eq '0') {
 4022:                 $runoff = ' checked="checked" ';
 4023:                 $runon = ' ';
 4024:             } else {
 4025:                 $runon = ' checked="checked" ';
 4026:                 $runoff = ' ';
 4027:             }
 4028:         } else {
 4029:             if ($autorun) {
 4030:                 $runon = ' checked="checked" ';
 4031:                 $runoff = ' ';
 4032:             } else {
 4033:                 $runoff = ' checked="checked" ';
 4034:                 $runon = ' ';
 4035:             }
 4036:         }
 4037:         if (exists($settings->{'co-owners'})) {
 4038:             if ($settings->{'co-owners'} eq '0') {
 4039:                 $coownersoff = ' checked="checked" ';
 4040:                 $coownerson = ' ';
 4041:             } else {
 4042:                 $coownerson = ' checked="checked" ';
 4043:                 $coownersoff = ' ';
 4044:             }
 4045:         } else {
 4046:             $coownersoff = ' checked="checked" ';
 4047:             $coownerson = ' ';
 4048:         }
 4049:         if (exists($settings->{'sender_domain'})) {
 4050:             $defdom = $settings->{'sender_domain'};
 4051:         }
 4052:         if (exists($settings->{'failsafe'})) {
 4053:             $failsafe = $settings->{'failsafe'};
 4054:             if ($failsafe eq 'zero') {
 4055:                 $failsafechecked{'zero'} = ' checked="checked"';
 4056:                 $failsafechecked{'off'} = '';
 4057:                 $failsafesty = 'inline-block';
 4058:             } elsif ($failsafe eq 'any') {
 4059:                 $failsafechecked{'any'} = ' checked="checked"';
 4060:                 $failsafechecked{'off'} = '';
 4061:             }
 4062:             $autofailsafe = $settings->{'autofailsafe'};
 4063:         } elsif (exists($settings->{'autofailsafe'})) {
 4064:             $autofailsafe = $settings->{'autofailsafe'};
 4065:             if ($autofailsafe ne '') {
 4066:                 $failsafechecked{'zero'} = ' checked="checked"';
 4067:                 $failsafe = 'zero';
 4068:                 $failsafechecked{'off'} = '';
 4069:             }
 4070:         }
 4071:     } else {
 4072:         if ($autorun) {
 4073:             $runon = ' checked="checked" ';
 4074:             $runoff = ' ';
 4075:         } else {
 4076:             $runoff = ' checked="checked" ';
 4077:             $runon = ' ';
 4078:         }
 4079:     }
 4080:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 4081:     my $notif_sender;
 4082:     if (ref($settings) eq 'HASH') {
 4083:         $notif_sender = $settings->{'sender_uname'};
 4084:     }
 4085:     my $datatable='<tr class="LC_odd_row">'.
 4086:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 4087:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4088:                   '<input type="radio" name="autoenroll_run"'.
 4089:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4090:                   '<label><input type="radio" name="autoenroll_run"'.
 4091:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4092:                   '</tr><tr>'.
 4093:                   '<td>'.&mt('Notification messages - sender').
 4094:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 4095:                   &mt('username').':&nbsp;'.
 4096:                   '<input type="text" name="sender_uname" value="'.
 4097:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 4098:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 4099:                   '<tr class="LC_odd_row">'.
 4100:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 4101:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4102:                   '<input type="radio" name="autoassign_coowners"'.
 4103:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4104:                   '<label><input type="radio" name="autoassign_coowners"'.
 4105:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4106:                   '</tr><tr>'.
 4107:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 4108:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 4109:                   '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="off" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'off'}.' />'.&mt('Not in use').'</label></span>&nbsp;&nbsp;&nbsp; '.
 4110:                   '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="zero" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'zero'}.' />'.&mt('Retrieved section enrollment is zero').'</label></span><br />'.
 4111:                   '<span class="LC_nobreak"><label><input type="radio" name="autoenroll_failsafe" value="any" onclick="toggleFailsafe(this.form)"'.$failsafechecked{'any'}.' />'.&mt('Retrieved section enrollment is zero or greater').'</label></span>'.
 4112:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 4113:                   '<span class="LC_nobreak">'.
 4114:                   &mt('Threshold for number of students in section to drop: [_1]',
 4115:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 4116:                   '</span></div></td></tr>';
 4117:     $$rowtotal += 4;
 4118:     return $datatable;
 4119: }
 4120: 
 4121: sub print_autoupdate {
 4122:     my ($position,$dom,$settings,$rowtotal) = @_;
 4123:     my ($enable,$datatable);
 4124:     if ($position eq 'top') {
 4125:         my %choices = &Apache::lonlocal::texthash (
 4126:                           run        => 'Auto-update active?',
 4127:                           classlists => 'Update information in classlists?',
 4128:                           unexpired  => 'Skip updates for users without active or future roles?',
 4129:                           lastactive => 'Skip updates for inactive users?',
 4130:         );
 4131:         my $itemcount = 0;
 4132:         my $updateon = ' ';
 4133:         my $updateoff = ' checked="checked" ';
 4134:         if (ref($settings) eq 'HASH') {
 4135:             if ($settings->{'run'} eq '1') {
 4136:                 $updateon = $updateoff;
 4137:                 $updateoff = ' ';
 4138:             }
 4139:         }
 4140:         $enable = '<tr class="LC_odd_row">'.
 4141:                   '<td>'.$choices{'run'}.'</td>'.
 4142:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4143:                   '<input type="radio" name="autoupdate_run"'.
 4144:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 4145:                   '<label><input type="radio" name="autoupdate_run"'.
 4146:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 4147:                   '</tr>';
 4148:         my @toggles = ('classlists','unexpired');
 4149:         my %defaultchecked = ('classlists' => 'off',
 4150:                               'unexpired'  => 'off'
 4151:                               );
 4152:         $$rowtotal ++;
 4153:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4154:                                                      \%choices,$itemcount,'','','left','no');
 4155:         $datatable = $enable.$datatable;
 4156:         $$rowtotal += $itemcount;
 4157:         my $lastactiveon = ' ';
 4158:         my $lastactiveoff = ' checked="checked" ';
 4159:         my $lastactivestyle = 'none';
 4160:         my $lastactivedays;
 4161:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 4162:         if (ref($settings) eq 'HASH') {
 4163:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 4164:                 $lastactiveon = $lastactiveoff;
 4165:                 $lastactiveoff = ' ';
 4166:                 $lastactivestyle = 'inline-block';
 4167:                 $lastactivedays = $settings->{'lastactive'};
 4168:             }
 4169:         }
 4170:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4171:         $datatable .= '<tr'.$css_class.'>'.
 4172:                       '<td>'.$choices{'lastactive'}.'</td>'.
 4173:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4174:                       '<input type="radio" name="lastactive"'.
 4175:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4176:                       '&nbsp;<label>'.
 4177:                       '<input type="radio" name="lastactive"'.
 4178:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 4179:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 4180:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 4181:                           '<input type="text" size="5" name="lastactivedays" value="'.
 4182:                           $lastactivedays.'" />').
 4183:                       '</span></td>'.
 4184:                       '</tr>';
 4185:         $$rowtotal ++;
 4186:     } elsif ($position eq 'middle') {
 4187:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4188:         my $numinrow = 3;
 4189:         my $locknamesettings;
 4190:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 4191:                                      $dom,$numinrow,$othertitle,
 4192:                                     'lockablenames',$rowtotal);
 4193:         $$rowtotal ++;
 4194:     } else {
 4195:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4196:         my @fields = ('lastname','firstname','middlename','generation',
 4197:                       'permanentemail','id');
 4198:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4199:         my $numrows = 0;
 4200:         if (ref($types) eq 'ARRAY') {
 4201:             if (@{$types} > 0) {
 4202:                 $datatable = 
 4203:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 4204:                                          \@fields,$types,\$numrows);
 4205:                     $$rowtotal += @{$types}; 
 4206:             }
 4207:         }
 4208:         $datatable .= 
 4209:             &usertype_update_row($settings,{'default' => $othertitle},
 4210:                                  \%fieldtitles,\@fields,['default'],
 4211:                                  \$numrows);
 4212:         $$rowtotal ++;     
 4213:     }
 4214:     return $datatable;
 4215: }
 4216: 
 4217: sub print_autocreate {
 4218:     my ($dom,$settings,$rowtotal) = @_;
 4219:     my (%createon,%createoff,%currhash);
 4220:     my @types = ('xml','req');
 4221:     if (ref($settings) eq 'HASH') {
 4222:         foreach my $item (@types) {
 4223:             $createoff{$item} = ' checked="checked" ';
 4224:             $createon{$item} = ' ';
 4225:             if (exists($settings->{$item})) {
 4226:                 if ($settings->{$item}) {
 4227:                     $createon{$item} = ' checked="checked" ';
 4228:                     $createoff{$item} = ' ';
 4229:                 }
 4230:             }
 4231:         }
 4232:         if ($settings->{'xmldc'} ne '') {
 4233:             $currhash{$settings->{'xmldc'}} = 1;
 4234:         }
 4235:     } else {
 4236:         foreach my $item (@types) {
 4237:             $createoff{$item} = ' checked="checked" ';
 4238:             $createon{$item} = ' ';
 4239:         }
 4240:     }
 4241:     $$rowtotal += 2;
 4242:     my $numinrow = 2;
 4243:     my $datatable='<tr class="LC_odd_row">'.
 4244:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 4245:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4246:                   '<input type="radio" name="autocreate_xml"'.
 4247:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4248:                   '<label><input type="radio" name="autocreate_xml"'.
 4249:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 4250:                   '</td></tr><tr>'.
 4251:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 4252:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4253:                   '<input type="radio" name="autocreate_req"'.
 4254:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4255:                   '<label><input type="radio" name="autocreate_req"'.
 4256:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 4257:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 4258:                                                    'autocreate_xmldc',%currhash);
 4259:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 4260:     if ($numdc > 1) {
 4261:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 4262:                       '</td><td class="LC_left_item">';
 4263:     } else {
 4264:         $datatable .= &mt('Course creation processed as:').
 4265:                       '</td><td class="LC_right_item">';
 4266:     }
 4267:     $datatable .= $dctable.'</td></tr>';
 4268:     $$rowtotal += $rows;
 4269:     return $datatable;
 4270: }
 4271: 
 4272: sub print_directorysrch {
 4273:     my ($position,$dom,$settings,$rowtotal) = @_;
 4274:     my $datatable;
 4275:     if ($position eq 'top') {
 4276:         my $instsrchon = ' ';
 4277:         my $instsrchoff = ' checked="checked" ';
 4278:         my ($exacton,$containson,$beginson);
 4279:         my $instlocalon = ' ';
 4280:         my $instlocaloff = ' checked="checked" ';
 4281:         if (ref($settings) eq 'HASH') {
 4282:             if ($settings->{'available'} eq '1') {
 4283:                 $instsrchon = $instsrchoff;
 4284:                 $instsrchoff = ' ';
 4285:             }
 4286:             if ($settings->{'localonly'} eq '1') {
 4287:                 $instlocalon = $instlocaloff;
 4288:                 $instlocaloff = ' ';
 4289:             }
 4290:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 4291:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 4292:                     if ($type eq 'exact') {
 4293:                         $exacton = ' checked="checked" ';
 4294:                     } elsif ($type eq 'contains') {
 4295:                         $containson = ' checked="checked" ';
 4296:                     } elsif ($type eq 'begins') {
 4297:                         $beginson = ' checked="checked" ';
 4298:                     }
 4299:                 }
 4300:             } else {
 4301:                 if ($settings->{'searchtypes'} eq 'exact') {
 4302:                     $exacton = ' checked="checked" ';
 4303:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 4304:                     $containson = ' checked="checked" ';
 4305:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 4306:                     $exacton = ' checked="checked" ';
 4307:                     $containson = ' checked="checked" ';
 4308:                 }
 4309:             }
 4310:         }
 4311:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 4312:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4313: 
 4314:         my $numinrow = 4;
 4315:         my $cansrchrow = 0;
 4316:         $datatable='<tr class="LC_odd_row">'.
 4317:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 4318:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4319:                    '<input type="radio" name="dirsrch_available"'.
 4320:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4321:                    '<label><input type="radio" name="dirsrch_available"'.
 4322:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4323:                    '</tr><tr>'.
 4324:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 4325:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4326:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 4327:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4328:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 4329:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4330:                    '</tr>';
 4331:         $$rowtotal += 2;
 4332:         if (ref($usertypes) eq 'HASH') {
 4333:             if (keys(%{$usertypes}) > 0) {
 4334:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4335:                                              $numinrow,$othertitle,'cansearch',
 4336:                                              $rowtotal);
 4337:                 $cansrchrow = 1;
 4338:             }
 4339:         }
 4340:         if ($cansrchrow) {
 4341:             $$rowtotal ++;
 4342:             $datatable .= '<tr>';
 4343:         } else {
 4344:             $datatable .= '<tr class="LC_odd_row">';
 4345:         }
 4346:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 4347:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 4348:         foreach my $title (@{$titleorder}) {
 4349:             if (defined($searchtitles->{$title})) {
 4350:                 my $check = ' ';
 4351:                 if (ref($settings) eq 'HASH') {
 4352:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 4353:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 4354:                             $check = ' checked="checked" ';
 4355:                         }
 4356:                     }
 4357:                 }
 4358:                 $datatable .= '<td class="LC_left_item">'.
 4359:                               '<span class="LC_nobreak"><label>'.
 4360:                               '<input type="checkbox" name="searchby" '.
 4361:                               'value="'.$title.'"'.$check.'/>'.
 4362:                               $searchtitles->{$title}.'</label></span></td>';
 4363:             }
 4364:         }
 4365:         $datatable .= '</tr></table></td></tr>';
 4366:         $$rowtotal ++;
 4367:         if ($cansrchrow) {
 4368:             $datatable .= '<tr class="LC_odd_row">';
 4369:         } else {
 4370:             $datatable .= '<tr>';
 4371:         }
 4372:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 4373:                       '<td class="LC_left_item" colspan="2">'.
 4374:                       '<span class="LC_nobreak"><label>'.
 4375:                       '<input type="checkbox" name="searchtypes" '.
 4376:                       $exacton.' value="exact" />'.&mt('Exact match').
 4377:                       '</label>&nbsp;'.
 4378:                       '<label><input type="checkbox" name="searchtypes" '.
 4379:                       $beginson.' value="begins" />'.&mt('Begins with').
 4380:                       '</label>&nbsp;'.
 4381:                       '<label><input type="checkbox" name="searchtypes" '.
 4382:                       $containson.' value="contains" />'.&mt('Contains').
 4383:                       '</label></span></td></tr>';
 4384:         $$rowtotal ++;
 4385:     } else {
 4386:         my $domsrchon = ' checked="checked" ';
 4387:         my $domsrchoff = ' ';
 4388:         my $domlocalon = ' ';
 4389:         my $domlocaloff = ' checked="checked" ';
 4390:         if (ref($settings) eq 'HASH') {
 4391:             if ($settings->{'lclocalonly'} eq '1') {
 4392:                 $domlocalon = $domlocaloff;
 4393:                 $domlocaloff = ' ';
 4394:             }
 4395:             if ($settings->{'lcavailable'} eq '0') {
 4396:                 $domsrchoff = $domsrchon;
 4397:                 $domsrchon = ' ';
 4398:             }
 4399:         }
 4400:         $datatable='<tr class="LC_odd_row">'.
 4401:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 4402:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4403:                       '<input type="radio" name="dirsrch_domavailable"'.
 4404:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4405:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 4406:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4407:                       '</tr><tr>'.
 4408:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 4409:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4410:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 4411:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4412:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 4413:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4414:                       '</tr>';
 4415:         $$rowtotal += 2;
 4416:     }
 4417:     return $datatable;
 4418: }
 4419: 
 4420: sub print_contacts {
 4421:     my ($position,$dom,$settings,$rowtotal) = @_;
 4422:     my $datatable;
 4423:     my @contacts = ('adminemail','supportemail');
 4424:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 4425:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 4426:     if ($position eq 'top') {
 4427:         if (ref($settings) eq 'HASH') {
 4428:             foreach my $item (@contacts) {
 4429:                 if (exists($settings->{$item})) {
 4430:                     $to{$item} = $settings->{$item};
 4431:                 }
 4432:             }
 4433:         }
 4434:     } elsif ($position eq 'middle') {
 4435:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 4436:                      'updatesmail','idconflictsmail','hostipmail');
 4437:         foreach my $type (@mailings) {
 4438:             $otheremails{$type} = '';
 4439:         }
 4440:     } elsif ($position eq 'lower') {
 4441:         if (ref($settings) eq 'HASH') {
 4442:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 4443:                 %lonstatus = %{$settings->{'lonstatus'}};
 4444:             }
 4445:         }
 4446:     } else {
 4447:         @mailings = ('helpdeskmail','otherdomsmail');
 4448:         foreach my $type (@mailings) {
 4449:             $otheremails{$type} = '';
 4450:         }
 4451:         $bccemails{'helpdeskmail'} = '';
 4452:         $bccemails{'otherdomsmail'} = '';
 4453:         $includestr{'helpdeskmail'} = '';
 4454:         $includestr{'otherdomsmail'} = '';
 4455:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 4456:     }
 4457:     if (ref($settings) eq 'HASH') {
 4458:         unless (($position eq 'top') || ($position eq 'lower')) {
 4459:             foreach my $type (@mailings) {
 4460:                 if (exists($settings->{$type})) {
 4461:                     if (ref($settings->{$type}) eq 'HASH') {
 4462:                         foreach my $item (@contacts) {
 4463:                             if ($settings->{$type}{$item}) {
 4464:                                 $checked{$type}{$item} = ' checked="checked" ';
 4465:                             }
 4466:                         }
 4467:                         $otheremails{$type} = $settings->{$type}{'others'};
 4468:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4469:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 4470:                             if ($settings->{$type}{'include'} ne '') {
 4471:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4472:                                 $includestr{$type} = &unescape($includestr{$type});
 4473:                             }
 4474:                         }
 4475:                     }
 4476:                 } elsif ($type eq 'lonstatusmail') {
 4477:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4478:                 }
 4479:             }
 4480:         }
 4481:         if ($position eq 'bottom') {
 4482:             foreach my $type (@mailings) {
 4483:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 4484:                 if ($settings->{$type}{'include'} ne '') {
 4485:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4486:                     $includestr{$type} = &unescape($includestr{$type});
 4487:                 }
 4488:             }
 4489:             if (ref($settings->{'helpform'}) eq 'HASH') {
 4490:                 if (ref($fields) eq 'ARRAY') {
 4491:                     foreach my $field (@{$fields}) {
 4492:                         $currfield{$field} = $settings->{'helpform'}{$field};
 4493:                     }
 4494:                 }
 4495:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 4496:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 4497:                 } else {
 4498:                     $maxsize = '1.0';
 4499:                 }
 4500:             } else {
 4501:                 if (ref($fields) eq 'ARRAY') {
 4502:                     foreach my $field (@{$fields}) {
 4503:                         $currfield{$field} = 'yes';
 4504:                     }
 4505:                 }
 4506:                 $maxsize = '1.0';
 4507:             }
 4508:         }
 4509:     } else {
 4510:         if ($position eq 'top') {
 4511:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 4512:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 4513:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 4514:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 4515:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4516:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 4517:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 4518:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 4519:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 4520:         } elsif ($position eq 'bottom') {
 4521:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 4522:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 4523:             if (ref($fields) eq 'ARRAY') {
 4524:                 foreach my $field (@{$fields}) {
 4525:                     $currfield{$field} = 'yes';
 4526:                 }
 4527:             }
 4528:             $maxsize = '1.0';
 4529:         }
 4530:     }
 4531:     my ($titles,$short_titles) = &contact_titles();
 4532:     my $rownum = 0;
 4533:     my $css_class;
 4534:     if ($position eq 'top') {
 4535:         foreach my $item (@contacts) {
 4536:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4537:             $datatable .= '<tr'.$css_class.'>'. 
 4538:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4539:                           '</span></td><td class="LC_right_item">'.
 4540:                           '<input type="text" name="'.$item.'" value="'.
 4541:                           $to{$item}.'" /></td></tr>';
 4542:             $rownum ++;
 4543:         }
 4544:     } elsif ($position eq 'bottom') {
 4545:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4546:         $datatable .= '<tr'.$css_class.'>'.
 4547:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4548:                       &mt('(e-mail, subject, and description always shown)').
 4549:                       '</td><td class="LC_left_item">';
 4550:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4551:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4552:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4553:             foreach my $field (@{$fields}) {
 4554:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4555:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4556:                     $datatable .= ' '.&mt('(logged-in users)');
 4557:                 }
 4558:                 $datatable .='</td><td>';
 4559:                 my $clickaction;
 4560:                 if ($field eq 'screenshot') {
 4561:                     $clickaction = ' onclick="screenshotSize(this);"';
 4562:                 }
 4563:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4564:                     foreach my $option (@{$possoptions->{$field}}) {
 4565:                         my $checked;
 4566:                         if ($currfield{$field} eq $option) {
 4567:                             $checked = ' checked="checked"';
 4568:                         }
 4569:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4570:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4571:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4572:                                       '</label></span>'.('&nbsp;'x2);
 4573:                     }
 4574:                 }
 4575:                 if ($field eq 'screenshot') {
 4576:                     my $display;
 4577:                     if ($currfield{$field} eq 'no') {
 4578:                         $display = ' style="display:none"';
 4579:                     }
 4580:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4581:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4582:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4583:                 }
 4584:                 $datatable .= '</td></tr>';
 4585:             }
 4586:             $datatable .= '</table>';
 4587:         }
 4588:         $datatable .= '</td></tr>'."\n";
 4589:         $rownum ++;
 4590:     }
 4591:     unless (($position eq 'top') || ($position eq 'lower')) {
 4592:         foreach my $type (@mailings) {
 4593:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4594:             $datatable .= '<tr'.$css_class.'>'.
 4595:                           '<td><span class="LC_nobreak">'.
 4596:                           $titles->{$type}.': </span></td>'.
 4597:                           '<td class="LC_left_item">';
 4598:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4599:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4600:             }
 4601:             $datatable .= '<span class="LC_nobreak">';
 4602:             foreach my $item (@contacts) {
 4603:                 $datatable .= '<label>'.
 4604:                               '<input type="checkbox" name="'.$type.'"'.
 4605:                               $checked{$type}{$item}.
 4606:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4607:                               '</label>&nbsp;';
 4608:             }
 4609:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4610:                           '<input type="text" name="'.$type.'_others" '.
 4611:                           'value="'.$otheremails{$type}.'"  />';
 4612:             my %locchecked;
 4613:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4614:                 foreach my $loc ('s','b') {
 4615:                     if ($includeloc{$type} eq $loc) {
 4616:                         $locchecked{$loc} = ' checked="checked"';
 4617:                         last;
 4618:                     }
 4619:                 }
 4620:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4621:                               '<input type="text" name="'.$type.'_bcc" '.
 4622:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4623:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4624:                               &mt('Text automatically added to e-mail:').' '.
 4625:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4626:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4627:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4628:                               ('&nbsp;'x2).
 4629:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4630:                               '</span></fieldset>';
 4631:             }
 4632:             $datatable .= '</td></tr>'."\n";
 4633:             $rownum ++;
 4634:         }
 4635:     }
 4636:     if ($position eq 'middle') {
 4637:         my %choices;
 4638:         my $corelink = &core_link_msu();
 4639:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4640:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4641:                                         $corelink);
 4642:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4643:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4644:         my %defaultchecked = ('reporterrors'  => 'on',
 4645:                               'reportupdates' => 'on',
 4646:                               'reportstatus'  => 'on');
 4647:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4648:                                                    \%choices,$rownum);
 4649:         $datatable .= $reports;
 4650:     } elsif ($position eq 'lower') {
 4651:         my (%current,%excluded,%weights);
 4652:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4653:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4654:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4655:         } else {
 4656:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4657:         }
 4658:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4659:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4660:         } else {
 4661:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4662:         }
 4663:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4664:             foreach my $type ('E','W','N','U') {
 4665:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4666:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4667:                 } else {
 4668:                     $weights{$type} = $defaults->{$type};
 4669:                 }
 4670:             }
 4671:         } else {
 4672:             foreach my $type ('E','W','N','U') {
 4673:                 $weights{$type} = $defaults->{$type};
 4674:             }
 4675:         }
 4676:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4677:             if (@{$lonstatus{'excluded'}} > 0) {
 4678:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4679:             }
 4680:         }
 4681:         foreach my $item ('errorthreshold','errorsysmail') { 
 4682:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4683:             $datatable .= '<tr'.$css_class.'>'.
 4684:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4685:                           $titles->{$item}.
 4686:                           '</span></td><td class="LC_left_item">'.
 4687:                           '<input type="text" name="'.$item.'" value="'.
 4688:                           $current{$item}.'" size="5" /></td></tr>';
 4689:             $rownum ++;
 4690:         }
 4691:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4692:         $datatable .= '<tr'.$css_class.'>'.
 4693:                       '<td class="LC_left_item">'.
 4694:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4695:                       '</span></td><td class="LC_left_item"><table><tr>';
 4696:         foreach my $type ('E','W','N','U') {
 4697:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4698:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4699:                           $weights{$type}.'" size="5" /></td>';
 4700:         }
 4701:         $datatable .= '</tr></table></tr>';
 4702:         $rownum ++;
 4703:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4704:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4705:                       $titles->{'errorexcluded'}.'</td>'.
 4706:                       '<td class="LC_left_item"><table>';
 4707:         my $numinrow = 4;
 4708:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4709:         for (my $i=0; $i<@ids; $i++) {
 4710:             my $rem = $i%($numinrow);
 4711:             if ($rem == 0) {
 4712:                 if ($i > 0) {
 4713:                     $datatable .= '</tr>';
 4714:                 }
 4715:                 $datatable .= '<tr>';
 4716:             }
 4717:             my $check;
 4718:             if ($excluded{$ids[$i]}) {
 4719:                 $check = ' checked="checked" ';
 4720:             }
 4721:             $datatable .= '<td class="LC_left_item">'.
 4722:                           '<span class="LC_nobreak"><label>'.
 4723:                           '<input type="checkbox" name="errorexcluded" '.
 4724:                           'value="'.$ids[$i].'"'.$check.' />'.
 4725:                           $ids[$i].'</label></span></td>';
 4726:         }
 4727:         my $colsleft = $numinrow - @ids%($numinrow);
 4728:         if ($colsleft > 1 ) {
 4729:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4730:                           '&nbsp;</td>';
 4731:         } elsif ($colsleft == 1) {
 4732:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4733:         }
 4734:         $datatable .= '</tr></table></td></tr>';
 4735:         $rownum ++;
 4736:     } elsif ($position eq 'bottom') {
 4737:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4738:         my (@posstypes,%usertypeshash);
 4739:         if (ref($types) eq 'ARRAY') {
 4740:             @posstypes = @{$types};
 4741:         }
 4742:         if (@posstypes) {
 4743:             if (ref($usertypes) eq 'HASH') {
 4744:                 %usertypeshash = %{$usertypes};
 4745:             }
 4746:             my @overridden;
 4747:             my $numinrow = 4;
 4748:             if (ref($settings) eq 'HASH') {
 4749:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4750:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4751:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4752:                             push(@overridden,$key);
 4753:                             foreach my $item (@contacts) {
 4754:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4755:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4756:                                 }
 4757:                             }
 4758:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4759:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4760:                             $includeloc{'override_'.$key} = '';
 4761:                             $includestr{'override_'.$key} = '';
 4762:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4763:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 4764:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4765:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4766:                             }
 4767:                         }
 4768:                     }
 4769:                 }
 4770:             }
 4771:             my $customclass = 'LC_helpdesk_override';
 4772:             my $optionsprefix = 'LC_options_helpdesk_';
 4773: 
 4774:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4775:  
 4776:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4777:                                          $numinrow,$othertitle,'overrides',
 4778:                                          \$rownum,$onclicktypes,$customclass);
 4779:             $rownum ++;
 4780:             $usertypeshash{'default'} = $othertitle;
 4781:             foreach my $status (@posstypes) {
 4782:                 my $css_class;
 4783:                 if ($rownum%2) {
 4784:                     $css_class = 'LC_odd_row ';
 4785:                 }
 4786:                 $css_class .= $customclass;
 4787:                 my $rowid = $optionsprefix.$status;
 4788:                 my $hidden = 1;
 4789:                 my $currstyle = 'display:none';
 4790:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4791:                     $currstyle = 'display:table-row';
 4792:                     $hidden = 0;
 4793:                 }
 4794:                 my $key = 'override_'.$status;
 4795:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4796:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4797:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4798:                                                   \@contacts,$short_titles);
 4799:                 unless ($hidden) {
 4800:                     $rownum ++;
 4801:                 }
 4802:             }
 4803:         }
 4804:     }
 4805:     $$rowtotal += $rownum;
 4806:     return $datatable;
 4807: }
 4808: 
 4809: sub core_link_msu {
 4810:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4811:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4812: }
 4813: 
 4814: sub overridden_helpdesk {
 4815:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4816:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4817:     my $class = 'LC_left_item';
 4818:     if ($css_class) {
 4819:         $css_class = ' class="'.$css_class.'"';
 4820:     }
 4821:     if ($rowid) {
 4822:         $rowid = ' id="'.$rowid.'"';
 4823:     }
 4824:     if ($rowstyle) {
 4825:         $rowstyle = ' style="'.$rowstyle.'"';
 4826:     }
 4827:     my ($output,$description);
 4828:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4829:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4830:               "<td>$description</td>\n".
 4831:               '<td class="'.$class.'" colspan="2">'.
 4832:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4833:               '<span class="LC_nobreak">';
 4834:     if (ref($contacts) eq 'ARRAY') {
 4835:         foreach my $item (@{$contacts}) {
 4836:             my $check;
 4837:             if (ref($checked) eq 'HASH') {
 4838:                $check = $checked->{$item};
 4839:             }
 4840:             my $title;
 4841:             if (ref($short_titles) eq 'HASH') {
 4842:                 $title = $short_titles->{$item}; 
 4843:             }
 4844:             $output .= '<label>'.
 4845:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4846:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4847:         }
 4848:     }
 4849:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4850:                '<input type="text" name="override_'.$type.'_others" '.
 4851:                'value="'.$otheremails.'"  />';
 4852:     my %locchecked;
 4853:     foreach my $loc ('s','b') {
 4854:         if ($includeloc eq $loc) {
 4855:             $locchecked{$loc} = ' checked="checked"';
 4856:             last;
 4857:         }
 4858:     }
 4859:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4860:                '<input type="text" name="override_'.$type.'_bcc" '.
 4861:                'value="'.$bccemails.'"  /></fieldset>'.
 4862:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4863:                &mt('Text automatically added to e-mail:').' '.
 4864:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4865:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4866:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4867:                ('&nbsp;'x2).
 4868:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4869:                '</span></fieldset>'.
 4870:                '</td></tr>'."\n";
 4871:     return $output;
 4872: }
 4873: 
 4874: sub contacts_javascript {
 4875:     return <<"ENDSCRIPT";
 4876: 
 4877: <script type="text/javascript">
 4878: // <![CDATA[
 4879: 
 4880: function screenshotSize(field) {
 4881:     if (document.getElementById('help_screenshotsize')) {
 4882:         if (field.value == 'no') {
 4883:             document.getElementById('help_screenshotsize').style.display="none";
 4884:         } else {
 4885:             document.getElementById('help_screenshotsize').style.display="";
 4886:         }
 4887:     }
 4888:     return;
 4889: }
 4890: 
 4891: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4892:     if (form.elements[checkbox].length != undefined) {
 4893:         var count = 0;
 4894:         if (docount) {
 4895:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4896:                 if (form.elements[checkbox][i].checked) {
 4897:                     count ++;
 4898:                 }
 4899:             }
 4900:         }
 4901:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4902:             var type = form.elements[checkbox][i].value;
 4903:             if (document.getElementById(prefix+type)) {
 4904:                 if (form.elements[checkbox][i].checked) {
 4905:                     document.getElementById(prefix+type).style.display = 'table-row';
 4906:                     if (count % 2 == 1) {
 4907:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4908:                     } else {
 4909:                         document.getElementById(prefix+type).className = target;
 4910:                     }
 4911:                     count ++;
 4912:                 } else {
 4913:                     document.getElementById(prefix+type).style.display = 'none';
 4914:                 }
 4915:             }
 4916:         }
 4917:     }
 4918:     return;
 4919: }
 4920: 
 4921: 
 4922: // ]]>
 4923: </script>
 4924: 
 4925: ENDSCRIPT
 4926: }
 4927: 
 4928: sub print_helpsettings {
 4929:     my ($position,$dom,$settings,$rowtotal) = @_;
 4930:     my $confname = $dom.'-domainconfig';
 4931:     my $formname = 'display';
 4932:     my ($datatable,$itemcount);
 4933:     if ($position eq 'top') {
 4934:         $itemcount = 1;
 4935:         my (%choices,%defaultchecked,@toggles);
 4936:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4937:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4938:                                      &mt('LON-CAPA bug tracker'),600,500));
 4939:         %defaultchecked = ('submitbugs' => 'on');
 4940:         @toggles = ('submitbugs');
 4941:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4942:                                                      \%choices,$itemcount);
 4943:         $$rowtotal ++;
 4944:     } else {
 4945:         my $css_class;
 4946:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4947:         my (%customroles,%ordered,%current);
 4948:         if (ref($settings) eq 'HASH') {
 4949:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4950:                 %current = %{$settings->{'adhoc'}};
 4951:             }
 4952:         }
 4953:         my $count = 0;
 4954:         foreach my $key (sort(keys(%existing))) {
 4955:             if ($key=~/^rolesdef\_(\w+)$/) {
 4956:                 my $rolename = $1;
 4957:                 my (%privs,$order);
 4958:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4959:                 $customroles{$rolename} = \%privs;
 4960:                 if (ref($current{$rolename}) eq 'HASH') {
 4961:                     $order = $current{$rolename}{'order'};
 4962:                 }
 4963:                 if ($order eq '') {
 4964:                     $order = $count;
 4965:                 }
 4966:                 $ordered{$order} = $rolename;
 4967:                 $count++;
 4968:             }
 4969:         }
 4970:         my $maxnum = scalar(keys(%ordered));
 4971:         my @roles_by_num = ();
 4972:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4973:             push(@roles_by_num,$item);
 4974:         }
 4975:         my $context = 'domprefs';
 4976:         my $crstype = 'Course';
 4977:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4978:         my @accesstypes = ('all','dh','da','none');
 4979:         my ($numstatustypes,@jsarray);
 4980:         if (ref($types) eq 'ARRAY') {
 4981:             if (@{$types} > 0) {
 4982:                 $numstatustypes = scalar(@{$types});
 4983:                 push(@accesstypes,'status');
 4984:                 @jsarray = ('bystatus');
 4985:             }
 4986:         }
 4987:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4988:         if (keys(%domhelpdesk)) {
 4989:             push(@accesstypes,('inc','exc'));
 4990:             push(@jsarray,('notinc','notexc'));
 4991:         }
 4992:         my $hiddenstr = join("','",@jsarray);
 4993:         my $context = 'domprefs';
 4994:         my $crstype = 'Course';
 4995:         my $prefix = 'helproles_';
 4996:         my $add_class = 'LC_hidden';
 4997:         foreach my $num (@roles_by_num) {
 4998:             my $role = $ordered{$num};
 4999:             my ($desc,$access,@statuses);
 5000:             if (ref($current{$role}) eq 'HASH') {
 5001:                 $desc = $current{$role}{'desc'};
 5002:                 $access = $current{$role}{'access'};
 5003:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 5004:                     @statuses = @{$current{$role}{'insttypes'}};
 5005:                 }
 5006:             }
 5007:             if ($desc eq '') {
 5008:                 $desc = $role;
 5009:             }
 5010:             my $identifier = 'custhelp'.$num;
 5011:             my %full=();
 5012:             my %levels= (
 5013:                          course => {},
 5014:                          domain => {},
 5015:                          system => {},
 5016:                         );
 5017:             my %levelscurrent=(
 5018:                                course => {},
 5019:                                domain => {},
 5020:                                system => {},
 5021:                               );
 5022:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 5023:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5024:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5025:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 5026:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 5027:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 5028:             for (my $k=0; $k<=$maxnum; $k++) {
 5029:                 my $vpos = $k+1;
 5030:                 my $selstr;
 5031:                 if ($k == $num) {
 5032:                     $selstr = ' selected="selected" ';
 5033:                 }
 5034:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5035:             }
 5036:             $datatable .= '</select>'.('&nbsp;'x2).
 5037:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 5038:                           '</td>'.
 5039:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5040:                           &mt('Name shown to users:').
 5041:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 5042:                           '</fieldset>'.
 5043:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 5044:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 5045:                           '<fieldset>'.
 5046:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 5047:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5048:                                                                    \%levelscurrent,$identifier,
 5049:                                                                    'LC_hidden',$prefix.$num.'_privs').
 5050:                           '</fieldset></td>';
 5051:             $itemcount ++;
 5052:         }
 5053:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5054:         my $newcust = 'custhelp'.$count;
 5055:         my (%privs,%levelscurrent);
 5056:         my %full=();
 5057:         my %levels= (
 5058:                      course => {},
 5059:                      domain => {},
 5060:                      system => {},
 5061:                     );
 5062:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5063:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5064:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 5065:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 5066:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 5067:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 5068:         for (my $k=0; $k<$maxnum+1; $k++) {
 5069:             my $vpos = $k+1;
 5070:             my $selstr;
 5071:             if ($k == $maxnum) {
 5072:                 $selstr = ' selected="selected" ';
 5073:             }
 5074:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5075:         }
 5076:         $datatable .= '</select>&nbsp;'."\n".
 5077:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 5078:                       '</label></span></td>'.
 5079:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5080:                       '<span class="LC_nobreak">'.
 5081:                       &mt('Internal name:').
 5082:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 5083:                       '</span>'.('&nbsp;'x4).
 5084:                       '<span class="LC_nobreak">'.
 5085:                       &mt('Name shown to users:').
 5086:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 5087:                       '</span></fieldset>'.
 5088:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 5089:                                              $usertypes,$types,\%domhelpdesk).
 5090:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 5091:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 5092:                                                                 \@templateroles,$newcust).
 5093:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 5094:                                                                \%levelscurrent,$newcust).
 5095:                       '</fieldset>'.
 5096:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 5097:                       '</td></tr>';
 5098:         $count ++;
 5099:         $$rowtotal += $count;
 5100:     }
 5101:     return $datatable;
 5102: }
 5103: 
 5104: sub adhocbutton {
 5105:     my ($prefix,$num,$field,$visibility) = @_;
 5106:     my %lt = &Apache::lonlocal::texthash(
 5107:                                           show => 'Show details',
 5108:                                           hide => 'Hide details',
 5109:                                         );
 5110:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 5111:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 5112:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 5113:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 5114: }
 5115: 
 5116: sub helpsettings_javascript {
 5117:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 5118:     return unless(ref($roles_by_num) eq 'ARRAY');
 5119:     my %html_js_lt = &Apache::lonlocal::texthash(
 5120:                                           show => 'Show details',
 5121:                                           hide => 'Hide details',
 5122:                                         );
 5123:     &html_escape(\%html_js_lt);
 5124:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 5125:     return <<"ENDSCRIPT";
 5126: <script type="text/javascript">
 5127: // <![CDATA[
 5128: 
 5129: function reorderHelpRoles(form,item) {
 5130:     var changedVal;
 5131: $jstext
 5132:     var newpos = 'helproles_${total}_pos';
 5133:     var maxh = 1 + $total;
 5134:     var current = new Array();
 5135:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5136:     if (item == newpos) {
 5137:         changedVal = newitemVal;
 5138:     } else {
 5139:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 5140:         current[newitemVal] = newpos;
 5141:     }
 5142:     for (var i=0; i<helproles.length; i++) {
 5143:         var elementName = 'helproles_'+helproles[i]+'_pos';
 5144:         if (elementName != item) {
 5145:             if (form.elements[elementName]) {
 5146:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 5147:                 current[currVal] = elementName;
 5148:             }
 5149:         }
 5150:     }
 5151:     var oldVal;
 5152:     for (var j=0; j<maxh; j++) {
 5153:         if (current[j] == undefined) {
 5154:             oldVal = j;
 5155:         }
 5156:     }
 5157:     if (oldVal < changedVal) {
 5158:         for (var k=oldVal+1; k<=changedVal ; k++) {
 5159:            var elementName = current[k];
 5160:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 5161:         }
 5162:     } else {
 5163:         for (var k=changedVal; k<oldVal; k++) {
 5164:             var elementName = current[k];
 5165:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 5166:         }
 5167:     }
 5168:     return;
 5169: }
 5170: 
 5171: function helpdeskAccess(num) {
 5172:     var curraccess = null;
 5173:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 5174:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 5175:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 5176:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 5177:             }
 5178:         }
 5179:     }
 5180:     var shown = Array();
 5181:     var hidden = Array();
 5182:     if (curraccess == 'none') {
 5183:         hidden = Array('$hiddenstr');
 5184:     } else {
 5185:         if (curraccess == 'status') {
 5186:             shown = Array('bystatus');
 5187:             hidden = Array('notinc','notexc');
 5188:         } else {
 5189:             if (curraccess == 'exc') {
 5190:                 shown = Array('notexc');
 5191:                 hidden = Array('notinc','bystatus');
 5192:             }
 5193:             if (curraccess == 'inc') {
 5194:                 shown = Array('notinc');
 5195:                 hidden = Array('notexc','bystatus');
 5196:             }
 5197:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 5198:                 hidden = Array('notinc','notexc','bystatus');
 5199:             }
 5200:         }
 5201:     }
 5202:     if (hidden.length > 0) {
 5203:         for (var i=0; i<hidden.length; i++) {
 5204:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 5205:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 5206:             }
 5207:         }
 5208:     }
 5209:     if (shown.length > 0) {
 5210:         for (var i=0; i<shown.length; i++) {
 5211:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 5212:                 if (shown[i] == 'privs') {
 5213:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 5214:                 } else {
 5215:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 5216:                 }
 5217:             }
 5218:         }
 5219:     }
 5220:     return;
 5221: }
 5222: 
 5223: function toggleHelpdeskItem(num,field) {
 5224:     if (document.getElementById('helproles_'+num+'_'+field)) {
 5225:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 5226:             document.getElementById('helproles_'+num+'_'+field).className =
 5227:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 5228:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5229:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 5230:             }
 5231:         } else {
 5232:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 5233:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5234:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 5235:             }
 5236:         }
 5237:     }
 5238:     return;
 5239: }
 5240: 
 5241: // ]]>
 5242: </script>
 5243: 
 5244: ENDSCRIPT
 5245: }
 5246: 
 5247: sub helpdeskroles_access {
 5248:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 5249:         $usertypes,$types,$domhelpdesk) = @_;
 5250:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 5251:     my %lt = &Apache::lonlocal::texthash(
 5252:                     'rou'    => 'Role usage',
 5253:                     'whi'    => 'Which helpdesk personnel may use this role?',
 5254:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 5255:                     'dh'     => 'All with domain helpdesk role',
 5256:                     'da'     => 'All with domain helpdesk assistant role',
 5257:                     'none'   => 'None',
 5258:                     'status' => 'Determined based on institutional status',
 5259:                     'inc'    => 'Include all, but exclude specific personnel',
 5260:                     'exc'    => 'Exclude all, but include specific personnel',
 5261:                   );
 5262:     my %usecheck = (
 5263:                      all => ' checked="checked"',
 5264:                    );
 5265:     my %displaydiv = (
 5266:                       status => 'none',
 5267:                       inc    => 'none',
 5268:                       exc    => 'none',
 5269:                       priv   => 'block',
 5270:                      );
 5271:     my $output;
 5272:     if (ref($current) eq 'HASH') {
 5273:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 5274:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 5275:                 $usecheck{$current->{access}} = $usecheck{'all'};
 5276:                 delete($usecheck{'all'});
 5277:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 5278:                     my $access = $1;
 5279:                     $displaydiv{$access} = 'inline';
 5280:                 } elsif ($current->{access} eq 'none') {
 5281:                     $displaydiv{'priv'} = 'none';
 5282:                 }
 5283:             }
 5284:         }
 5285:     }
 5286:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 5287:               '<p>'.$lt{'whi'}.'</p>';
 5288:     foreach my $access (@{$accesstypes}) {
 5289:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 5290:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 5291:                    $lt{$access}.'</label>';
 5292:         if ($access eq 'status') {
 5293:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 5294:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 5295:                                                                  $othertitle,$usertypes,$types).
 5296:                        '</div>';
 5297:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 5298:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 5299:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5300:                        '</div>';
 5301:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 5302:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 5303:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5304:                        '</div>';
 5305:         }
 5306:         $output .= '</p>';
 5307:     }
 5308:     $output .= '</fieldset>';
 5309:     return $output;
 5310: }
 5311: 
 5312: sub radiobutton_prefs {
 5313:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 5314:         $additional,$align,$firstval) = @_;
 5315:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 5316:                    (ref($choices) eq 'HASH'));
 5317: 
 5318:     my (%checkedon,%checkedoff,$datatable,$css_class);
 5319: 
 5320:     foreach my $item (@{$toggles}) {
 5321:         if ($defaultchecked->{$item} eq 'on') {
 5322:             $checkedon{$item} = ' checked="checked" ';
 5323:             $checkedoff{$item} = ' ';
 5324:         } elsif ($defaultchecked->{$item} eq 'off') {
 5325:             $checkedoff{$item} = ' checked="checked" ';
 5326:             $checkedon{$item} = ' ';
 5327:         }
 5328:     }
 5329:     if (ref($settings) eq 'HASH') {
 5330:         foreach my $item (@{$toggles}) {
 5331:             if ($settings->{$item} eq '1') {
 5332:                 $checkedon{$item} =  ' checked="checked" ';
 5333:                 $checkedoff{$item} = ' ';
 5334:             } elsif ($settings->{$item} eq '0') {
 5335:                 $checkedoff{$item} =  ' checked="checked" ';
 5336:                 $checkedon{$item} = ' ';
 5337:             }
 5338:         }
 5339:     }
 5340:     if ($onclick) {
 5341:         $onclick = ' onclick="'.$onclick.'"';
 5342:     }
 5343:     foreach my $item (@{$toggles}) {
 5344:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5345:         $datatable .=
 5346:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5347:             '<span class="LC_nobreak">'.$choices->{$item}.
 5348:             '</span></td>';
 5349:         if ($align eq 'left') {
 5350:             $datatable .= '<td class="LC_left_item">';
 5351:         } else {
 5352:             $datatable .= '<td class="LC_right_item">';
 5353:         }
 5354:         $datatable .= '<span class="LC_nobreak">';
 5355:         if ($firstval eq 'no') {
 5356:             $datatable .=
 5357:                 '<label><input type="radio" name="'.
 5358:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 5359:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5360:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 5361:         } else {
 5362:             $datatable .=
 5363:                 '<label><input type="radio" name="'.
 5364:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 5365:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5366:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 5367:         }
 5368:         $datatable .= '</span>'.$additional.'</td></tr>';
 5369:         $itemcount ++;
 5370:     }
 5371:     return ($datatable,$itemcount);
 5372: }
 5373: 
 5374: sub print_ltitools {
 5375:     my ($dom,$settings,$rowtotal) = @_;
 5376:     my $rownum = 0;
 5377:     my $css_class;
 5378:     my $itemcount = 1;
 5379:     my $maxnum = 0;
 5380:     my %ordered;
 5381:     if (ref($settings) eq 'HASH') {
 5382:         foreach my $item (keys(%{$settings})) {
 5383:             if (ref($settings->{$item}) eq 'HASH') {
 5384:                 my $num = $settings->{$item}{'order'};
 5385:                 $ordered{$num} = $item;
 5386:             }
 5387:         }
 5388:     }
 5389:     my $confname = $dom.'-domainconfig';
 5390:     my $switchserver = &check_switchserver($dom,$confname);
 5391:     my $maxnum = scalar(keys(%ordered));
 5392:     my $datatable;
 5393:     my %lt = &ltitools_names();
 5394:     my @courseroles = ('cc','in','ta','ep','st');
 5395:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 5396:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 5397:     if (keys(%ordered)) {
 5398:         my @items = sort { $a <=> $b } keys(%ordered);
 5399:         for (my $i=0; $i<@items; $i++) {
 5400:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5401:             my $item = $ordered{$items[$i]};
 5402:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 5403:             if (ref($settings->{$item}) eq 'HASH') {
 5404:                 $title = $settings->{$item}->{'title'};
 5405:                 $url = $settings->{$item}->{'url'};
 5406:                 $key = $settings->{$item}->{'key'};
 5407:                 $secret = $settings->{$item}->{'secret'};
 5408:                 $lifetime = $settings->{$item}->{'lifetime'};
 5409:                 my $image = $settings->{$item}->{'image'};
 5410:                 if ($image ne '') {
 5411:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 5412:                 }
 5413:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 5414:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 5415:                 } else {
 5416:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 5417:                 }
 5418:             }
 5419:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 5420:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5421:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 5422:             for (my $k=0; $k<=$maxnum; $k++) {
 5423:                 my $vpos = $k+1;
 5424:                 my $selstr;
 5425:                 if ($k == $i) {
 5426:                     $selstr = ' selected="selected" ';
 5427:                 }
 5428:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5429:             }
 5430:             $datatable .= '</select>'.('&nbsp;'x2).
 5431:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 5432:                 &mt('Delete?').'</label></span></td>'.
 5433:                 '<td colspan="2">'.
 5434:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5435:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 5436:                 ('&nbsp;'x2).
 5437:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 5438:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5439:                 ('&nbsp;'x2).
 5440:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 5441:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5442:                 ('&nbsp;'x2).
 5443:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 5444:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 5445:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 5446:                 '<br /><br />'.
 5447:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 5448:                 ' value="'.$url.'" /></span>'.
 5449:                 ('&nbsp;'x2).
 5450:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 5451:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 5452:                 ('&nbsp;'x2).
 5453:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 5454:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 5455:                 ('&nbsp;'x2).
 5456:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 5457:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 5458:                 '<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>'.
 5459:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 5460:                 '</fieldset>'.
 5461:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5462:                 '<span class="LC_nobreak">'.&mt('Display target:');
 5463:             my %currdisp;
 5464:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 5465:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 5466:                     $currdisp{'window'} = ' checked="checked"';
 5467:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 5468:                     $currdisp{'tab'} = ' checked="checked"';
 5469:                 } else {
 5470:                     $currdisp{'iframe'} = ' checked="checked"';
 5471:                 }
 5472:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 5473:                     $currdisp{'width'} = $1;
 5474:                 }
 5475:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 5476:                      $currdisp{'height'} = $1;
 5477:                 }
 5478:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 5479:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 5480:             } else {
 5481:                 $currdisp{'iframe'} = ' checked="checked"';
 5482:             }
 5483:             foreach my $disp ('iframe','tab','window') {
 5484:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 5485:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 5486:             }
 5487:             $datatable .= ('&nbsp;'x4);
 5488:             foreach my $dimen ('width','height') {
 5489:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5490:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 5491:                               ('&nbsp;'x2);
 5492:             }
 5493:             $datatable .= '</span><br />'.
 5494:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5495:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 5496:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5497:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 5498:                           '</textarea></div><div style=""></div><br />';
 5499:             my %units = (
 5500:                           'passback' => 'days',
 5501:                           'roster'   => 'seconds',
 5502:                         );
 5503:             foreach my $extra ('passback','roster') {
 5504:                 my $validsty = 'none';
 5505:                 my $currvalid;
 5506:                 my $checkedon = '';
 5507:                 my $checkedoff = ' checked="checked"';
 5508:                 if ($settings->{$item}->{$extra}) {
 5509:                     $checkedon = $checkedoff;
 5510:                     $checkedoff = '';
 5511:                     $validsty = 'inline-block';
 5512:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 5513:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 5514:                     }
 5515:                 }
 5516:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 5517:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5518:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 5519:                               &mt('No').'</label>'.('&nbsp;'x2).
 5520:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 5521:                               &mt('Yes').'</label></span></div>'.
 5522:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 5523:                               '<span class="LC_nobreak">'.
 5524:                               &mt("at least [_1] $units{$extra} after launch",
 5525:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 5526:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5527:             }
 5528:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5529:             if ($imgsrc) {
 5530:                 $datatable .= $imgsrc.
 5531:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 5532:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 5533:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 5534:             } else {
 5535:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5536:             }
 5537:             if ($switchserver) {
 5538:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5539:             } else {
 5540:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 5541:             }
 5542:             $datatable .= '</span></fieldset>';
 5543:             my (%checkedfields,%rolemaps,$userincdom);
 5544:             if (ref($settings->{$item}) eq 'HASH') {
 5545:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 5546:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 5547:                 }
 5548:                 $userincdom = $settings->{$item}->{'incdom'};
 5549:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 5550:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 5551:                     $checkedfields{'roles'} = 1;
 5552:                 }
 5553:             }
 5554:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5555:                           '<span class="LC_nobreak">';
 5556:             my $userfieldstyle = 'display:none;';
 5557:             my $seluserdom = '';
 5558:             my $unseluserdom = ' selected="selected"';
 5559:             foreach my $field (@fields) {
 5560:                 my ($checked,$onclick,$id,$spacer);
 5561:                 if ($checkedfields{$field}) {
 5562:                     $checked = ' checked="checked"';
 5563:                 }
 5564:                 if ($field eq 'user') {
 5565:                     $id = ' id="ltitools_user_field_'.$i.'"';
 5566:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 5567:                     if ($checked) {
 5568:                         $userfieldstyle = 'display:inline-block';
 5569:                         if ($userincdom) {
 5570:                             $seluserdom = $unseluserdom;
 5571:                             $unseluserdom = '';
 5572:                         }
 5573:                     }
 5574:                 } else {
 5575:                     $spacer = ('&nbsp;' x2);
 5576:                 }
 5577:                 $datatable .= '<label>'.
 5578:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 5579:                               $lt{$field}.'</label>'.$spacer;
 5580:             }
 5581:             $datatable .= '</span>';
 5582:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 5583:                           '<span class="LC_nobreak"> : '.
 5584:                           '<select name="ltitools_userincdom_'.$i.'">'.
 5585:                           '<option value="">'.&mt('Select').'</option>'.
 5586:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 5587:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 5588:                           '</select></span></div>';
 5589:             $datatable .= '</fieldset>'.
 5590:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5591:             foreach my $role (@courseroles) {
 5592:                 my ($selected,$selectnone);
 5593:                 if (!$rolemaps{$role}) {
 5594:                     $selectnone = ' selected="selected"';
 5595:                 }
 5596:                 $datatable .= '<td style="text-align: center">'. 
 5597:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5598:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 5599:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5600:                 foreach my $ltirole (@ltiroles) {
 5601:                     unless ($selectnone) {
 5602:                         if ($rolemaps{$role} eq $ltirole) {
 5603:                             $selected = ' selected="selected"';
 5604:                         } else {
 5605:                             $selected = '';
 5606:                         }
 5607:                     }
 5608:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5609:                 }
 5610:                 $datatable .= '</select></td>';
 5611:             }
 5612:             $datatable .= '</tr></table></fieldset>';
 5613:             my %courseconfig;
 5614:             if (ref($settings->{$item}) eq 'HASH') {
 5615:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 5616:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 5617:                 }
 5618:             }
 5619:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5620:             foreach my $item ('label','title','target','linktext','explanation','append') {
 5621:                 my $checked;
 5622:                 if ($courseconfig{$item}) {
 5623:                     $checked = ' checked="checked"';
 5624:                 }
 5625:                 $datatable .= '<label>'.
 5626:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 5627:                        $lt{'crs'.$item}.'</label>&nbsp; '."\n";
 5628:             }
 5629:             $datatable .= '</span></fieldset>'.
 5630:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5631:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 5632:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 5633:                 my %custom = %{$settings->{$item}->{'custom'}};
 5634:                 if (keys(%custom) > 0) {
 5635:                     foreach my $key (sort(keys(%custom))) {
 5636:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 5637:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 5638:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5639:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 5640:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 5641:                     }
 5642:                 }
 5643:             }
 5644:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 5645:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 5646:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 5647:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 5648:             $datatable .= '</table></fieldset></td></tr>'."\n";
 5649:             $itemcount ++;
 5650:         }
 5651:     }
 5652:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5653:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 5654:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5655:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 5656:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 5657:     for (my $k=0; $k<$maxnum+1; $k++) {
 5658:         my $vpos = $k+1;
 5659:         my $selstr;
 5660:         if ($k == $maxnum) {
 5661:             $selstr = ' selected="selected" ';
 5662:         }
 5663:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5664:     }
 5665:     $datatable .= '</select>&nbsp;'."\n".
 5666:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5667:                   '<td colspan="2">'.
 5668:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5669:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 5670:                   ('&nbsp;'x2).
 5671:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 5672:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5673:                   ('&nbsp;'x2).
 5674:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 5675:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5676:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 5677:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5678:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5679:                   '<br />'.
 5680:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 5681:                   ('&nbsp;'x2).
 5682:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 5683:                   ('&nbsp;'x2).
 5684:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 5685:                   ('&nbsp;'x2).
 5686:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 5687:                   '<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".
 5688:                   '</fieldset>'.
 5689:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5690:                   '<span class="LC_nobreak">'.&mt('Display target:');
 5691:     my %defaultdisp;
 5692:     $defaultdisp{'iframe'} = ' checked="checked"';
 5693:     foreach my $disp ('iframe','tab','window') {
 5694:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 5695:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 5696:     }
 5697:     $datatable .= ('&nbsp;'x4);
 5698:     foreach my $dimen ('width','height') {
 5699:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5700:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 5701:                       ('&nbsp;'x2);
 5702:     }
 5703:     $datatable .= '</span><br />'.
 5704:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5705:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 5706:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5707:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 5708:                   '</div><div style=""></div><br />';
 5709:     my %units = (
 5710:                   'passback' => 'days',
 5711:                   'roster'   => 'seconds',
 5712:                 );
 5713:     my %defaulttimes = (
 5714:                      'passback' => '7',
 5715:                      'roster'   => '300',
 5716:                    );
 5717:     foreach my $extra ('passback','roster') {
 5718:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 5719:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5720:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 5721:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 5722:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 5723:                       &mt('Yes').'</label></span></div>'.
 5724:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 5725:                       '<span class="LC_nobreak">'.
 5726:                       &mt("at least [_1] $units{$extra} after launch",
 5727:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 5728:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5729:     }
 5730:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 5731:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5732:     if ($switchserver) {
 5733:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5734:     } else {
 5735:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 5736:     }
 5737:     $datatable .= '</span></fieldset>'.
 5738:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5739:                   '<span class="LC_nobreak">';
 5740:     foreach my $field (@fields) {
 5741:         my ($id,$onclick,$spacer);
 5742:         if ($field eq 'user') {
 5743:             $id = ' id="ltitools_user_field_add"';
 5744:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 5745:         } else {
 5746:             $spacer = ('&nbsp;' x2);
 5747:         }
 5748:         $datatable .= '<label>'.
 5749:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 5750:                       $lt{$field}.'</label>'.$spacer;
 5751:     }
 5752:     $datatable .= '</span>'.
 5753:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 5754:                   '<span class="LC_nobreak"> : '.
 5755:                   '<select name="ltitools_userincdom_add">'.
 5756:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5757:                   '<option value="0">'.&mt('username').'</option>'.
 5758:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5759:                   '</select></span></div></fieldset>';
 5760:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5761:     foreach my $role (@courseroles) {
 5762:         my ($checked,$checkednone);
 5763:         $datatable .= '<td style="text-align: center">'.
 5764:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5765:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5766:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5767:         foreach my $ltirole (@ltiroles) {
 5768:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5769:         }
 5770:         $datatable .= '</select></td>';
 5771:     }
 5772:     $datatable .= '</tr></table></fieldset>'.
 5773:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5774:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5775:         $datatable .= '<label>'.
 5776:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5777:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5778:     }
 5779:     $datatable .= '</span></fieldset>'.
 5780:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5781:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5782:                   '<tr><td><span class="LC_nobreak">'.
 5783:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5784:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5785:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5786:                   '</table></fieldset>'."\n".
 5787:                   '</td>'."\n".
 5788:                   '</tr>'."\n";
 5789:     $itemcount ++;
 5790:     return $datatable;
 5791: }
 5792: 
 5793: sub ltitools_names {
 5794:     my %lt = &Apache::lonlocal::texthash(
 5795:                                           'title'          => 'Title',
 5796:                                           'version'        => 'Version',
 5797:                                           'msgtype'        => 'Message Type',
 5798:                                           'sigmethod'      => 'Signature Method',
 5799:                                           'url'            => 'URL',
 5800:                                           'key'            => 'Key',
 5801:                                           'lifetime'       => 'Nonce lifetime (s)',
 5802:                                           'secret'         => 'Secret',
 5803:                                           'icon'           => 'Icon',   
 5804:                                           'user'           => 'User',
 5805:                                           'fullname'       => 'Full Name',
 5806:                                           'firstname'      => 'First Name',
 5807:                                           'lastname'       => 'Last Name',
 5808:                                           'email'          => 'E-mail',
 5809:                                           'roles'          => 'Role',
 5810:                                           'window'         => 'Window',
 5811:                                           'tab'            => 'Tab',
 5812:                                           'iframe'         => 'iFrame',
 5813:                                           'height'         => 'Height',
 5814:                                           'width'          => 'Width',
 5815:                                           'linktext'       => 'Default Link Text',
 5816:                                           'explanation'    => 'Default Explanation',
 5817:                                           'passback'       => 'Tool can return grades:',
 5818:                                           'roster'         => 'Tool can retrieve roster:',
 5819:                                           'crstarget'      => 'Display target',
 5820:                                           'crslabel'       => 'Course label',
 5821:                                           'crstitle'       => 'Course title', 
 5822:                                           'crslinktext'    => 'Link Text',
 5823:                                           'crsexplanation' => 'Explanation',
 5824:                                           'crsappend'      => 'Provider URL',
 5825:                                         );
 5826:     return %lt;
 5827: }
 5828: 
 5829: sub print_proctoring {
 5830:     my ($dom,$settings,$rowtotal) = @_;
 5831:     my $itemcount = 1;
 5832:     my (%ordered,%providernames,%current,%currentdef);
 5833:     my $confname = $dom.'-domainconfig';
 5834:     my $switchserver = &check_switchserver($dom,$confname);
 5835:     if (ref($settings) eq 'HASH') {
 5836:         foreach my $item (keys(%{$settings})) {
 5837:             if (ref($settings->{$item}) eq 'HASH') {
 5838:                 my $num = $settings->{$item}{'order'};
 5839:                 $ordered{$num} = $item;
 5840:             }
 5841:         }
 5842:     } else {
 5843:         %ordered = (
 5844:                      1 => 'proctorio',
 5845:                      2 => 'examity',
 5846:                    );
 5847:     }
 5848:     %providernames = &proctoring_providernames();
 5849:     my $maxnum = scalar(keys(%ordered));
 5850:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5851:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5852:     if (ref($requref) eq 'HASH') {
 5853:         %requserfields = %{$requref};
 5854:     }
 5855:     if (ref($opturef) eq 'HASH') {
 5856:         %optuserfields = %{$opturef};
 5857:     }
 5858:     if (ref($defref) eq 'HASH') {
 5859:         %defaults = %{$defref};
 5860:     }
 5861:     if (ref($extref) eq 'HASH') {
 5862:         %extended = %{$extref};
 5863:     }
 5864:     if (ref($crsref) eq 'HASH') {
 5865:         %crsconf = %{$crsref};
 5866:     }
 5867:     if (ref($rolesref) eq 'ARRAY') {
 5868:         @courseroles = @{$rolesref};
 5869:     }
 5870:     if (ref($ltiref) eq 'ARRAY') {
 5871:         @ltiroles = @{$ltiref};
 5872:     }
 5873:     my $datatable;
 5874:     my $css_class;
 5875:     if (keys(%ordered)) {
 5876:         my @items = sort { $a <=> $b } keys(%ordered);
 5877:         for (my $i=0; $i<@items; $i++) {
 5878:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5879:             my $provider = $ordered{$items[$i]};
 5880:             my $optionsty = 'none';
 5881:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5882:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5883:             if (ref($settings) eq 'HASH') {
 5884:                 if (ref($settings->{$provider}) eq 'HASH') {
 5885:                     %current = %{$settings->{$provider}};
 5886:                     if ($current{'available'}) {
 5887:                         $optionsty = 'block';
 5888:                         $available = 1;
 5889:                     }
 5890:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5891:                         $lifetime = $current{'lifetime'};
 5892:                     }
 5893:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5894:                         $version = $current{'version'};
 5895:                     }
 5896:                     if ($current{'image'} ne '') {
 5897:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5898:                     }
 5899:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5900:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5901:                     }
 5902:                     $userincdom = $current{'incdom'};
 5903:                     if (ref($current{'roles'}) eq 'HASH') {
 5904:                         %rolemaps = %{$current{'roles'}};
 5905:                         $checkedfields{'roles'} = 1;
 5906:                     }
 5907:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5908:                         foreach my $val (@{$current{'defaults'}}) {
 5909:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5910:                                 $inuse{$val} = 1;
 5911:                             } else {
 5912:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5913:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5914:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5915:                                             $inuse{$poss} = $val;
 5916:                                             last;
 5917:                                         }
 5918:                                     }
 5919:                                 }
 5920:                             }
 5921:                         }
 5922:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5923:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5924:                             my $currval = $current{'defaults'}{$key}; 
 5925:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5926:                                 $inuse{$key} = 1;
 5927:                             } else {
 5928:                                 my $match;
 5929:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5930:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5931:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5932:                                             $inuse{$poss} = $key;
 5933:                                             last;
 5934:                                         }
 5935:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5936:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5937:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5938:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5939:                                                     $currentdef{$inner} = $currval;
 5940:                                                     $match = 1;
 5941:                                                     last;
 5942:                                                 }
 5943:                                             } elsif ($inner eq $key) {
 5944:                                                 $currentdef{$key} = $currval;
 5945:                                                 $match = 1;
 5946:                                                 last;
 5947:                                             }
 5948:                                         }
 5949:                                     }
 5950:                                     last if ($match);
 5951:                                 }
 5952:                             }
 5953:                         }
 5954:                     }
 5955:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5956:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5957:                     }
 5958:                 }
 5959:             }
 5960:             my %lt = &proctoring_titles($provider);
 5961:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5962:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5963:             my %checkedavailable = (
 5964:                                    yes => '',
 5965:                                    no  => ' checked="checked"',
 5966:                                  );
 5967:             if ($available) {
 5968:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5969:                 $checkedavailable{'no'} = '';
 5970:             }
 5971:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5972:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5973:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 5974:             for (my $k=0; $k<$maxnum; $k++) {
 5975:                 my $vpos = $k+1;
 5976:                 my $selstr;
 5977:                 if ($k == $i) {
 5978:                     $selstr = ' selected="selected" ';
 5979:                 }
 5980:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5981:             }
 5982:             if ($version eq '') {
 5983:                 if ($provider eq 'proctorio') {
 5984:                     $version = '1.0';
 5985:                 } elsif ($provider eq 'examity') {
 5986:                     $version = '1.1';
 5987:                 }
 5988:             }
 5989:             if ($lifetime eq '') {
 5990:                 $lifetime = '300';
 5991:             }
 5992:             $datatable .=
 5993:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 5994:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 5995:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5996:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 5997:                 '</td>'.
 5998:                 '<td colspan="2">'.
 5999:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 6000:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 6001:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 6002:                 ('&nbsp;'x2).
 6003:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 6004:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 6005:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 6006:                 ('&nbsp;'x2).
 6007:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 6008:                 '<br />'.
 6009:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 6010:                 '<br />'.
 6011:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 6012:                 ('&nbsp;'x2).
 6013:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 6014:                 '<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";
 6015:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 6016:             if ($imgsrc) {
 6017:                 $datatable .= $imgsrc.
 6018:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 6019:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 6020:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 6021:             }
 6022:             $datatable .= '&nbsp;';
 6023:             if ($switchserver) {
 6024:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 6025:             } else {
 6026:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 6027:             }
 6028:             unless ($imgsrc) {
 6029:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 6030:             }
 6031:             $datatable .= '</fieldset>'."\n";
 6032:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 6033:                 if (@{$requserfields{$provider}} > 0) {
 6034:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 6035:                     foreach my $field (@{$requserfields{$provider}}) {
 6036:                         $datatable .= '<span class="LC_nobreak">'.
 6037:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 6038:                                       $lt{$field}.'</label>';
 6039:                         if ($field eq 'user') {
 6040:                             my $seluserdom = '';
 6041:                             my $unseluserdom = ' selected="selected"';
 6042:                             if ($userincdom) {
 6043:                                 $seluserdom = $unseluserdom;
 6044:                                 $unseluserdom = '';
 6045:                             }
 6046:                             $datatable .= ':&nbsp;'.
 6047:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 6048:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 6049:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 6050:                                 '</select>&nbsp;';
 6051:                         } else {
 6052:                             $datatable .= '&nbsp;';
 6053:                             if ($field eq 'roles') {
 6054:                                 $showroles = 1; 
 6055:                             } 
 6056:                         }
 6057:                         $datatable .= '</span> ';
 6058:                     }
 6059:                 }
 6060:                 $datatable .= '</fieldset>'."\n";
 6061:             }
 6062:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 6063:                 if (@{$optuserfields{$provider}} > 0) {
 6064:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 6065:                     foreach my $field (@{$optuserfields{$provider}}) {
 6066:                         my $checked;
 6067:                         if ($checkedfields{$field}) {
 6068:                             $checked = ' checked="checked"';
 6069:                         }
 6070:                         $datatable .= '<span class="LC_nobreak">'.
 6071:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 6072:                     }
 6073:                     $datatable .= '</fieldset>'."\n";
 6074:                 }
 6075:             }
 6076:             if (ref($defaults{$provider}) eq 'ARRAY') {
 6077:                 if (@{$defaults{$provider}}) {
 6078:                     my (%options,@selectboxes);
 6079:                     if (ref($extended{$provider}) eq 'HASH') {
 6080:                         %options = %{$extended{$provider}};
 6081:                     }
 6082:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 6083:                     my ($rem,$numinrow,$dropdowns);
 6084:                     if ($provider eq 'proctorio') { 
 6085:                         $datatable .= '<table>';
 6086:                         $numinrow = 4;
 6087:                     }
 6088:                     my $i = 0;
 6089:                     foreach my $field (@{$defaults{$provider}}) {
 6090:                         my $checked;
 6091:                         if ($inuse{$field}) {
 6092:                             $checked = ' checked="checked"';
 6093:                         }
 6094:                         if ($provider eq 'examity') {
 6095:                             if ($field eq 'display') {
 6096:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 6097:                                 foreach my $option ('iframe','tab','window') {
 6098:                                     my $checkdisp;
 6099:                                     if ($currentdef{'target'} eq $option) {
 6100:                                         $checkdisp = ' checked="checked"';
 6101:                                     }
 6102:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 6103:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 6104:                                 }
 6105:                                 $datatable .= ('&nbsp;'x4);
 6106:                                 foreach my $dimen ('width','height') {
 6107:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 6108:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 6109:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 6110:                                                   ('&nbsp;'x2);
 6111:                                 }
 6112:                                 $datatable .= '</span><br />'.
 6113:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 6114:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 6115:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 6116:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 6117:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 6118:                                               $currentdef{'explanation'}.
 6119:                                               '</textarea></div><div style=""></div><br />';
 6120:                             }
 6121:                         } else {
 6122:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 6123:                                 my ($output,$selnone);
 6124:                                 unless ($checked) {
 6125:                                     $selnone = ' selected="selected"';
 6126:                                 }
 6127:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 6128:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 6129:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 6130:                                 foreach my $option (@{$options{$field}}) {
 6131:                                     my $sel; 
 6132:                                     if ($inuse{$field} eq $option) {
 6133:                                         $sel = ' selected="selected"';
 6134:                                     }
 6135:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 6136:                                 }
 6137:                                 $output .= '</select></span>';
 6138:                                 push(@selectboxes,$output);
 6139:                             } else {
 6140:                                 $rem = $i%($numinrow);
 6141:                                 if ($rem == 0) {
 6142:                                     if ($i > 0) {
 6143:                                         $datatable .= '</tr>';
 6144:                                     }
 6145:                                     $datatable .= '<tr>';
 6146:                                 }
 6147:                                 $datatable .= '<td class="LC_left_item">'.
 6148:                                               '<span class="LC_nobreak">'.
 6149:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 6150:                                               $fieldtitles{$field}.'</label></span></td>';
 6151:                                 $i++;
 6152:                             }
 6153:                         }
 6154:                     }
 6155:                     if ($provider eq 'proctorio') {
 6156:                         if ($numinrow) {
 6157:                             $rem = $i%$numinrow;
 6158:                         }
 6159:                         my $colsleft = $numinrow - $rem;
 6160:                         if ($colsleft > 1) {
 6161:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6162:                         } else {
 6163:                             $datatable .= '<td class="LC_left_item">';
 6164:                         }
 6165:                         $datatable .= '&nbsp;'.
 6166:                                       '</td></tr></table>';
 6167:                         if (@selectboxes) {
 6168:                             $datatable .= '<hr /><table>';
 6169:                             $numinrow = 2;
 6170:                             for (my $i=0; $i<@selectboxes; $i++) {
 6171:                                 $rem = $i%($numinrow);
 6172:                                 if ($rem == 0) {
 6173:                                     if ($i > 0) {
 6174:                                         $datatable .= '</tr>';
 6175:                                     }
 6176:                                     $datatable .= '<tr>';
 6177:                                 }
 6178:                                 $datatable .= '<td class="LC_left_item">'.
 6179:                                               $selectboxes[$i].'</td>';
 6180:                             }
 6181:                             if ($numinrow) {
 6182:                                 $rem = $i%$numinrow;
 6183:                             }
 6184:                             $colsleft = $numinrow - $rem;
 6185:                             if ($colsleft > 1) {
 6186:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6187:                             } else {
 6188:                                 $datatable .= '<td class="LC_left_item">';
 6189:                             }
 6190:                             $datatable .= '&nbsp;'.
 6191:                                           '</td></tr></table>';
 6192:                         }
 6193:                     }
 6194:                     $datatable .= '</fieldset>';
 6195:                 }
 6196:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 6197:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6198:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 6199:                     my ($rem,$numinrow);
 6200:                     if ($provider eq 'proctorio') {
 6201:                         $datatable .= '<table>';
 6202:                         $numinrow = 4;
 6203:                     }
 6204:                     my $i = 0;
 6205:                     foreach my $item (@{$crsconf{$provider}}) {
 6206:                         my $name;
 6207:                         if ($provider eq 'examity') {
 6208:                             $name = $lt{'crs'.$item};
 6209:                         } elsif ($provider eq 'proctorio') {
 6210:                             $name = $fieldtitles{$item};
 6211:                             $rem = $i%($numinrow);
 6212:                             if ($rem == 0) {
 6213:                                 if ($i > 0) {
 6214:                                     $datatable .= '</tr>';
 6215:                                 }
 6216:                                 $datatable .= '<tr>';
 6217:                             }
 6218:                             $datatable .= '<td class="LC_left_item>';
 6219:                         }
 6220:                         my $checked;
 6221:                         if ($crsconfig{$item}) {
 6222:                             $checked = ' checked="checked"';
 6223:                         }
 6224:                         $datatable .= '<span class="LC_nobreak"><label>'.
 6225:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 6226:                                       $name.'</label></span>';
 6227:                         if ($provider eq 'examity') {
 6228:                             $datatable .= '&nbsp; ';
 6229:                         }
 6230:                         $datatable .= "\n";
 6231:                         $i++;
 6232:                     }
 6233:                     if ($provider eq 'proctorio') {
 6234:                         if ($numinrow) {
 6235:                             $rem = $i%$numinrow;
 6236:                         }
 6237:                         my $colsleft = $numinrow - $rem;
 6238:                         if ($colsleft > 1) {
 6239:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6240:                         } else {
 6241:                             $datatable .= '<td class="LC_left_item">';
 6242:                         }
 6243:                         $datatable .= '&nbsp;'.
 6244:                                       '</td></tr></table>';
 6245:                     }
 6246:                     $datatable .= '</fieldset>';
 6247:                 }
 6248:                 if ($showroles) {
 6249:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6250:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 6251:                     foreach my $role (@courseroles) {
 6252:                         my ($selected,$selectnone);
 6253:                         if (!$rolemaps{$role}) {
 6254:                             $selectnone = ' selected="selected"';
 6255:                         }
 6256:                         $datatable .= '<td style="text-align: center">'.
 6257:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 6258:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 6259:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6260:                         foreach my $ltirole (@ltiroles) {
 6261:                             unless ($selectnone) {
 6262:                                 if ($rolemaps{$role} eq $ltirole) {
 6263:                                     $selected = ' selected="selected"';
 6264:                                 } else {
 6265:                                     $selected = '';
 6266:                                 }
 6267:                             }
 6268:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 6269:                         }
 6270:                         $datatable .= '</select></td>';
 6271:                     }
 6272:                     $datatable .= '</tr></table></fieldset>'.
 6273:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6274:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 6275:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 6276:                                   '<tr><td></td><td>lms</td>'.
 6277:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 6278:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 6279:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 6280:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 6281:                         my %custom = %{$settings->{$provider}->{'custom'}};
 6282:                         if (keys(%custom) > 0) {
 6283:                             foreach my $key (sort(keys(%custom))) {
 6284:                                 next if ($key eq 'lms');
 6285:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 6286:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 6287:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 6288:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 6289:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 6290:                             }
 6291:                         }
 6292:                     }
 6293:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 6294:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 6295:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 6296:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 6297:                                   '</table></fieldset></td></tr>'."\n";
 6298:                 }
 6299:                 $datatable .= '</td></tr>';
 6300:             }
 6301:             $itemcount ++;
 6302:         }
 6303:     }
 6304:     return $datatable;
 6305: }
 6306: 
 6307: sub proctoring_data {
 6308:     my $requserfields = {
 6309:                       proctorio => ['user'],
 6310:                       examity   => ['roles','user'],
 6311:                      };
 6312:     my $optuserfields = {
 6313:                         proctorio => ['fullname'],
 6314:                         examity   => ['fullname','firstname','lastname','email'],
 6315:                      };
 6316:     my $defaults = {
 6317:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6318:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6319:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6320:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 6321:                                 'reentry','calculator','whiteboard'],
 6322:                   examity   => ['display'],
 6323:                 };
 6324:     my $extended = { 
 6325:                   proctorio => {
 6326:                                  verifyid => ['verifyidauto','verifyidlive'],
 6327:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 6328:                                  tabslinks => ['notabs','linksonly'],
 6329:                                  reentry => ['noreentry','agentreentry'],
 6330:                                  calculator => ['calculatorbasic','calculatorsci'],
 6331:                                },
 6332:                   examity => {
 6333:                                display => {
 6334:                                            target      => ['iframe','tab','window'],
 6335:                                            width       => '',
 6336:                                            height      => '',
 6337:                                            linktext    => '',
 6338:                                            explanation => '',
 6339:                                           },
 6340:                              },
 6341:                 };
 6342:     my $crsconf = {
 6343:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6344:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6345:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6346:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 6347:                                'reentry','calculator','whiteboard'],
 6348:                  examity => ['label','title','target','linktext','explanation','append'],
 6349:                };
 6350:     my $courseroles = ['cc','in','ta','ep','st'];
 6351:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 6352:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 6353: }
 6354: 
 6355: sub proctoring_titles {
 6356:     my ($item) = @_;
 6357:     my (%common_lt,%custom_lt);
 6358:     %common_lt = &Apache::lonlocal::texthash (
 6359:                      'avai'      => 'Available?',
 6360:                      'base'      => 'Basic Settings',
 6361:                      'requ'      => 'User data required to be sent on launch',
 6362:                      'optu'      => 'User data optionally sent on launch',
 6363:                      'udsl'      => 'User data sent on launch',
 6364:                      'defa'      => 'Defaults for items configurable in course',
 6365:                      'sigmethod' => 'Signature Method',
 6366:                      'key'       => 'Key',
 6367:                      'lifetime'  => 'Nonce lifetime (s)',
 6368:                      'secret'    => 'Secret',
 6369:                      'icon'      => 'Icon',
 6370:                      'fullname'  => 'Full Name',
 6371:                      'visible'   => 'Visible input',
 6372:                      'username'  => 'username',
 6373:                      'user'      => 'User',
 6374:                  );
 6375:     if ($item eq 'proctorio') {
 6376:         %custom_lt = &Apache::lonlocal::texthash (
 6377:                          'version'        => 'OAuth version',
 6378:                          'url'            => 'API URL',
 6379:                          'uname:dom'      => 'username-domain',
 6380:         );
 6381:     } elsif ($item eq 'examity') {
 6382:         %custom_lt = &Apache::lonlocal::texthash (
 6383:                          'version'        => 'LTI Version',
 6384:                          'url'            => 'URL',
 6385:                          'uname:dom'      => 'username:domain',
 6386:                          'msgtype'        => 'Message Type',
 6387:                          'firstname'      => 'First Name',
 6388:                          'lastname'       => 'Last Name',
 6389:                          'email'          => 'E-mail',
 6390:                          'roles'          => 'Role',
 6391:                          'crstarget'      => 'Display target',
 6392:                          'crslabel'       => 'Course label',
 6393:                          'crstitle'       => 'Course title', 
 6394:                          'crslinktext'    => 'Link Text',
 6395:                          'crsexplanation' => 'Explanation',
 6396:                          'crsappend'      => 'Provider URL',
 6397:         );
 6398:     }
 6399:     my %lt = (%common_lt,%custom_lt);
 6400:     return %lt;
 6401: }
 6402: 
 6403: sub proctoring_fieldtitles {
 6404:     my ($item) = @_;
 6405:     if ($item eq 'proctorio') {
 6406:         return &Apache::lonlocal::texthash (
 6407:                   'recordvideo' => 'Record video',
 6408:                   'recordaudio' => 'Record audio',
 6409:                   'recordscreen' => 'Record screen',
 6410:                   'recordwebtraffic' => 'Record web traffic',
 6411:                   'recordroomstart' => 'Record room scan',
 6412:                   'verifyvideo' => 'Verify webcam',
 6413:                   'verifyaudio' => 'Verify microphone',
 6414:                   'verifydesktop' => 'Verify desktop recording',
 6415:                   'verifyid' => 'Photo ID verification',
 6416:                   'verifysignature' => 'Require signature',
 6417:                   'fullscreen' => 'Fullscreen',
 6418:                   'clipboard' => 'Disable copy/paste',
 6419:                   'tabslinks' => 'New tabs/windows',
 6420:                   'closetabs' => 'Close other tabs',
 6421:                   'onescreen' => 'Limit to single screen',
 6422:                   'print' => 'Disable Printing',
 6423:                   'downloads' => 'Disable Downloads',
 6424:                   'cache' => 'Empty cache after exam',
 6425:                   'rightclick' => 'Disable right click',
 6426:                   'reentry' => 'Re-entry to exam',
 6427:                   'calculator' => 'Onscreen calculator',
 6428:                   'whiteboard' => 'Onscreen whiteboard',
 6429:                   'verifyidauto' => 'Automated verification',
 6430:                   'verifyidlive' => 'Live agent verification',
 6431:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 6432:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 6433:                   'fullscreensever' => 'Forced, navigation away ends exam',
 6434:                   'notabs' => 'Disaallowed',
 6435:                   'linksonly' => 'Allowed from links in exam',
 6436:                   'noreentry' => 'Disallowed',
 6437:                   'agentreentry' => 'Agent required for re-entry',
 6438:                   'calculatorbasic' => 'Basic',
 6439:                   'calculatorsci' => 'Scientific',
 6440:         );
 6441:     } elsif ($item eq 'examity') {
 6442:         return &Apache::lonlocal::texthash (
 6443:                 'target'         => 'Display target',   
 6444:                 'window'         => 'Window',
 6445:                 'tab'            => 'Tab',
 6446:                 'iframe'         => 'iFrame',
 6447:                 'height'         => 'Height (pixels)',
 6448:                 'width'          => 'Width (pixels)',
 6449:                 'linktext'       => 'Default Link Text',
 6450:                 'explanation'    => 'Default Explanation',
 6451:                 'append'         => 'Provider URL',
 6452:         );
 6453:     }
 6454: }
 6455: 
 6456: sub proctoring_providernames {
 6457:     return (
 6458:              proctorio => 'Proctorio',
 6459:              examity   => 'Examity',
 6460:            );
 6461: }
 6462: 
 6463: sub print_lti {
 6464:     my ($position,$dom,$settings,$rowtotal) = @_;
 6465:     my $itemcount = 1;
 6466:     my ($datatable,$css_class);
 6467:     my (%rules,%encrypt,%privkeys,%linkprot);
 6468:     if (ref($settings) eq 'HASH') {
 6469:         if ($position eq 'top') {
 6470:             if (exists($settings->{'encrypt'})) {
 6471:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 6472:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 6473:                         if ($key eq 'consumers') {
 6474:                             $encrypt{'ltisec_'.$key} = $settings->{'encrypt'}{$key};
 6475:                         } else {
 6476:                             $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 6477:                         }
 6478:                     }
 6479:                 }
 6480:             }
 6481:             if (exists($settings->{'private'})) {
 6482:                 if (ref($settings->{'private'}) eq 'HASH') {
 6483:                     if (ref($settings->{'private'}) eq 'HASH') {
 6484:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 6485:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 6486:                         }
 6487:                     }
 6488:                 }
 6489:             }
 6490:         } elsif ($position eq 'middle') {
 6491:             if (exists($settings->{'rules'})) {
 6492:                 if (ref($settings->{'rules'}) eq 'HASH') {
 6493:                     %rules = %{$settings->{'rules'}};
 6494:                 }
 6495:             }
 6496:         } elsif ($position eq 'lower') {
 6497:             if (exists($settings->{'linkprot'})) {
 6498:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 6499:                     %linkprot = %{$settings->{'linkprot'}};
 6500:                     if ($linkprot{'lock'}) {
 6501:                         delete($linkprot{'lock'});
 6502:                     }
 6503:                 }
 6504:             }
 6505:         } else {
 6506:             foreach my $key ('encrypt','private','rules','linkprot') {
 6507:                 if (exists($settings->{$key})) {
 6508:                     delete($settings->{$key});
 6509:                 }
 6510:             }
 6511:         }
 6512:     }
 6513:     if ($position eq 'top') {
 6514:         my @ids=&Apache::lonnet::current_machine_ids();
 6515:         my %servers = &Apache::lonnet::get_servers($dom,'library');
 6516:         my $primary = &Apache::lonnet::domain($dom,'primary');
 6517:         my ($extra,$numshown);
 6518:         foreach my $hostid (sort(keys(%servers))) {
 6519:             my ($showextra,$divsty,$switch);
 6520:             if ($hostid eq $primary) {
 6521:                 if (($encrypt{'ltisec_consumers'}) || ($encrypt{'ltisec_domlinkprot'})) {
 6522:                     $showextra = 1;
 6523:                 }
 6524:             }
 6525:             if ($encrypt{'ltisec_crslinkprot'}) {
 6526:                 $showextra = 1;
 6527:             }
 6528:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 6529:                 $switch = 1;
 6530:             }
 6531:             if ($showextra) {
 6532:                 $numshown ++;
 6533:                 $divsty = 'display:inline-block'; 
 6534:             } else {
 6535:                 $divsty = 'display:none';
 6536:             } 
 6537:             $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
 6538:                       '<legend>'.$hostid.'</legend>';
 6539:             if ($switch) {
 6540:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 6541:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 6542:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 6543:                 if (exists($privkeys{$hostid})) {
 6544:                     $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 6545:                               '<span class="LC_nobreak">'.
 6546:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6547:                               '<span class="LC_nobreak">'.&mt('Change?').
 6548:                               '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6549:                               ('&nbsp;'x2).
 6550:                               '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6551:                               '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6552:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6553:                               '</span></div>';
 6554:                 } else {
 6555:                     $extra .= '<span class="LC_nobreak">'.
 6556:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6557:                               '</span>'."\n";
 6558:                 }
 6559:             } elsif (exists($privkeys{$hostid})) {
 6560:                 $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 6561:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6562:                           '<span class="LC_nobreak">'.&mt('Change?').
 6563:                           '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6564:                           ('&nbsp;'x2).
 6565:                           '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6566:                           '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6567:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 6568:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6569:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>'.
 6570:                           '</span></div>';
 6571:             } else {
 6572:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 6573:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6574:                           '<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.ltisec_privkey_'.$hostid.'.type='."'text'".' } else { this.form.ltisec_privkey_'.$hostid.'.type='."'password'".' }" />'.&mt('Visible input').'</label>';
 6575:             }
 6576:             $extra .= '</fieldset>';
 6577:         }
 6578:         my %choices = &Apache::lonlocal::texthash (
 6579:                                                       ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 6580:                                                       ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 6581:                                                       ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
 6582:                                                   );
 6583:         my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
 6584:         my %defaultchecked = (
 6585:                                'ltisec_crslinkprot' => 'off',
 6586:                                'ltisec_domlinkprot' => 'off',
 6587:                                'ltisec_consumers'   => 'off',
 6588:                              );
 6589:         my ($onclick,$itemcount);
 6590:         $onclick = 'javascript:toggleLTIEncKey(this.form);';
 6591:         ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
 6592:                                                      \%choices,$itemcount,$onclick,'','left','no');
 6593: 
 6594:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6595:         my $noprivkeysty = 'display:inline-block';
 6596:         if ($numshown) {
 6597:             $noprivkeysty = 'display:none'; 
 6598:         }
 6599:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 6600:                       '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
 6601:                       '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 6602:                       $extra.
 6603:                       '</td></tr>';
 6604:         $itemcount ++;                
 6605:         $$rowtotal += $itemcount;
 6606:     } elsif ($position eq 'middle') {
 6607:         $datatable = &password_rules('secrets',\$itemcount,\%rules);
 6608:         $$rowtotal += $itemcount;
 6609:     } elsif ($position eq 'lower') {
 6610:          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
 6611:     } else {
 6612:         my $maxnum = 0;
 6613:         my %ordered;
 6614:         if (ref($settings) eq 'HASH') {
 6615:             foreach my $item (keys(%{$settings})) {
 6616:                 if (ref($settings->{$item}) eq 'HASH') {
 6617:                     my $num = $settings->{$item}{'order'};
 6618:                     if ($num eq '') {
 6619:                         $num = scalar(keys(%{$settings}));
 6620:                     }
 6621:                     $ordered{$num} = $item;
 6622:                 }
 6623:             }
 6624:         }
 6625:         $maxnum = scalar(keys(%ordered));
 6626:         my %lt = &lti_names();
 6627:         if (keys(%ordered)) {
 6628:             my @items = sort { $a <=> $b } keys(%ordered);
 6629:             for (my $i=0; $i<@items; $i++) {
 6630:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6631:                 my $item = $ordered{$items[$i]};
 6632:                 my ($key,$secret,$lifetime,$consumer,$requser,$crsinc,$current);
 6633:                 if (ref($settings->{$item}) eq 'HASH') {
 6634:                     $key = $settings->{$item}->{'key'};
 6635:                     $secret = $settings->{$item}->{'secret'};
 6636:                     $lifetime = $settings->{$item}->{'lifetime'};
 6637:                     $consumer = $settings->{$item}->{'consumer'};
 6638:                     $requser = $settings->{$item}->{'requser'};
 6639:                     $crsinc = $settings->{$item}->{'crsinc'};
 6640:                     $current = $settings->{$item};
 6641:                 }
 6642:                 my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 6643:                 my %checkedrequser = (
 6644:                                        yes => ' checked="checked"',
 6645:                                        no  => '',
 6646:                                      );
 6647:                 if (!$requser) {
 6648:                     $checkedrequser{'no'} = $checkedrequser{'yes'};
 6649:                     $checkedrequser{'yes'} = '';
 6650:                 }
 6651:                 my $onclickcrsinc = ' onclick="toggleLTI(this.form,'."'crsinc','$i'".');"';
 6652:                 my %checkedcrsinc = (
 6653:                                       yes => ' checked="checked"',
 6654:                                       no  => '',
 6655:                                     );
 6656:                 if (!$crsinc) {
 6657:                     $checkedcrsinc{'no'} = $checkedcrsinc{'yes'};
 6658:                     $checkedcrsinc{'yes'} = '';
 6659:                 }
 6660:                 my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 6661:                 $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6662:                              .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 6663:                 for (my $k=0; $k<=$maxnum; $k++) {
 6664:                     my $vpos = $k+1;
 6665:                     my $selstr;
 6666:                     if ($k == $i) {
 6667:                         $selstr = ' selected="selected" ';
 6668:                     }
 6669:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6670:                 }
 6671:                 $datatable .= '</select>'.('&nbsp;'x2).
 6672:                     '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 6673:                     &mt('Delete?').'</label></span></td>'.
 6674:                     '<td colspan="2">'.
 6675:                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6676:                     '<span class="LC_nobreak">'.$lt{'consumer'}.
 6677:                     ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 6678:                     ('&nbsp;'x2).
 6679:                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 6680:                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 6681:                     ('&nbsp;'x2).
 6682:                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 6683:                     'value="'.$lifetime.'" size="3" /></span>'.
 6684:                     ('&nbsp;'x2).
 6685:                     '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6686:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6687:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 6688:                     '<br /><br />'.
 6689:                     '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6690:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="1"'.$onclickcrsinc.$checkedcrsinc{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6691:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="0"'.$onclickcrsinc.$checkedcrsinc{no}.' />'.&mt('No').'</label></span>'."\n".
 6692:                     ('&nbsp;'x4).
 6693:                     '<span class="LC_nobreak">'.$lt{'key'}.
 6694:                     ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 6695:                     ('&nbsp;'x2).
 6696:                     '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 6697:                     '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 6698:                     '<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>'.
 6699:                     '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 6700:                     '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 6701:                 $itemcount ++;
 6702:             }
 6703:         }
 6704:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6705:         my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 6706:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 6707:                       '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 6708:                       '<select name="lti_pos_add"'.$chgstr.'>';
 6709:         for (my $k=0; $k<$maxnum+1; $k++) {
 6710:             my $vpos = $k+1;
 6711:             my $selstr;
 6712:             if ($k == $maxnum) {
 6713:                 $selstr = ' selected="selected" ';
 6714:             }
 6715:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6716:         }
 6717:         $datatable .= '</select>&nbsp;'."\n".
 6718:                       '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 6719:                       '<td colspan="2">'.
 6720:                       '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6721:                       '<span class="LC_nobreak">'.$lt{'consumer'}.
 6722:                       ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 6723:                       ('&nbsp;'x2).
 6724:                       '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 6725:                       '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 6726:                       ('&nbsp;'x2).
 6727:                       '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 6728:                       ('&nbsp;'x2).
 6729:                       '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6730:                       '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6731:                       '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 6732:                       '<br /><br />'.
 6733:                       '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6734:                       '<label><input type="radio" name="lti_crsinc_add" value="1" onclick="toggleLTI(this.form,'."'crsinc','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6735:                       '<label><input type="radio" name="lti_crsinc_add" value="0" onclick="toggleLTI(this.form,'."'crsinc','add'".');" />'.&mt('No').'</label></span>'."\n".
 6736:                       ('&nbsp;'x4).
 6737:                       '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 6738:                       ('&nbsp;'x2).
 6739:                       '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 6740:                       '<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".
 6741:                       '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 6742:                       '</td>'."\n".
 6743:                       '</tr>'."\n";
 6744:         $itemcount ++;
 6745:     }
 6746:     $$rowtotal += $itemcount;
 6747:     return $datatable;
 6748: }
 6749: 
 6750: sub lti_names {
 6751:     my %lt = &Apache::lonlocal::texthash(
 6752:                                           'version'   => 'LTI Version',
 6753:                                           'url'       => 'URL',
 6754:                                           'key'       => 'Key',
 6755:                                           'lifetime'  => 'Nonce lifetime (s)',
 6756:                                           'consumer'  => 'Consumer',
 6757:                                           'secret'    => 'Secret',
 6758:                                           'requser'   => "User's identity sent",
 6759:                                           'crsinc'    => "Course's identity sent",
 6760:                                           'email'     => 'Email address',
 6761:                                           'sourcedid' => 'User ID',
 6762:                                           'other'     => 'Other',
 6763:                                           'passback'  => 'Can return grades to Consumer:',
 6764:                                           'roster'    => 'Can retrieve roster from Consumer:',
 6765:                                           'topmenu'   => 'Display LON-CAPA page header',
 6766:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 6767:                                         );
 6768:     return %lt;
 6769: }
 6770: 
 6771: sub lti_options {
 6772:     my ($num,$current,$itemcount,%lt) = @_;
 6773:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 6774:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 6775:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 6776:     $checked{'storecrs'}{'Y'} = ' checked="checked"';
 6777:     $checked{'makecrs'}{'N'} = ' checked="checked"';
 6778:     $checked{'mapcrstype'} = {};
 6779:     $checked{'makeuser'} = {};
 6780:     $checked{'selfenroll'} = {};
 6781:     $checked{'crssec'} = {};
 6782:     $checked{'crssecsrc'} = {};
 6783:     $checked{'lcauth'} = {};
 6784:     $checked{'menuitem'} = {};
 6785:     if ($num eq 'add') {
 6786:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 6787:     }
 6788:     my $userfieldsty = 'none';
 6789:     my $crsfieldsty = 'none';
 6790:     my $crssecfieldsty = 'none';
 6791:     my $secsrcfieldsty = 'none';
 6792:     my $callbacksty = 'none';
 6793:     my $passbacksty = 'none';
 6794:     my $optionsty = 'block';
 6795:     my $crssty = 'block';
 6796:     my $lcauthparm;
 6797:     my $lcauthparmstyle = 'display:none';
 6798:     my $lcauthparmtext;
 6799:     my $menusty;
 6800:     my $numinrow = 4;
 6801:     my %menutitles = &ltimenu_titles();
 6802: 
 6803:     if (ref($current) eq 'HASH') {
 6804:         if (!$current->{'requser'}) {
 6805:             $optionsty = 'none';
 6806:             $crssty = 'none';
 6807:         } elsif (!$current->{'crsinc'}) {
 6808:             $crssty = 'none';
 6809:         }
 6810:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 6811:             $checked{'mapuser'}{'sourcedid'} = '';
 6812:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 6813:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 6814:             } else {
 6815:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 6816:                 $userfield = $current->{'mapuser'};
 6817:                 $userfieldsty = 'inline-block';
 6818:             }
 6819:         }
 6820:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 6821:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 6822:             if ($current->{'mapcrs'} eq 'context_id') {
 6823:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 6824:             } else {
 6825:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 6826:                 $cidfield = $current->{'mapcrs'};
 6827:                 $crsfieldsty = 'inline-block';
 6828:             }
 6829:         }
 6830:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 6831:             foreach my $type (@{$current->{'mapcrstype'}}) {
 6832:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 6833:             }
 6834:         }
 6835:         if (!$current->{'storecrs'}) {
 6836:             $checked{'storecrs'}{'N'} = $checked{'storecrs'}{'Y'};
 6837:             $checked{'storecrs'}{'Y'} = '';
 6838:         }
 6839:         if ($current->{'makecrs'}) {
 6840:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 6841:         }
 6842:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 6843:             foreach my $role (@{$current->{'makeuser'}}) {
 6844:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 6845:             }
 6846:         }
 6847:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 6848:             $checked{'lcauth'}{$1} = ' checked="checked"';
 6849:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 6850:                 $lcauthparm = $current->{'lcauthparm'};
 6851:                 $lcauthparmstyle = 'display:table-row'; 
 6852:                 if ($current->{'lcauth'} eq 'localauth') {
 6853:                     $lcauthparmtext = &mt('Local auth argument');
 6854:                 } else {
 6855:                     $lcauthparmtext = &mt('Kerberos domain');
 6856:                 }
 6857:             }
 6858:         }
 6859:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 6860:             foreach my $role (@{$current->{'selfenroll'}}) {
 6861:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 6862:             }
 6863:         }
 6864:         if (ref($current->{'maproles'}) eq 'HASH') {
 6865:             %rolemaps = %{$current->{'maproles'}};
 6866:         }
 6867:         if ($current->{'section'} ne '') {
 6868:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 6869:             $crssecfieldsty = 'inline-block';
 6870:             if ($current->{'section'} eq 'course_section_sourcedid') {
 6871:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 6872:             } else {
 6873:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 6874:                 $crssecsrc = $current->{'section'};
 6875:                 $secsrcfieldsty = 'inline-block';
 6876:             }
 6877:         } else {
 6878:             $checked{'crssec'}{'N'} = ' checked="checked"';
 6879:         }
 6880:         if ($current->{'callback'} ne '') {
 6881:             $callback = $current->{'callback'};
 6882:             $checked{'callback'}{'Y'} = ' checked="checked"';
 6883:             $callbacksty = 'inline-block';
 6884:         } else {
 6885:             $checked{'callback'}{'N'} = ' checked="checked"';
 6886:         }
 6887:         if ($current->{'topmenu'}) {
 6888:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 6889:         } else {
 6890:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 6891:         }
 6892:         if ($current->{'inlinemenu'}) {
 6893:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6894:         } else {
 6895:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 6896:         }
 6897:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 6898:             $menusty = 'inline-block';
 6899:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 6900:                 foreach my $item (@{$current->{'lcmenu'}}) {
 6901:                     if (exists($menutitles{$item})) {
 6902:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 6903:                     }
 6904:                 }
 6905:             }
 6906:         } else {
 6907:             $menusty = 'none';
 6908:         }
 6909:     } else {
 6910:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 6911:         $checked{'crssec'}{'N'} = ' checked="checked"';
 6912:         $checked{'callback'}{'N'} = ' checked="checked"';
 6913:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 6914:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 6915:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 6916:         $menusty = 'inline-block'; 
 6917:     }
 6918:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 6919:     my %coursetypetitles = &Apache::lonlocal::texthash (
 6920:                                official   => 'Official',
 6921:                                unofficial => 'Unofficial',
 6922:                                community  => 'Community',
 6923:                                textbook   => 'Textbook',
 6924:                                placement  => 'Placement Test',
 6925:                                lti        => 'LTI Provider',
 6926:     );
 6927:     my @authtypes = ('internal','krb4','krb5','localauth');
 6928:     my %shortauth = (
 6929:                      internal => 'int',
 6930:                      krb4 => 'krb4',
 6931:                      krb5 => 'krb5',
 6932:                      localauth  => 'loc'
 6933:                     );
 6934:     my %authnames = &authtype_names();
 6935:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6936:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6937:     my @courseroles = ('cc','in','ta','ep','st');
 6938:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6939:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6940:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6941:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6942:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6943:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6944:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6945:     my $output = '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Logout options').'</legend>'.
 6946:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback to logout LON-CAPA on log out from Consumer').':&nbsp;'.
 6947:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6948:                  $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6949:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6950:                  $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6951:                  '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6952:                  '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6953:                  '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6954:                  '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6955:                  '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6956:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6957:     foreach my $option ('sourcedid','email','other') {
 6958:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6959:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6960:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6961:     }
 6962:     $output .= '</span></div>'.
 6963:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6964:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6965:                'value="'.$userfield.'" /></div></fieldset>'.
 6966:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6967:     foreach my $ltirole (@ltiroles) {
 6968:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6969:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 6970:     }
 6971:     $output .= '</fieldset>'.
 6972:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 6973:                '<table>'.
 6974:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 6975:                '</table>'.
 6976:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 6977:                '<td class="LC_left_item">';
 6978:     foreach my $auth ('lti',@authtypes) {
 6979:         my $authtext;
 6980:         if ($auth eq 'lti') {
 6981:             $authtext = &mt('None');
 6982:         } else {
 6983:             $authtext = $authnames{$shortauth{$auth}};
 6984:         }
 6985:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 6986:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 6987:                    $authtext.'</label></span> &nbsp;';
 6988:     }
 6989:     $output .= '</td></tr>'.
 6990:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 6991:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 6992:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 6993:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 6994:                '</table></fieldset>'.
 6995:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.
 6996:                &mt('LON-CAPA menu items (Course Coordinator can override)').'</legend>'.
 6997:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 6998:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 6999:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7000:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 7001:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 7002:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7003:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 7004:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 7005:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7006:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 7007:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 7008:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7009:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 7010:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 7011:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 7012:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 7013:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 7014:                    ('&nbsp;'x2);
 7015:     }
 7016:     $output .= '</span></div></fieldset>'.
 7017:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 7018:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 7019:                &mt('Unique course identifier').':&nbsp;';
 7020:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 7021:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 7022:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 7023:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 7024:     }
 7025:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 7026:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 7027:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7028:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 7029:     foreach my $type (@coursetypes) {
 7030:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 7031:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 7032:                    ('&nbsp;'x2);
 7033:     }
 7034:     $output .= '</span><br /><br />'.
 7035:                '<span class="LC_nobreak">'.&mt('Store mapping of course identifier to LON-CAPA CourseID').':&nbsp;'.
 7036:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="0"'.
 7037:                $checked{'storecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7038:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="1"'.
 7039:                $checked{'storecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7040:                '</fieldset>'.
 7041:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 7042:     foreach my $ltirole (@lticourseroles) {
 7043:         my ($selected,$selectnone);
 7044:         if ($rolemaps{$ltirole} eq '') {
 7045:             $selectnone = ' selected="selected"';
 7046:         }
 7047:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 7048:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 7049:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 7050:         foreach my $role (@courseroles) {
 7051:             unless ($selectnone) {
 7052:                 if ($rolemaps{$ltirole} eq $role) {
 7053:                     $selected = ' selected="selected"';
 7054:                 } else {
 7055:                     $selected = '';
 7056:                 }
 7057:             }
 7058:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 7059:                        &Apache::lonnet::plaintext($role,'Course').
 7060:                        '</option>';
 7061:         }
 7062:         $output .= '</select></td>';
 7063:     }
 7064:     $output .= '</tr></table></fieldset>'.
 7065:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Creating courses').'</legend>'.
 7066:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 7067:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 7068:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7069:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 7070:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7071:                '</fieldset>'.
 7072:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 7073:     foreach my $lticrsrole (@lticourseroles) {
 7074:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 7075:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 7076:     }
 7077:     $output .= '</fieldset>'.
 7078:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Course options').'</legend>'.
 7079:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 7080:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 7081:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7082:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 7083:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 7084:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 7085:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 7086:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 7087:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 7088:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 7089:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 7090:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 7091:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 7092:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 7093:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 7094:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 7095:     foreach my $extra ('roster','passback') {
 7096:         my $checkedon = '';
 7097:         my $checkedoff = ' checked="checked"';
 7098:         if ($extra eq 'passback') {
 7099:             $pb1p1chk = ' checked="checked"';
 7100:             $pb1p0chk = '';
 7101:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 7102:         } else {
 7103:             $onclickpb = ''; 
 7104:         }
 7105:         if (ref($current) eq 'HASH') {
 7106:             if (($current->{$extra})) {
 7107:                 $checkedon = $checkedoff;
 7108:                 $checkedoff = '';
 7109:                 if ($extra eq 'passback') {
 7110:                     $passbacksty = 'inline-block';
 7111:                 }
 7112:                 if ($current->{'passbackformat'} eq '1.0') {
 7113:                     $pb1p0chk =  ' checked="checked"';
 7114:                     $pb1p1chk = '';
 7115:                 }
 7116:             }
 7117:         }
 7118:         $output .= $lt{$extra}.'&nbsp;'.
 7119:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 7120:                    &mt('No').'</label>'.('&nbsp;'x2).
 7121:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 7122:                    &mt('Yes').'</label><br />';
 7123:     }
 7124:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 7125:                '<span class="LC_nobreak">'.&mt('Grade format').
 7126:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 7127:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 7128:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 7129:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 7130:                '<div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>';
 7131:     $output .= '</span></div></fieldset>';
 7132: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 7133: #
 7134: #    $output .= '</fieldset>'.
 7135: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 7136:     return $output;
 7137: }
 7138: 
 7139: sub ltimenu_titles {
 7140:     return &Apache::lonlocal::texthash(
 7141:                                         fullname    => 'Full name',
 7142:                                         coursetitle => 'Course title',
 7143:                                         role        => 'Role',
 7144:                                         logout      => 'Logout',
 7145:                                         grades      => 'Grades',
 7146:     );
 7147: }
 7148: 
 7149: sub check_switchserver {
 7150:     my ($home) = @_;
 7151:     my $switchserver;
 7152:     if ($home ne '') {
 7153:         my $allowed;
 7154:         my @ids=&Apache::lonnet::current_machine_ids();
 7155:         foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 7156:         if (!$allowed) {
 7157:             $switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role='.
 7158:                           &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 7159:                           '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 7160:         }
 7161:     }
 7162:     return $switchserver;
 7163: }
 7164: 
 7165: sub print_coursedefaults {
 7166:     my ($position,$dom,$settings,$rowtotal) = @_;
 7167:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 7168:     my $itemcount = 1;
 7169:     my %choices =  &Apache::lonlocal::texthash (
 7170:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 7171:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 7172:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 7173:         coursecredits        => 'Credits can be specified for courses',
 7174:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 7175:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 7176:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 7177:         texengine            => 'Default method to display mathematics',
 7178:         postsubmit           => 'Disable submit button/keypress following student submission',
 7179:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 7180:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 7181:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 7182:     );
 7183:     my %staticdefaults = (
 7184:                            anonsurvey_threshold => 10,
 7185:                            uploadquota          => 500,
 7186:                            postsubmit           => 60,
 7187:                            mysqltables          => 172800,
 7188:                          );
 7189:     if ($position eq 'top') {
 7190:         %defaultchecked = (
 7191:                             'canuse_pdfforms' => 'off',
 7192:                             'uselcmath'       => 'on',
 7193:                             'usejsme'         => 'on',
 7194:                             'inline_chem'     => 'on',
 7195:                             'canclone'        => 'none',
 7196:                           );
 7197:         @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem');
 7198:         my $deftex = $Apache::lonnet::deftex;
 7199:         if (ref($settings) eq 'HASH') {
 7200:             if ($settings->{'texengine'}) {
 7201:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 7202:                     $deftex = $settings->{'texengine'};
 7203:                 }
 7204:             }
 7205:         }
 7206:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7207:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 7208:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 7209:                        '</span></td><td class="LC_right_item">'.
 7210:                        '<select name="texengine">'."\n";
 7211:         my %texoptions = (
 7212:                             MathJax  => 'MathJax',
 7213:                             mimetex  => &mt('Convert to Images'),
 7214:                             tth      => &mt('TeX to HTML'),
 7215:                          );
 7216:         foreach my $renderer ('MathJax','mimetex','tth') {
 7217:             my $selected = '';
 7218:             if ($renderer eq $deftex) {
 7219:                 $selected = ' selected="selected"';
 7220:             }
 7221:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 7222:         }
 7223:         $mathdisp .= '</select></td></tr>'."\n";
 7224:         $itemcount ++;
 7225:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 7226:                                                      \%choices,$itemcount);
 7227:         $datatable = $mathdisp.$datatable;
 7228:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7229:         $datatable .=
 7230:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 7231:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 7232:             '</span></td><td class="LC_left_item">';
 7233:         my $currcanclone = 'none';
 7234:         my $onclick;
 7235:         my @cloneoptions = ('none','domain');
 7236:         my %clonetitles = &Apache::lonlocal::texthash (
 7237:                              none     => 'No additional course requesters',
 7238:                              domain   => "Any course requester in course's domain",
 7239:                              instcode => 'Course requests for official courses ...',
 7240:                           );
 7241:         my (%codedefaults,@code_order,@posscodes);
 7242:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 7243:                                                     \@code_order) eq 'ok') {
 7244:             if (@code_order > 0) {
 7245:                 push(@cloneoptions,'instcode');
 7246:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 7247:             }
 7248:         }
 7249:         if (ref($settings) eq 'HASH') {
 7250:             if ($settings->{'canclone'}) {
 7251:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 7252:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 7253:                         if (@code_order > 0) {
 7254:                             $currcanclone = 'instcode';
 7255:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 7256:                         }
 7257:                     }
 7258:                 } elsif ($settings->{'canclone'} eq 'domain') {
 7259:                     $currcanclone = $settings->{'canclone'};
 7260:                 }
 7261:             }
 7262:         }
 7263:         foreach my $option (@cloneoptions) {
 7264:             my ($checked,$additional);
 7265:             if ($currcanclone eq $option) {
 7266:                 $checked = ' checked="checked"';
 7267:             }
 7268:             if ($option eq 'instcode') {
 7269:                 if (@code_order) {
 7270:                     my $show = 'none';
 7271:                     if ($checked) {
 7272:                         $show = 'block';
 7273:                     }
 7274:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 7275:                                   &mt('Institutional codes for new and cloned course have identical:').
 7276:                                   '<br />';
 7277:                     foreach my $item (@code_order) {
 7278:                         my $codechk;
 7279:                         if ($checked) {
 7280:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 7281:                                 $codechk = ' checked="checked"';
 7282:                             }
 7283:                         }
 7284:                         $additional .= '<label>'.
 7285:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 7286:                                        $item.'</label>';
 7287:                     }
 7288:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 7289:                 }
 7290:             }
 7291:             $datatable .=
 7292:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 7293:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 7294:                 '</label>&nbsp;'.$additional.'</span><br />';
 7295:         }
 7296:         $datatable .= '</td>'.
 7297:                       '</tr>';
 7298:         $itemcount ++;
 7299:     } else {
 7300:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7301:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 7302:         my $currusecredits = 0;
 7303:         my $postsubmitclient = 1;
 7304:         my $ltiauth = 0;
 7305:         my @types = ('official','unofficial','community','textbook','placement');
 7306:         if (ref($settings) eq 'HASH') {
 7307:             if ($settings->{'ltiauth'}) {
 7308:                 $ltiauth = 1;
 7309:             }
 7310:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 7311:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 7312:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 7313:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 7314:                 }
 7315:             }
 7316:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 7317:                 foreach my $type (@types) {
 7318:                     next if ($type eq 'community');
 7319:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 7320:                     if ($defcredits{$type} ne '') {
 7321:                         $currusecredits = 1;
 7322:                     }
 7323:                 }
 7324:             }
 7325:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 7326:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 7327:                     $postsubmitclient = 0;
 7328:                     foreach my $type (@types) {
 7329:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7330:                     }
 7331:                 } else {
 7332:                     foreach my $type (@types) {
 7333:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 7334:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 7335:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 7336:                             } else {
 7337:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7338:                             }
 7339:                         } else {
 7340:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7341:                         }
 7342:                     }
 7343:                 }
 7344:             } else {
 7345:                 foreach my $type (@types) {
 7346:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7347:                 }
 7348:             }
 7349:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 7350:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 7351:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 7352:                 }
 7353:             } else {
 7354:                 foreach my $type (@types) {
 7355:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 7356:                 }
 7357:             }
 7358:         } else {
 7359:             foreach my $type (@types) {
 7360:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7361:             }
 7362:         }
 7363:         if (!$currdefresponder) {
 7364:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 7365:         } elsif ($currdefresponder < 1) {
 7366:             $currdefresponder = 1;
 7367:         }
 7368:         foreach my $type (@types) {
 7369:             if ($curruploadquota{$type} eq '') {
 7370:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 7371:             }
 7372:         }
 7373:         $datatable .=
 7374:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7375:                 $choices{'anonsurvey_threshold'}.
 7376:                 '</span></td>'.
 7377:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 7378:                 '<input type="text" name="anonsurvey_threshold"'.
 7379:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 7380:                 '</td></tr>'."\n";
 7381:         $itemcount ++;
 7382:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7383:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7384:                       $choices{'uploadquota'}.
 7385:                       '</span></td>'.
 7386:                       '<td style="text-align: right" class="LC_right_item">'.
 7387:                       '<table><tr>';
 7388:         foreach my $type (@types) {
 7389:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7390:                            '<input type="text" name="uploadquota_'.$type.'"'.
 7391:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 7392:         }
 7393:         $datatable .= '</tr></table></td></tr>'."\n";
 7394:         $itemcount ++;
 7395:         my $onclick = "toggleDisplay(this.form,'credits');";
 7396:         my $display = 'none';
 7397:         if ($currusecredits) {
 7398:             $display = 'block';
 7399:         }
 7400:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 7401:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 7402:         foreach my $type (@types) {
 7403:             next if ($type eq 'community');
 7404:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7405:                            '<input type="text" name="'.$type.'_credits"'.
 7406:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 7407:         }
 7408:         $additional .= '</tr></table></div>'."\n";
 7409:         %defaultchecked = ('coursecredits' => 'off');
 7410:         @toggles = ('coursecredits');
 7411:         my $current = {
 7412:                         'coursecredits' => $currusecredits,
 7413:                       };
 7414:         (my $table,$itemcount) =
 7415:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7416:                                \%choices,$itemcount,$onclick,$additional,'left');
 7417:         $datatable .= $table;
 7418:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 7419:         my $display = 'none';
 7420:         if ($postsubmitclient) {
 7421:             $display = 'block';
 7422:         }
 7423:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 7424:                       &mt('Number of seconds submit is disabled').'<br />'.
 7425:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 7426:                       '<table><tr>';
 7427:         foreach my $type (@types) {
 7428:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7429:                            '<input type="text" name="'.$type.'_timeout" value="'.
 7430:                            $deftimeout{$type}.'" size="5" /></td>';
 7431:         }
 7432:         $additional .= '</tr></table></div>'."\n";
 7433:         %defaultchecked = ('postsubmit' => 'on');
 7434:         @toggles = ('postsubmit');
 7435:         $current = {
 7436:                        'postsubmit' => $postsubmitclient,
 7437:                    };
 7438:         ($table,$itemcount) =
 7439:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7440:                                \%choices,$itemcount,$onclick,$additional,'left');
 7441:         $datatable .= $table;
 7442:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7443:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7444:                       $choices{'mysqltables'}.
 7445:                       '</span></td>'.
 7446:                       '<td style="text-align: right" class="LC_right_item">'.
 7447:                       '<table><tr>';
 7448:         foreach my $type (@types) {
 7449:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7450:                            '<input type="text" name="mysqltables_'.$type.'"'.
 7451:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 7452:         }
 7453:         $datatable .= '</tr></table></td></tr>'."\n";
 7454:         $itemcount ++;
 7455:         %defaultchecked = ('ltiauth' => 'off');
 7456:         @toggles = ('ltiauth');
 7457:         $current = {
 7458:                        'ltiauth' => $ltiauth,
 7459:                    };
 7460:         ($table,$itemcount) =
 7461:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7462:                                \%choices,$itemcount,undef,undef,'left');
 7463:         $datatable .= $table;
 7464:         $itemcount ++;
 7465:     }
 7466:     $$rowtotal += $itemcount;
 7467:     return $datatable;
 7468: }
 7469: 
 7470: sub print_selfenrollment {
 7471:     my ($position,$dom,$settings,$rowtotal) = @_;
 7472:     my ($css_class,$datatable);
 7473:     my $itemcount = 1;
 7474:     my @types = ('official','unofficial','community','textbook','placement');
 7475:     if (($position eq 'top') || ($position eq 'middle')) {
 7476:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 7477:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 7478:         my @rows;
 7479:         my $key;
 7480:         if ($position eq 'top') {
 7481:             $key = 'admin'; 
 7482:             if (ref($rowsref) eq 'ARRAY') {
 7483:                 @rows = @{$rowsref};
 7484:             }
 7485:         } elsif ($position eq 'middle') {
 7486:             $key = 'default';
 7487:             @rows = ('types','registered','approval','limit');
 7488:         }
 7489:         foreach my $row (@rows) {
 7490:             if (defined($titlesref->{$row})) {
 7491:                 $itemcount ++;
 7492:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7493:                 $datatable .= '<tr'.$css_class.'>'.
 7494:                               '<td>'.$titlesref->{$row}.'</td>'.
 7495:                               '<td class="LC_left_item">'.
 7496:                               '<table><tr>';
 7497:                 my (%current,%currentcap);
 7498:                 if (ref($settings) eq 'HASH') {
 7499:                     if (ref($settings->{$key}) eq 'HASH') {
 7500:                         foreach my $type (@types) {
 7501:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7502:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 7503:                             }
 7504:                             if (($row eq 'limit') && ($key eq 'default')) {
 7505:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7506:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 7507:                                 }
 7508:                             }
 7509:                         }
 7510:                     }
 7511:                 }
 7512:                 my %roles = (
 7513:                              '0' => &Apache::lonnet::plaintext('dc'),
 7514:                             ); 
 7515:             
 7516:                 foreach my $type (@types) {
 7517:                     unless (($row eq 'registered') && ($key eq 'default')) {
 7518:                         $datatable .= '<th>'.&mt($type).'</th>';
 7519:                     }
 7520:                 }
 7521:                 unless (($row eq 'registered') && ($key eq 'default')) {
 7522:                     $datatable .= '</tr><tr>';
 7523:                 }
 7524:                 foreach my $type (@types) {
 7525:                     if ($type eq 'community') {
 7526:                         $roles{'1'} = &mt('Community personnel');
 7527:                     } else {
 7528:                         $roles{'1'} = &mt('Course personnel');
 7529:                     }
 7530:                     $datatable .= '<td style="vertical-align: top">';
 7531:                     if ($position eq 'top') {
 7532:                         my %checked;
 7533:                         if ($current{$type} eq '0') {
 7534:                             $checked{'0'} = ' checked="checked"';
 7535:                         } else {
 7536:                             $checked{'1'} = ' checked="checked"';
 7537:                         }
 7538:                         foreach my $role ('1','0') {
 7539:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7540:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 7541:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 7542:                                           $roles{$role}.'</label></span> ';
 7543:                         }
 7544:                     } else {
 7545:                         if ($row eq 'types') {
 7546:                             my %checked;
 7547:                             if ($current{$type} =~ /^(all|dom)$/) {
 7548:                                 $checked{$1} = ' checked="checked"';
 7549:                             } else {
 7550:                                 $checked{''} = ' checked="checked"';
 7551:                             }
 7552:                             foreach my $val ('','dom','all') {
 7553:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7554:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7555:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7556:                             }
 7557:                         } elsif ($row eq 'registered') {
 7558:                             my %checked;
 7559:                             if ($current{$type} eq '1') {
 7560:                                 $checked{'1'} = ' checked="checked"';
 7561:                             } else {
 7562:                                 $checked{'0'} = ' checked="checked"';
 7563:                             }
 7564:                             foreach my $val ('0','1') {
 7565:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7566:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7567:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7568:                             }
 7569:                         } elsif ($row eq 'approval') {
 7570:                             my %checked;
 7571:                             if ($current{$type} =~ /^([12])$/) {
 7572:                                 $checked{$1} = ' checked="checked"';
 7573:                             } else {
 7574:                                 $checked{'0'} = ' checked="checked"';
 7575:                             }
 7576:                             for my $val (0..2) {
 7577:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7578:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7579:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7580:                             }
 7581:                         } elsif ($row eq 'limit') {
 7582:                             my %checked;
 7583:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 7584:                                 $checked{$1} = ' checked="checked"';
 7585:                             } else {
 7586:                                 $checked{'none'} = ' checked="checked"';
 7587:                             }
 7588:                             my $cap;
 7589:                             if ($currentcap{$type} =~ /^\d+$/) {
 7590:                                 $cap = $currentcap{$type};
 7591:                             }
 7592:                             foreach my $val ('none','allstudents','selfenrolled') {
 7593:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7594:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7595:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7596:                             }
 7597:                             $datatable .= '<br />'.
 7598:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 7599:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 7600:                                           '</span>'; 
 7601:                         }
 7602:                     }
 7603:                     $datatable .= '</td>';
 7604:                 }
 7605:                 $datatable .= '</tr>';
 7606:             }
 7607:             $datatable .= '</table></td></tr>';
 7608:         }
 7609:     } elsif ($position eq 'bottom') {
 7610:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 7611:     }
 7612:     $$rowtotal += $itemcount;
 7613:     return $datatable;
 7614: }
 7615: 
 7616: sub print_validation_rows {
 7617:     my ($caller,$dom,$settings,$rowtotal) = @_;
 7618:     my ($itemsref,$namesref,$fieldsref);
 7619:     if ($caller eq 'selfenroll') { 
 7620:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 7621:     } elsif ($caller eq 'requestcourses') {
 7622:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7623:     }
 7624:     my %currvalidation;
 7625:     if (ref($settings) eq 'HASH') {
 7626:         if (ref($settings->{'validation'}) eq 'HASH') {
 7627:             %currvalidation = %{$settings->{'validation'}};
 7628:         }
 7629:     }
 7630:     my $datatable;
 7631:     my $itemcount = 0;
 7632:     foreach my $item (@{$itemsref}) {
 7633:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7634:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7635:                       $namesref->{$item}.
 7636:                       '</span></td>'.
 7637:                       '<td class="LC_left_item">';
 7638:         if (($item eq 'url') || ($item eq 'button')) {
 7639:             $datatable .= '<span class="LC_nobreak">'.
 7640:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 7641:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 7642:         } elsif ($item eq 'fields') {
 7643:             my @currfields;
 7644:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 7645:                 @currfields = @{$currvalidation{$item}};
 7646:             }
 7647:             foreach my $field (@{$fieldsref}) {
 7648:                 my $check = '';
 7649:                 if (grep(/^\Q$field\E$/,@currfields)) {
 7650:                     $check = ' checked="checked"';
 7651:                 }
 7652:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7653:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 7654:                               ' value="'.$field.'"'.$check.' />'.$field.
 7655:                               '</label></span> ';
 7656:             }
 7657:         } elsif ($item eq 'markup') {
 7658:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 7659:                            $currvalidation{$item}.
 7660:                               '</textarea>';
 7661:         }
 7662:         $datatable .= '</td></tr>'."\n";
 7663:         if (ref($rowtotal)) {
 7664:             $itemcount ++;
 7665:         }
 7666:     }
 7667:     if ($caller eq 'requestcourses') {
 7668:         my %currhash;
 7669:         if (ref($settings) eq 'HASH') {
 7670:             if (ref($settings->{'validation'}) eq 'HASH') {
 7671:                 if ($settings->{'validation'}{'dc'} ne '') {
 7672:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 7673:                 }
 7674:             }
 7675:         }
 7676:         my $numinrow = 2;
 7677:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 7678:                                                        'validationdc',%currhash);
 7679:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7680:         $datatable .= '<tr'.$css_class.'><td>';
 7681:         if ($numdc > 1) {
 7682:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 7683:         } else {
 7684:             $datatable .=  &mt('Course creation processed as: ');
 7685:         }
 7686:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 7687:         $itemcount ++;
 7688:     }
 7689:     if (ref($rowtotal)) {
 7690:         $$rowtotal += $itemcount;
 7691:     }
 7692:     return $datatable;
 7693: }
 7694: 
 7695: sub print_privacy {
 7696:     my ($position,$dom,$settings,$rowtotal) = @_;
 7697:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 7698:     my $itemcount = 0;
 7699:     unless ($position eq 'top') {
 7700:         @items = ('domain','author','course','community');
 7701:         %names = &Apache::lonlocal::texthash (
 7702:                      domain => 'Assigned domain role(s)',
 7703:                      author => 'Assigned co-author role(s)',
 7704:                      course => 'Assigned course role(s)',
 7705:                      community => 'Assigned community role',
 7706:                  );
 7707:         $numinrow = 4;
 7708:         ($othertitle,$usertypes,$types) =
 7709:             &Apache::loncommon::sorted_inst_types($dom);
 7710:     }
 7711:     if (($position eq 'top') || ($position eq 'middle')) {
 7712:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7713:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7714:         if ($position eq 'top') {
 7715:             my %curr;
 7716:             my @options = ('none','user','domain','auto');
 7717:             my %titles = &Apache::lonlocal::texthash (
 7718:                 none   => 'Not allowed',
 7719:                 user   => 'User authorizes',
 7720:                 domain => 'DC authorizes',
 7721:                 auto   => 'Unrestricted',
 7722:                 instdom => 'Other domain shares institution/provider',
 7723:                 extdom => 'Other domain has different institution/provider',
 7724:             );
 7725:             my %names = &Apache::lonlocal::texthash (
 7726:                 domain => 'Domain role',
 7727:                 author => 'Co-author role',
 7728:                 course => 'Course role',
 7729:                 community => 'Community role',
 7730:             );
 7731:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7732:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7733:             foreach my $domtype ('instdom','extdom') {
 7734:                 my (%checked,$skip);
 7735:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7736:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 7737:                               '<td class="LC_left_item">';
 7738:                 if ($domtype eq 'instdom') {
 7739:                     unless (@instdoms > 1) {
 7740:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 7741:                         $skip = 1;
 7742:                     }
 7743:                 } elsif ($domtype eq 'extdom') {
 7744:                     if (keys(%by_location) == 0) {
 7745:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 7746:                         $skip = 1;
 7747:                     }
 7748:                 }
 7749:                 unless ($skip) {
 7750:                     foreach my $roletype ('domain','author','course','community') {
 7751:                         $checked{'auto'} = ' checked="checked"';
 7752:                         if (ref($settings) eq 'HASH') {
 7753:                             if (ref($settings->{approval}) eq 'HASH') {
 7754:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 7755:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 7756:                                         $checked{$1} = ' checked="checked"';
 7757:                                         $checked{'auto'} = '';
 7758:                                     }
 7759:                                 }
 7760:                             }
 7761:                         }
 7762:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 7763:                         foreach my $option (@options) {
 7764:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7765:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 7766:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7767:                                           '</label></span>&nbsp; ';
 7768:                         }
 7769:                         $datatable .= '</fieldset>';
 7770:                     }
 7771:                 }
 7772:                 $datatable .= '</td></tr>';
 7773:                 $itemcount ++;
 7774:             }
 7775:         } elsif ($position eq 'middle') {
 7776:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7777:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7778:                     foreach my $item (@{$types}) {
 7779:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 7780:                                                                $numinrow,$itemcount,'','','','','',
 7781:                                                                '',$usertypes->{$item});
 7782:                         $itemcount ++;
 7783:                     }
 7784:                 }
 7785:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 7786:                                                        $numinrow,$itemcount,'','','','','',
 7787:                                                        '',$othertitle);
 7788:                 $itemcount ++;
 7789:             } else {
 7790:                 my (@insttypes,%insttitles);
 7791:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7792:                     @insttypes = @{$types};
 7793:                     %insttitles = %{$usertypes};
 7794:                 }
 7795:                 foreach my $item (@insttypes,'default') {
 7796:                     my $title;
 7797:                     if ($item eq 'default') {
 7798:                         $title = $othertitle;
 7799:                     } else {
 7800:                         $title = $insttitles{$item};
 7801:                     }
 7802:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7803:                     $datatable .= '<tr'.$css_class.'>'.
 7804:                                   '<td class="LC_left_item">'.$title.'</td>'.
 7805:                                   '<td class="LC_left_item">'.
 7806:                                   &mt('Nothing to set here, as there are no other domains').
 7807:                                   '</td></tr>';
 7808:                     $itemcount ++;
 7809:                 }
 7810:             }
 7811:         }
 7812:     } else {
 7813:         my $prefix;
 7814:         if ($position eq 'lower') {
 7815:             $prefix = 'priv';
 7816:         } else {
 7817:             $prefix = 'unpriv';
 7818:         }
 7819:         foreach my $item (@items) {
 7820:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 7821:                                                    $numinrow,$itemcount,'','','','','',
 7822:                                                    '',$names{$item});
 7823:             $itemcount ++;
 7824:         }
 7825:     }
 7826:     if (ref($rowtotal)) {
 7827:         $$rowtotal += $itemcount;
 7828:     }
 7829:     return $datatable;
 7830: }
 7831: 
 7832: sub print_passwords {
 7833:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 7834:     my ($datatable,$css_class);
 7835:     my $itemcount = 0;
 7836:     my %titles = &Apache::lonlocal::texthash (
 7837:         captcha        => '"Forgot Password" CAPTCHA validation',
 7838:         link           => 'Reset link expiration (hours)',
 7839:         case           => 'Case-sensitive usernames/e-mail',
 7840:         prelink        => 'Information required (form 1)',
 7841:         postlink       => 'Information required (form 2)',
 7842:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 7843:         customtext     => 'Domain specific text (HTML)',
 7844:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 7845:         intauth_check  => 'Check bcrypt cost if authenticated',
 7846:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 7847:         permanent      => 'Permanent e-mail address',
 7848:         critical       => 'Critical notification address',
 7849:         notify         => 'Notification address',
 7850:         min            => 'Minimum password length',
 7851:         max            => 'Maximum password length',
 7852:         chars          => 'Required characters',
 7853:         expire         => 'Password expiration (days)',
 7854:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 7855:     );
 7856:     if ($position eq 'top') {
 7857:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7858:         my $shownlinklife = 2;
 7859:         my $prelink = 'both';
 7860:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 7861:         if (ref($settings) eq 'HASH') {
 7862:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 7863:                 $shownlinklife = $settings->{resetlink};
 7864:             }
 7865:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 7866:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 7867:             }
 7868:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 7869:                 $prelink = $settings->{resetprelink};
 7870:             }
 7871:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 7872:                 %postlink = %{$settings->{resetpostlink}};
 7873:             }
 7874:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 7875:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 7876:             }
 7877:             if ($settings->{resetremove}) {
 7878:                 $nostdtext = 1;
 7879:             }
 7880:             if ($settings->{resetcustom}) {
 7881:                 $customurl = $settings->{resetcustom};
 7882:             }
 7883:         } else {
 7884:             if (ref($types) eq 'ARRAY') {
 7885:                 foreach my $item (@{$types}) {
 7886:                     $casesens{$item} = 1;
 7887:                     $postlink{$item} = ['username','email'];
 7888:                 }
 7889:             }
 7890:             $casesens{'default'} = 1;
 7891:             $postlink{'default'} = ['username','email'];
 7892:             $prelink = 'both';
 7893:             %emailsrc = (
 7894:                           permanent => 1,
 7895:                           critical  => 1,
 7896:                           notify    => 1,
 7897:             );
 7898:         }
 7899:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 7900:         $itemcount ++;
 7901:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7902:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 7903:                       '<td class="LC_left_item">'.
 7904:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 7905:                       'name="passwords_link" size="3" /></td></tr>';
 7906:         $itemcount ++;
 7907:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7908:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 7909:                       '<td class="LC_left_item">';
 7910:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7911:             foreach my $item (@{$types}) {
 7912:                 my $checkedcase;
 7913:                 if ($casesens{$item}) {
 7914:                     $checkedcase = ' checked="checked"';
 7915:                 }
 7916:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7917:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 7918:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 7919:                               '</span>&nbsp;&nbsp; ';
 7920:             }
 7921:         }
 7922:         my $checkedcase;
 7923:         if ($casesens{'default'}) {
 7924:             $checkedcase = ' checked="checked"';
 7925:         }
 7926:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7927:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 7928:                       $othertitle.'</label></span></td>';
 7929:         $itemcount ++;
 7930:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7931:         my %checkedpre = (
 7932:                              both => ' checked="checked"',
 7933:                              either => '',
 7934:                          );
 7935:         if ($prelink eq 'either') {
 7936:             $checkedpre{either} = ' checked="checked"';
 7937:             $checkedpre{both} = '';
 7938:         }
 7939:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 7940:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7941:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 7942:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 7943:                       '<span class="LC_nobreak"><label>'.
 7944:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 7945:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 7946:         $itemcount ++;
 7947:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7948:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 7949:                       '<td class="LC_left_item">';
 7950:         my %postlinked;
 7951:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7952:             foreach my $item (@{$types}) {
 7953:                 undef(%postlinked);
 7954:                 $datatable .= '<fieldset style="display: inline-block;">'.
 7955:                               '<legend>'.$usertypes->{$item}.'</legend>';
 7956:                 if (ref($postlink{$item}) eq 'ARRAY') {
 7957:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 7958:                 }
 7959:                 foreach my $field ('email','username') {
 7960:                     my $checked;
 7961:                     if ($postlinked{$field}) {
 7962:                         $checked = ' checked="checked"';
 7963:                     }
 7964:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7965:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 7966:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 7967:                                   '<span>&nbsp;&nbsp; ';
 7968:                 }
 7969:                 $datatable .= '</fieldset>';
 7970:             }
 7971:         }
 7972:         if (ref($postlink{'default'}) eq 'ARRAY') {
 7973:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 7974:         }
 7975:         $datatable .= '<fieldset style="display: inline-block;">'.
 7976:                       '<legend>'.$othertitle.'</legend>';
 7977:         foreach my $field ('email','username') {
 7978:             my $checked;
 7979:             if ($postlinked{$field}) {
 7980:                 $checked = ' checked="checked"';
 7981:             }
 7982:             $datatable .= '<span class="LC_nobreak"><label>'.
 7983:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 7984:                           $field.'"'.$checked.' />'.$field.'</label>'.
 7985:                           '<span>&nbsp;&nbsp; ';
 7986:         }
 7987:         $datatable .= '</fieldset></td></tr>';
 7988:         $itemcount ++;
 7989:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7990:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 7991:                       '<td class="LC_left_item">';
 7992:         foreach my $type ('permanent','critical','notify') {
 7993:             my $checkedemail;
 7994:             if ($emailsrc{$type}) {
 7995:                 $checkedemail = ' checked="checked"';
 7996:             }
 7997:             $datatable .= '<span class="LC_nobreak"><label>'.
 7998:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 7999:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 8000:                           '<span>&nbsp;&nbsp; ';
 8001:         }
 8002:         $datatable .= '</td></tr>';
 8003:         $itemcount ++;
 8004:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8005:         my $switchserver = &check_switchserver($dom,$confname);
 8006:         my ($showstd,$noshowstd);
 8007:         if ($nostdtext) {
 8008:             $noshowstd = ' checked="checked"';
 8009:         } else {
 8010:             $showstd = ' checked="checked"';
 8011:         }
 8012:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 8013:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8014:                       &mt('Retain standard text:').
 8015:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 8016:                       &mt('Yes').'</label>'.'&nbsp;'.
 8017:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 8018:                       &mt('No').'</label></span><br />'.
 8019:                       '<span class="LC_fontsize_small">'.
 8020:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 8021:                       &mt('Include custom text:');
 8022:         if ($customurl) {
 8023:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 8024:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8025:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 8026:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 8027:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 8028:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 8029:         }
 8030:         if ($switchserver) {
 8031:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 8032:         } else {
 8033:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8034:                          '<input type="file" name="passwords_customfile" /></span>';
 8035:         }
 8036:         $datatable .= '</td></tr>';
 8037:     } elsif ($position eq 'middle') {
 8038:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 8039:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 8040:         my %defaults;
 8041:         if (ref($domconf{'defaults'}) eq 'HASH') {
 8042:             %defaults = %{$domconf{'defaults'}};
 8043:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 8044:                 $defaults{'intauth_cost'} = 10;
 8045:             }
 8046:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 8047:                 $defaults{'intauth_check'} = 0;
 8048:             }
 8049:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 8050:                 $defaults{'intauth_switch'} = 0;
 8051:             }
 8052:         } else {
 8053:             %defaults = (
 8054:                           'intauth_cost'   => 10,
 8055:                           'intauth_check'  => 0,
 8056:                           'intauth_switch' => 0,
 8057:                         );
 8058:         }
 8059:         foreach my $item (@items) {
 8060:             if ($itemcount%2) {
 8061:                 $css_class = '';
 8062:             } else {
 8063:                 $css_class = ' class="LC_odd_row" ';
 8064:             }
 8065:             $datatable .= '<tr'.$css_class.'>'.
 8066:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 8067:                           '</span></td><td class="LC_left_item" colspan="3">';
 8068:             if ($item eq 'intauth_switch') {
 8069:                 my @options = (0,1,2);
 8070:                 my %optiondesc = &Apache::lonlocal::texthash (
 8071:                                    0 => 'No',
 8072:                                    1 => 'Yes',
 8073:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 8074:                                  );
 8075:                 $datatable .= '<table width="100%">';
 8076:                 foreach my $option (@options) {
 8077:                     my $checked = ' ';
 8078:                     if ($defaults{$item} eq $option) {
 8079:                         $checked = ' checked="checked"';
 8080:                     }
 8081:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8082:                                   '<label><input type="radio" name="'.$item.
 8083:                                   '" value="'.$option.'"'.$checked.' />'.
 8084:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8085:                 }
 8086:                 $datatable .= '</table>';
 8087:             } elsif ($item eq 'intauth_check') {
 8088:                 my @options = (0,1,2);
 8089:                 my %optiondesc = &Apache::lonlocal::texthash (
 8090:                                    0 => 'No',
 8091:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 8092:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 8093:                                  );
 8094:                 $datatable .= '<table width="100%">';
 8095:                 foreach my $option (@options) {
 8096:                     my $checked = ' ';
 8097:                     my $onclick;
 8098:                     if ($defaults{$item} eq $option) {
 8099:                         $checked = ' checked="checked"';
 8100:                     }
 8101:                     if ($option == 2) {
 8102:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 8103:                     }
 8104:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8105:                                   '<label><input type="radio" name="'.$item.
 8106:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 8107:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8108:                 }
 8109:                 $datatable .= '</table>';
 8110:             } else {
 8111:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8112:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 8113:             }
 8114:             $datatable .= '</td></tr>';
 8115:             $itemcount ++;
 8116:         }
 8117:     } elsif ($position eq 'lower') {
 8118:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 8119:     } else {
 8120:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8121:         my %ownerchg = (
 8122:                           by  => {},
 8123:                           for => {},
 8124:                        );
 8125:         my %ownertitles = &Apache::lonlocal::texthash (
 8126:                             by  => 'Course owner status(es) allowed',
 8127:                             for => 'Student status(es) allowed',
 8128:                           );
 8129:         if (ref($settings) eq 'HASH') {
 8130:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 8131:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 8132:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 8133:                 }
 8134:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 8135:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 8136:                 }
 8137:             }
 8138:         }
 8139:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8140:         $datatable .= '<tr '.$css_class.'>'.
 8141:                       '<td>'.
 8142:                       &mt('Requirements').'<ul>'.
 8143:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 8144:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 8145:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 8146:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 8147:                       '</ul>'.
 8148:                       '</td>'.
 8149:                       '<td class="LC_left_item">';
 8150:         foreach my $item ('by','for') {
 8151:             $datatable .= '<fieldset style="display: inline-block;">'.
 8152:                           '<legend>'.$ownertitles{$item}.'</legend>';
 8153:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8154:                 foreach my $type (@{$types}) {
 8155:                     my $checked;
 8156:                     if ($ownerchg{$item}{$type}) {
 8157:                         $checked = ' checked="checked"';
 8158:                     }
 8159:                     $datatable .= '<span class="LC_nobreak"><label>'.
 8160:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 8161:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 8162:                                   '</span>&nbsp;&nbsp; ';
 8163:                 }
 8164:             }
 8165:             my $checked;
 8166:             if ($ownerchg{$item}{'default'}) {
 8167:                 $checked = ' checked="checked"';
 8168:             }
 8169:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 8170:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 8171:                           $othertitle.'</label></span></fieldset>';
 8172:         }
 8173:         $datatable .= '</td></tr>';
 8174:     }
 8175:     return $datatable;
 8176: }
 8177: 
 8178: sub password_rules {
 8179:     my ($prefix,$itemcountref,$settings) = @_;
 8180:     my ($min,$max,%chars,$expire,$numsaved,$numinrow);
 8181:     my %titles;
 8182:     if ($prefix eq 'passwords') {
 8183:         %titles = &Apache::lonlocal::texthash (
 8184:             min            => 'Minimum password length',
 8185:             max            => 'Maximum password length',
 8186:             chars          => 'Required characters',
 8187:         );
 8188:     } elsif ($prefix eq 'secrets') {
 8189:         %titles = &Apache::lonlocal::texthash (
 8190:             min            => 'Minimum secret length',
 8191:             max            => 'Maximum secret length',
 8192:             chars          => 'Required characters',
 8193:         );
 8194:     }
 8195:     $min = $Apache::lonnet::passwdmin;
 8196:     my $datatable;
 8197:     my $itemcount;
 8198:     if (ref($itemcountref)) {
 8199:         $itemcount = $$itemcountref;
 8200:     }
 8201:     if (ref($settings) eq 'HASH') {
 8202:         if ($settings->{min}) {
 8203:             $min = $settings->{min};
 8204:         }
 8205:         if ($settings->{max}) {
 8206:             $max = $settings->{max};
 8207:         }
 8208:         if (ref($settings->{chars}) eq 'ARRAY') {
 8209:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 8210:         }
 8211:         if ($prefix eq 'passwords') { 
 8212:             if ($settings->{expire}) {
 8213:                 $expire = $settings->{expire};
 8214:             }
 8215:             if ($settings->{numsaved}) {
 8216:                 $numsaved = $settings->{numsaved};
 8217:             }
 8218:         }
 8219:     }
 8220:     my %rulenames = &Apache::lonlocal::texthash(
 8221:                                                  uc => 'At least one upper case letter',
 8222:                                                  lc => 'At least one lower case letter',
 8223:                                                  num => 'At least one number',
 8224:                                                  spec => 'At least one non-alphanumeric',
 8225:                                                );
 8226:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8227:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 8228:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8229:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 8230:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8231:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 8232:                   '</span></td></tr>';
 8233:     $itemcount ++;
 8234:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8235:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 8236:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8237:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 8238:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8239:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 8240:                   '</span></td></tr>';
 8241:     $itemcount ++;
 8242:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8243:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 8244:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 8245:                   '</span></td>';
 8246:     my $numinrow = 2;
 8247:     my @possrules = ('uc','lc','num','spec');
 8248:     $datatable .= '<td class="LC_left_item"><table>';
 8249:     for (my $i=0; $i<@possrules; $i++) {
 8250:         my ($rem,$checked);
 8251:         if ($chars{$possrules[$i]}) {
 8252:             $checked = ' checked="checked"';
 8253:         }
 8254:         $rem = $i%($numinrow);
 8255:         if ($rem == 0) {
 8256:             if ($i > 0) {
 8257:                 $datatable .= '</tr>';
 8258:             }
 8259:             $datatable .= '<tr>';
 8260:         }
 8261:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 8262:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 8263:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 8264:     }
 8265:     my $rem = @possrules%($numinrow);
 8266:     my $colsleft = $numinrow - $rem;
 8267:     if ($colsleft > 1 ) {
 8268:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8269:                       '&nbsp;</td>';
 8270:     } elsif ($colsleft == 1) {
 8271:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8272:     }
 8273:     $datatable .='</table></td></tr>';
 8274:     $itemcount ++;
 8275:     if ($prefix eq 'passwords') {
 8276:         $titles{'expire'} = &mt('Password expiration (days)');
 8277:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 8278:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8279:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 8280:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8281:                       '<input type="text" name="'.$prefix.'_expire" value="'.$expire.'" size="4" '.
 8282:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8283:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 8284:                       '</span></td></tr>';
 8285:         $itemcount ++;
 8286:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8287:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 8288:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8289:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 8290:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8291:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 8292:                       '</span></td></tr>';
 8293:         $itemcount ++;
 8294:     }
 8295:     if (ref($itemcountref)) {
 8296:         $$itemcountref += $itemcount;
 8297:     }
 8298:     return $datatable;
 8299: }
 8300: 
 8301: sub print_wafproxy {
 8302:     my ($position,$dom,$settings,$rowtotal) = @_;
 8303:     my $css_class;
 8304:     my $itemcount = 0;
 8305:     my $datatable;
 8306:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8307:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 8308:     my %lt = &wafproxy_titles();
 8309:     foreach my $server (sort(keys(%servers))) {
 8310:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 8311:         next if ($serverhome eq '');
 8312:         my $serverdom;
 8313:         if ($serverhome ne $server) {
 8314:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 8315:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 8316:                 $othercontrol{$server} = $serverdom;
 8317:             }
 8318:         } else {
 8319:             $serverdom = &Apache::lonnet::host_domain($server);
 8320:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 8321:             if ($serverdom ne $dom) {
 8322:                 $othercontrol{$server} = $serverdom;
 8323:             } else {
 8324:                 $setdom = 1;
 8325:                 if (ref($settings) eq 'HASH') {
 8326:                     if (ref($settings->{'alias'}) eq 'HASH') {
 8327:                         $aliases{$dom} = $settings->{'alias'};
 8328:                         if ($aliases{$dom} ne '') {
 8329:                             $showdom = 1;
 8330:                         }
 8331:                     }
 8332:                     if (ref($settings->{'saml'}) eq 'HASH') {
 8333:                         $saml{$dom} = $settings->{'saml'};
 8334:                     }
 8335:                 }
 8336:             }
 8337:         }
 8338:     }
 8339:     if ($setdom) {
 8340:         %{$values{$dom}} = ();
 8341:         if (ref($settings) eq 'HASH') {
 8342:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8343:                 $values{$dom}{$item} = $settings->{$item};
 8344:             }
 8345:         }
 8346:     }
 8347:     if (keys(%othercontrol)) {
 8348:         %otherdoms = reverse(%othercontrol);
 8349:         foreach my $domain (keys(%otherdoms)) {
 8350:             %{$values{$domain}} = ();
 8351:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 8352:             if (ref($config{'wafproxy'}) eq 'HASH') {
 8353:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 8354:                 if (exists($config{'wafproxy'}{'saml'})) { 
 8355:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 8356:                 }
 8357:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8358:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 8359:                 }
 8360:             }
 8361:         }
 8362:     }
 8363:     if ($position eq 'top') {
 8364:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8365:         my %aliasinfo;
 8366:         foreach my $server (sort(keys(%servers))) {
 8367:             $itemcount ++;
 8368:             my $dom_in_effect;
 8369:             my $aliasrows = '<tr>'.
 8370:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8371:                             &mt('Hostname').':&nbsp;'.
 8372:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 8373:             if ($othercontrol{$server}) {
 8374:                 $dom_in_effect = $othercontrol{$server};
 8375:                 my ($current,$forsaml);
 8376:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 8377:                     $current = $aliases{$dom_in_effect}{$server};
 8378:                 }
 8379:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 8380:                     if ($saml{$dom_in_effect}{$server}) {
 8381:                         $forsaml = 1;
 8382:                     }
 8383:                 }
 8384:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8385:                               &mt('Alias').':&nbsp';
 8386:                 if ($current) {
 8387:                     $aliasrows .= $current;
 8388:                     if ($forsaml) {
 8389:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 8390:                     }
 8391:                 } else {
 8392:                     $aliasrows .= &mt('None');
 8393:                 }
 8394:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 8395:                               &mt('controlled by domain: [_1]',
 8396:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 8397:             } else {
 8398:                 $dom_in_effect = $dom;
 8399:                 my ($current,$samlon,$samloff);
 8400:                 $samloff = ' checked="checked"';
 8401:                 if (ref($aliases{$dom}) eq 'HASH') {
 8402:                     if ($aliases{$dom}{$server}) {
 8403:                         $current = $aliases{$dom}{$server};
 8404:                     }
 8405:                 }
 8406:                 if (ref($saml{$dom}) eq 'HASH') {
 8407:                     if ($saml{$dom}{$server}) {
 8408:                         $samlon = $samloff;
 8409:                         undef($samloff);
 8410:                     }
 8411:                 }
 8412:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8413:                               &mt('Alias').':&nbsp;'.
 8414:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 8415:                               'value="'.$current.'" size="30" />'.
 8416:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 8417:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 8418:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 8419:                               &mt('No').'</label>&nbsp;<label>'. 
 8420:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 8421:                               &mt('Yes').'</label></span>'.
 8422:                               '</td>'; 
 8423:             }
 8424:             $aliasrows .= '</tr>';
 8425:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 8426:         }
 8427:         if ($aliasinfo{$dom}) {
 8428:             my ($onclick,$wafon,$wafoff,$showtable);
 8429:             $onclick = ' onclick="javascript:toggleWAF();"';
 8430:             $wafoff = ' checked="checked"';
 8431:             $showtable = ' style="display:none";';
 8432:             if ($showdom) {
 8433:                 $wafon = $wafoff;
 8434:                 $wafoff = '';
 8435:                 $showtable = ' style="display:inline;"';
 8436:             }
 8437:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8438:             $datatable = '<tr'.$css_class.'>'.
 8439:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 8440:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 8441:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 8442:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 8443:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 8444:                          &mt('No').'</label></span></td>'.
 8445:                          '<td class="LC_left_item">'.
 8446:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 8447:                          '</table></td></tr>';
 8448:             $itemcount++;
 8449:         }
 8450:         if (keys(%otherdoms)) {
 8451:             foreach my $key (sort(keys(%otherdoms))) {
 8452:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8453:                 $datatable .= '<tr'.$css_class.'>'.
 8454:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 8455:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 8456:                               '</table></td></tr>';
 8457:                 $itemcount++;
 8458:             }
 8459:         }
 8460:     } else {
 8461:         my %ip_methods = &remoteip_methods();
 8462:         if ($setdom) {
 8463:             $itemcount ++;
 8464:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8465:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 8466:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 8467:             $wafstyle = ' style="display:none;"';
 8468:             $nowafstyle = ' style="display:table-row;"';
 8469:             $currwafdisplay = ' style="display: none"';
 8470:             $wafrangestyle = ' style="display: none"';
 8471:             $curr_remotip = 'n';
 8472:             $ssltossl = ' checked="checked"';
 8473:             if ($showdom) {
 8474:                 $wafstyle = ' style="display:table-row;"';
 8475:                 $nowafstyle =  ' style="display:none;"';
 8476:                 if (keys(%{$values{$dom}})) {
 8477:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 8478:                         $curr_remotip = $values{$dom}{remoteip};
 8479:                     }
 8480:                     if ($curr_remotip eq 'h') {
 8481:                         $currwafdisplay = ' style="display:table-row"';
 8482:                         $wafrangestyle = ' style="display:inline-block;"';
 8483:                     }
 8484:                     if ($values{$dom}{'sslopt'}) {
 8485:                         $alltossl = ' checked="checked"';
 8486:                         $ssltossl = '';
 8487:                     }
 8488:                 }
 8489:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 8490:                     $vpndircheck = ' checked="checked"';
 8491:                     $currwafvpn = ' style="display:table-row;"';
 8492:                     $wafrangestyle = ' style="display:inline-block;"';
 8493:                 } else {
 8494:                     $vpnaliascheck = ' checked="checked"';
 8495:                     $currwafvpn = ' style="display:none;"';
 8496:                 }
 8497:             }
 8498:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8499:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 8500:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 8501:                           '</tr>'.
 8502:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8503:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 8504:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 8505:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 8506:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 8507:                           '<td class="LC_left_item"><table>'.
 8508:                           '<tr>'.
 8509:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 8510:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 8511:             foreach my $option ('m','h','n') {
 8512:                 my $sel;
 8513:                 if ($option eq $curr_remotip) {
 8514:                    $sel = ' selected="selected"';
 8515:                 }
 8516:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 8517:                               $ip_methods{$option}.'</option>';
 8518:             }
 8519:             $datatable .= '</select></td></tr>'."\n".
 8520:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 8521:                           $lt{'ipheader'}.':&nbsp;'.
 8522:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 8523:                           'name="wafproxy_ipheader" />'.
 8524:                           '</td></tr>'."\n".
 8525:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 8526:                           $lt{'trusted'}.':<br />'.
 8527:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 8528:                           $values{$dom}{'trusted'}.'</textarea>'.
 8529:                           '</td></tr>'."\n".
 8530:                           '<tr><td><hr /></td></tr>'."\n".
 8531:                           '<tr>'.
 8532:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 8533:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 8534:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 8535:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 8536:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 8537:             foreach my $item ('vpnint','vpnext') {
 8538:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 8539:                               '<td valign="top">'.$lt{$item}.':<br />'.
 8540:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 8541:                               $values{$dom}{$item}.'</textarea>'.
 8542:                               '</td></tr>'."\n";
 8543:             }
 8544:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 8545:                           '<tr>'.
 8546:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 8547:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 8548:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 8549:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 8550:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 8551:                           '</table></td></tr>';
 8552:         }
 8553:         if (keys(%otherdoms)) {
 8554:             foreach my $domain (sort(keys(%otherdoms))) {
 8555:                 $itemcount ++;
 8556:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8557:                 $datatable .= '<tr'.$css_class.'>'.
 8558:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 8559:                               '<td class="LC_left_item"><table>';
 8560:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 8561:                     my $showval = &mt('None');
 8562:                     if ($item eq 'ssl') {
 8563:                         $showval = $lt{'ssltossl'};
 8564:                     }
 8565:                     if ($values{$domain}{$item}) {
 8566:                         $showval = $values{$domain}{$item};
 8567:                         if ($item eq 'ssl') {
 8568:                             $showval = $lt{'alltossl'};
 8569:                         } elsif ($item eq 'remoteip') {
 8570:                             $showval = $ip_methods{$values{$domain}{$item}};
 8571:                         }
 8572:                     }
 8573:                     $datatable .= '<tr>'.
 8574:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 8575:                 }
 8576:                 $datatable .= '</table></td></tr>';
 8577:             }
 8578:         }
 8579:     }
 8580:     $$rowtotal += $itemcount;
 8581:     return $datatable;
 8582: }
 8583: 
 8584: sub wafproxy_titles {
 8585:     return &Apache::lonlocal::texthash(
 8586:                remoteip   => "Method for determining user's IP",
 8587:                ipheader   => 'Request header containing remote IP',
 8588:                trusted    => 'Trusted IP range(s)',
 8589:                vpnaccess  => 'Access from institutional VPN',
 8590:                vpndirect  => 'via regular hostname (no WAF)',
 8591:                vpnaliased => 'via aliased hostname (WAF)',
 8592:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 8593:                vpnext     => 'IP Range(s) for backend WAF connections',
 8594:                sslopt     => 'Forwarding http/https',
 8595:                alltossl   => 'WAF forwards both http and https requests to https',
 8596:                ssltossl   => 'WAF forwards http requests to http and https to https',
 8597:            );
 8598: }
 8599: 
 8600: sub remoteip_methods {
 8601:     return &Apache::lonlocal::texthash(
 8602:               m => 'Use Apache mod_remoteip',
 8603:               h => 'Use headers parsed by LON-CAPA',
 8604:               n => 'Not in use',
 8605:            );
 8606: }
 8607: 
 8608: sub print_usersessions {
 8609:     my ($position,$dom,$settings,$rowtotal) = @_;
 8610:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 8611:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8612:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8613: 
 8614:     my @alldoms = &Apache::lonnet::all_domains();
 8615:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8616:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8617:     my %altids = &id_for_thisdom(%servers);
 8618:     if ($position eq 'top') {
 8619:         if (keys(%serverhomes) > 1) {
 8620:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 8621:             my ($curroffloadnow,$curroffloadoth);
 8622:             if (ref($settings) eq 'HASH') {
 8623:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 8624:                     $curroffloadnow = $settings->{'offloadnow'};
 8625:                 }
 8626:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 8627:                     $curroffloadoth = $settings->{'offloadoth'};
 8628:                 }
 8629:             }
 8630:             my $other_insts = scalar(keys(%by_location));
 8631:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 8632:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 8633:         } else {
 8634:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 8635:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 8636:                           '</td></tr>';
 8637:         }
 8638:     } else {
 8639:         my %titles = &usersession_titles();
 8640:         my ($prefix,@types);
 8641:         if ($position eq 'bottom') {
 8642:             $prefix = 'remote';
 8643:             @types = ('version','excludedomain','includedomain');
 8644:         } else {
 8645:             $prefix = 'hosted';
 8646:             @types = ('excludedomain','includedomain');
 8647:         }
 8648:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8649:     }
 8650:     $$rowtotal += $itemcount;
 8651:     return $datatable;
 8652: }
 8653: 
 8654: sub rules_by_location {
 8655:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 8656:     my ($datatable,$itemcount,$css_class);
 8657:     if (keys(%{$by_location}) == 0) {
 8658:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8659:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 8660:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 8661:                      '</td></tr>';
 8662:         $itemcount = 1;
 8663:     } else {
 8664:         $itemcount = 0;
 8665:         my $numinrow = 5;
 8666:         my (%current,%checkedon,%checkedoff);
 8667:         my @locations = sort(keys(%{$by_location}));
 8668:         foreach my $type (@{$types}) {
 8669:             $checkedon{$type} = '';
 8670:             $checkedoff{$type} = ' checked="checked"';
 8671:         }
 8672:         if (ref($settings) eq 'HASH') {
 8673:             if (ref($settings->{$prefix}) eq 'HASH') {
 8674:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 8675:                     $current{$key} = $settings->{$prefix}{$key};
 8676:                     if ($key eq 'version') {
 8677:                         if ($current{$key} ne '') {
 8678:                             $checkedon{$key} = ' checked="checked"';
 8679:                             $checkedoff{$key} = '';
 8680:                         }
 8681:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 8682:                         $checkedon{$key} = ' checked="checked"';
 8683:                         $checkedoff{$key} = '';
 8684:                     }
 8685:                 }
 8686:             }
 8687:         }
 8688:         foreach my $type (@{$types}) {
 8689:             next if ($type ne 'version' && !@locations);
 8690:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8691:             $datatable .= '<tr'.$css_class.'>
 8692:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 8693:                            <span class="LC_nobreak">&nbsp;
 8694:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 8695:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 8696:             if ($type eq 'version') {
 8697:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 8698:                 my $selector = '<select name="'.$prefix.'_version">';
 8699:                 foreach my $version (@lcversions) {
 8700:                     my $selected = '';
 8701:                     if ($current{'version'} eq $version) {
 8702:                         $selected = ' selected="selected"';
 8703:                     }
 8704:                     $selector .= ' <option value="'.$version.'"'.
 8705:                                  $selected.'>'.$version.'</option>';
 8706:                 }
 8707:                 $selector .= '</select> ';
 8708:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 8709:             } else {
 8710:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 8711:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 8712:                              ' />'.('&nbsp;'x2).
 8713:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 8714:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 8715:                              "\n".
 8716:                              '</div><div><table>';
 8717:                 my $rem;
 8718:                 for (my $i=0; $i<@locations; $i++) {
 8719:                     my ($showloc,$value,$checkedtype);
 8720:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 8721:                         my $ip = $by_location->{$locations[$i]}->[0];
 8722:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8723:                             $value = join(':',@{$by_ip->{$ip}});
 8724:                             $showloc = join(', ',@{$by_ip->{$ip}});
 8725:                             if (ref($current{$type}) eq 'ARRAY') {
 8726:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 8727:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 8728:                                         $checkedtype = ' checked="checked"';
 8729:                                         last;
 8730:                                     }
 8731:                                 }
 8732:                             }
 8733:                         }
 8734:                     }
 8735:                     $rem = $i%($numinrow);
 8736:                     if ($rem == 0) {
 8737:                         if ($i > 0) {
 8738:                             $datatable .= '</tr>';
 8739:                         }
 8740:                         $datatable .= '<tr>';
 8741:                     }
 8742:                     $datatable .= '<td class="LC_left_item">'.
 8743:                                   '<span class="LC_nobreak"><label>'.
 8744:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 8745:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 8746:                                   '</label></span></td>';
 8747:                 }
 8748:                 $rem = @locations%($numinrow);
 8749:                 my $colsleft = $numinrow - $rem;
 8750:                 if ($colsleft > 1 ) {
 8751:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8752:                                   '&nbsp;</td>';
 8753:                 } elsif ($colsleft == 1) {
 8754:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8755:                 }
 8756:                 $datatable .= '</tr></table>';
 8757:             }
 8758:             $datatable .= '</td></tr>';
 8759:             $itemcount ++;
 8760:         }
 8761:     }
 8762:     return ($datatable,$itemcount);
 8763: }
 8764: 
 8765: sub print_ssl {
 8766:     my ($position,$dom,$settings,$rowtotal) = @_;
 8767:     my ($css_class,$datatable);
 8768:     my $itemcount = 1;
 8769:     if ($position eq 'top') {
 8770:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8771:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8772:         my $same_institution;
 8773:         if ($intdom ne '') {
 8774:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 8775:             if (ref($internet_names) eq 'ARRAY') {
 8776:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8777:                     $same_institution = 1;
 8778:                 }
 8779:             }
 8780:         }
 8781:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8782:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 8783:         if ($same_institution) {
 8784:             my %domservers = &Apache::lonnet::get_servers($dom);
 8785:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 8786:         } else {
 8787:             $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.");
 8788:         }
 8789:         $datatable .= '</td></tr>';
 8790:         $itemcount ++;
 8791:     } else {
 8792:         my %titles = &ssl_titles();
 8793:         my (%by_ip,%by_location,@intdoms,@instdoms);
 8794:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8795:         my @alldoms = &Apache::lonnet::all_domains();
 8796:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8797:         my @domservers = &Apache::lonnet::get_servers($dom);
 8798:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8799:         my %altids = &id_for_thisdom(%servers);
 8800:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 8801:             my $legacy;
 8802:             unless (ref($settings) eq 'HASH') {
 8803:                 my $name;
 8804:                 if ($position eq 'connto') {
 8805:                     $name = 'loncAllowInsecure';
 8806:                 } else {
 8807:                     $name = 'londAllowInsecure';
 8808:                 }
 8809:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 8810:                 my @ids=&Apache::lonnet::current_machine_ids();
 8811:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 8812:                     my %what = (
 8813:                                    $name => 1,
 8814:                                );
 8815:                     my ($result,$returnhash) =
 8816:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8817:                     if ($result eq 'ok') {
 8818:                         if (ref($returnhash) eq 'HASH') {
 8819:                             $legacy = $returnhash->{$name};
 8820:                         }
 8821:                     }
 8822:                 } else {
 8823:                     $legacy = $Apache::lonnet::perlvar{$name};
 8824:                 }
 8825:             }
 8826:             foreach my $type ('dom','intdom','other') {
 8827:                 my %checked;
 8828:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8829:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8830:                               '<td class="LC_right_item">';
 8831:                 my $skip; 
 8832:                 if ($type eq 'dom') {
 8833:                     unless (keys(%servers) > 1) {
 8834:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8835:                         $skip = 1;
 8836:                     }
 8837:                 }
 8838:                 if ($type eq 'intdom') {
 8839:                     unless (@instdoms > 1) {
 8840:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8841:                         $skip = 1;
 8842:                     } 
 8843:                 } elsif ($type eq 'other') {
 8844:                     if (keys(%by_location) == 0) {
 8845:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8846:                         $skip = 1;
 8847:                     }
 8848:                 }
 8849:                 unless ($skip) {
 8850:                     $checked{'yes'} = ' checked="checked"'; 
 8851:                     if (ref($settings) eq 'HASH') {
 8852:                         if (ref($settings->{$position}) eq 'HASH') {
 8853:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8854:                                 $checked{$1} = $checked{'yes'};
 8855:                                 delete($checked{'yes'}); 
 8856:                             }
 8857:                         }
 8858:                     } else {
 8859:                         if ($legacy == 0) {
 8860:                             $checked{'req'} = $checked{'yes'};
 8861:                             delete($checked{'yes'});    
 8862:                         }
 8863:                     }
 8864:                     foreach my $option ('no','yes','req') {
 8865:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8866:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8867:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8868:                                       '</label></span>'.('&nbsp;'x2);
 8869:                     }
 8870:                 }
 8871:                 $datatable .= '</td></tr>';
 8872:                 $itemcount ++; 
 8873:             }
 8874:         } else {
 8875:             my $prefix = 'replication';
 8876:             my @types = ('certreq','nocertreq');
 8877:             if (keys(%by_location) == 0) {
 8878:                 $datatable .= '<tr'.$css_class.'><td>'.
 8879:                               &mt('Nothing to set here, as there are no other institutions').
 8880:                               '</td></tr>';
 8881:                 $itemcount ++;
 8882:             } else {
 8883:                 ($datatable,$itemcount) = 
 8884:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8885:             }
 8886:         }
 8887:     }
 8888:     $$rowtotal += $itemcount;
 8889:     return $datatable;
 8890: }
 8891: 
 8892: sub ssl_titles {
 8893:     return &Apache::lonlocal::texthash (
 8894:                dom           => 'LON-CAPA servers/VMs from same domain',
 8895:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8896:                other         => 'External LON-CAPA servers/VMs',
 8897:                connto        => 'Connections to other servers',
 8898:                connfrom      => 'Connections from other servers',
 8899:                replication   => 'Replicating content to other institutions',
 8900:                certreq       => 'Client certificate required, but specific domains exempt',
 8901:                nocertreq     => 'No client certificate required, except for specific domains',
 8902:                no            => 'SSL not used',
 8903:                yes           => 'SSL Optional (used if available)',
 8904:                req           => 'SSL Required',
 8905:     );
 8906: }
 8907: 
 8908: sub print_trust {
 8909:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8910:     my ($css_class,$datatable,%checked,%choices);
 8911:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8912:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8913:     my $itemcount = 1;
 8914:     my %titles = &trust_titles();
 8915:     my @types = ('exc','inc');
 8916:     if ($prefix eq 'top') {
 8917:         $prefix = 'content';
 8918:     } elsif ($prefix eq 'bottom') {
 8919:         $prefix = 'msg';
 8920:     }
 8921:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8922:     $$rowtotal += $itemcount;
 8923:     return $datatable;
 8924: }
 8925: 
 8926: sub trust_titles {
 8927:     return &Apache::lonlocal::texthash(
 8928:                content  => "Access to this domain's content by others",
 8929:                shared   => "Access to other domain's content by this domain",
 8930:                enroll   => "Enrollment in this domain's courses by others", 
 8931:                othcoau  => "Co-author roles in this domain for others",
 8932:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8933:                domroles => "Domain roles in this domain assignable to others",
 8934:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8935:                reqcrs   => "Requests for creation of courses in this domain by others",
 8936:                msg      => "Users in other domains can send messages to this domain",
 8937:                exc      => "Allow all, but exclude specific domains",
 8938:                inc      => "Deny all, but include specific domains",
 8939:            );
 8940: } 
 8941: 
 8942: sub build_location_hashes {
 8943:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8944:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8945:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8946:     my %iphost = &Apache::lonnet::get_iphost();
 8947:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 8948:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 8949:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 8950:         foreach my $id (@{$iphost{$primary_ip}}) {
 8951:             my $intdom = &Apache::lonnet::internet_dom($id);
 8952:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 8953:                 push(@{$intdoms},$intdom);
 8954:             }
 8955:         }
 8956:     }
 8957:     foreach my $ip (keys(%iphost)) {
 8958:         if (ref($iphost{$ip}) eq 'ARRAY') {
 8959:             foreach my $id (@{$iphost{$ip}}) {
 8960:                 my $location = &Apache::lonnet::internet_dom($id);
 8961:                 if ($location) {
 8962:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 8963:                         my $dom = &Apache::lonnet::host_domain($id);
 8964:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 8965:                             push(@{$instdoms},$dom);
 8966:                         }
 8967:                         next;
 8968:                     }
 8969:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8970:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 8971:                             push(@{$by_ip->{$ip}},$location);
 8972:                         }
 8973:                     } else {
 8974:                         $by_ip->{$ip} = [$location];
 8975:                     }
 8976:                 }
 8977:             }
 8978:         }
 8979:     }
 8980:     foreach my $ip (sort(keys(%{$by_ip}))) {
 8981:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8982:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 8983:             my $first = $by_ip->{$ip}->[0];
 8984:             if (ref($by_location->{$first}) eq 'ARRAY') {
 8985:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 8986:                     push(@{$by_location->{$first}},$ip);
 8987:                 }
 8988:             } else {
 8989:                 $by_location->{$first} = [$ip];
 8990:             }
 8991:         }
 8992:     }
 8993:     return;
 8994: }
 8995: 
 8996: sub current_offloads_to {
 8997:     my ($dom,$settings,$servers) = @_;
 8998:     my (%spareid,%otherdomconfigs);
 8999:     if (ref($servers) eq 'HASH') {
 9000:         foreach my $lonhost (sort(keys(%{$servers}))) {
 9001:             my $gotspares;
 9002:             if (ref($settings) eq 'HASH') {
 9003:                 if (ref($settings->{'spares'}) eq 'HASH') {
 9004:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 9005:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 9006:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 9007:                         $gotspares = 1;
 9008:                     }
 9009:                 }
 9010:             }
 9011:             unless ($gotspares) {
 9012:                 my $gotspares;
 9013:                 my $serverhomeID =
 9014:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 9015:                 my $serverhomedom =
 9016:                     &Apache::lonnet::host_domain($serverhomeID);
 9017:                 if ($serverhomedom ne $dom) {
 9018:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 9019:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9020:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9021:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9022:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9023:                                 $gotspares = 1;
 9024:                             }
 9025:                         }
 9026:                     } else {
 9027:                         $otherdomconfigs{$serverhomedom} =
 9028:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 9029:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 9030:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9031:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9032:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 9033:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9034:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9035:                                         $gotspares = 1;
 9036:                                     }
 9037:                                 }
 9038:                             }
 9039:                         }
 9040:                     }
 9041:                 }
 9042:             }
 9043:             unless ($gotspares) {
 9044:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9045:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9046:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9047:                } else {
 9048:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 9049:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 9050:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9051:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9052:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9053:                     } else {
 9054:                         my %what = (
 9055:                              spareid => 1,
 9056:                         );
 9057:                         my ($result,$returnhash) = 
 9058:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 9059:                         if ($result eq 'ok') { 
 9060:                             if (ref($returnhash) eq 'HASH') {
 9061:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 9062:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 9063:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 9064:                                 }
 9065:                             }
 9066:                         }
 9067:                     }
 9068:                 }
 9069:             }
 9070:         }
 9071:     }
 9072:     return %spareid;
 9073: }
 9074: 
 9075: sub spares_row {
 9076:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 9077:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 9078:     my $css_class;
 9079:     my $numinrow = 4;
 9080:     my $itemcount = 1;
 9081:     my $datatable;
 9082:     my %typetitles = &sparestype_titles();
 9083:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9084:         foreach my $server (sort(keys(%{$servers}))) {
 9085:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 9086:             my ($othercontrol,$serverdom);
 9087:             if ($serverhome ne $server) {
 9088:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 9089:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9090:             } else {
 9091:                 $serverdom = &Apache::lonnet::host_domain($server);
 9092:                 if ($serverdom ne $dom) {
 9093:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9094:                 }
 9095:             }
 9096:             next unless (ref($spareid->{$server}) eq 'HASH');
 9097:             my ($checkednow,$checkedoth);
 9098:             if (ref($curroffloadnow) eq 'HASH') {
 9099:                 if ($curroffloadnow->{$server}) {
 9100:                     $checkednow = ' checked="checked"';
 9101:                 }
 9102:             }
 9103:             if (ref($curroffloadoth) eq 'HASH') {
 9104:                 if ($curroffloadoth->{$server}) {
 9105:                     $checkedoth = ' checked="checked"';
 9106:                 }
 9107:             }
 9108:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 9109:             $datatable .= '<tr'.$css_class.'>
 9110:                            <td rowspan="2">
 9111:                             <span class="LC_nobreak">'.
 9112:                           &mt('[_1] when busy, offloads to:'
 9113:                               ,'<b>'.$server.'</b>').'</span><br />'.
 9114:                           '<span class="LC_nobreak">'."\n".
 9115:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 9116:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 9117:                           "\n";
 9118:             if ($other_insts) {
 9119:                 $datatable .= '<br />'.
 9120:                               '<span class="LC_nobreak">'."\n".
 9121:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 9122:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 9123:                           "\n";
 9124:             }
 9125:             my (%current,%canselect);
 9126:             my @choices = 
 9127:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 9128:             foreach my $type ('primary','default') {
 9129:                 if (ref($spareid->{$server}) eq 'HASH') {
 9130:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 9131:                         my @spares = @{$spareid->{$server}{$type}};
 9132:                         if (@spares > 0) {
 9133:                             if ($othercontrol) {
 9134:                                 $current{$type} = join(', ',@spares);
 9135:                             } else {
 9136:                                 $current{$type} .= '<table>';
 9137:                                 my $numspares = scalar(@spares);
 9138:                                 for (my $i=0;  $i<@spares; $i++) {
 9139:                                     my $rem = $i%($numinrow);
 9140:                                     if ($rem == 0) {
 9141:                                         if ($i > 0) {
 9142:                                             $current{$type} .= '</tr>';
 9143:                                         }
 9144:                                         $current{$type} .= '<tr>';
 9145:                                     }
 9146:                                     $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;'.
 9147:                                                        $spareid->{$server}{$type}[$i].
 9148:                                                        '</label></td>'."\n";
 9149:                                 }
 9150:                                 my $rem = @spares%($numinrow);
 9151:                                 my $colsleft = $numinrow - $rem;
 9152:                                 if ($colsleft > 1 ) {
 9153:                                     $current{$type} .= '<td colspan="'.$colsleft.
 9154:                                                        '" class="LC_left_item">'.
 9155:                                                        '&nbsp;</td>';
 9156:                                 } elsif ($colsleft == 1) {
 9157:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 9158:                                 }
 9159:                                 $current{$type} .= '</tr></table>';
 9160:                             }
 9161:                         }
 9162:                     }
 9163:                     if ($current{$type} eq '') {
 9164:                         $current{$type} = &mt('None specified');
 9165:                     }
 9166:                     if ($othercontrol) {
 9167:                         if ($type eq 'primary') {
 9168:                             $canselect{$type} = $othercontrol;
 9169:                         }
 9170:                     } else {
 9171:                         $canselect{$type} = 
 9172:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 9173:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 9174:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 9175:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 9176:                         if (@choices > 0) {
 9177:                             foreach my $lonhost (@choices) {
 9178:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 9179:                             }
 9180:                         }
 9181:                         $canselect{$type} .= '</select>'."\n";
 9182:                     }
 9183:                 } else {
 9184:                     $current{$type} = &mt('Could not be determined');
 9185:                     if ($type eq 'primary') {
 9186:                         $canselect{$type} =  $othercontrol;
 9187:                     }
 9188:                 }
 9189:                 if ($type eq 'default') {
 9190:                     $datatable .= '<tr'.$css_class.'>';
 9191:                 }
 9192:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 9193:                               '<td>'.$current{$type}.'</td>'."\n".
 9194:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 9195:             }
 9196:             $itemcount ++;
 9197:         }
 9198:     }
 9199:     $$rowtotal += $itemcount;
 9200:     return $datatable;
 9201: }
 9202: 
 9203: sub possible_newspares {
 9204:     my ($server,$currspares,$serverhomes,$altids) = @_;
 9205:     my $serverhostname = &Apache::lonnet::hostname($server);
 9206:     my %excluded;
 9207:     if ($serverhostname ne '') {
 9208:         %excluded = (
 9209:                        $serverhostname => 1,
 9210:                     );
 9211:     }
 9212:     if (ref($currspares) eq 'HASH') {
 9213:         foreach my $type (keys(%{$currspares})) {
 9214:             if (ref($currspares->{$type}) eq 'ARRAY') {
 9215:                 if (@{$currspares->{$type}} > 0) {
 9216:                     foreach my $curr (@{$currspares->{$type}}) {
 9217:                         my $hostname = &Apache::lonnet::hostname($curr);
 9218:                         $excluded{$hostname} = 1;
 9219:                     }
 9220:                 }
 9221:             }
 9222:         }
 9223:     }
 9224:     my @choices;
 9225:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9226:         if (keys(%{$serverhomes}) > 1) {
 9227:             foreach my $name (sort(keys(%{$serverhomes}))) {
 9228:                 unless ($excluded{$name}) {
 9229:                     if (exists($altids->{$serverhomes->{$name}})) {
 9230:                         push(@choices,$altids->{$serverhomes->{$name}});
 9231:                     } else {
 9232:                         push(@choices,$serverhomes->{$name});
 9233:                     }
 9234:                 }
 9235:             }
 9236:         }
 9237:     }
 9238:     return sort(@choices);
 9239: }
 9240: 
 9241: sub print_loadbalancing {
 9242:     my ($dom,$settings,$rowtotal) = @_;
 9243:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9244:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9245:     my $numinrow = 1;
 9246:     my $datatable;
 9247:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9248:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 9249:     if (ref($settings) eq 'HASH') {
 9250:         %existing = %{$settings};
 9251:     }
 9252:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 9253:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 9254:                                   \%currtargets,\%currrules,\%currcookies);
 9255:     } else {
 9256:         return;
 9257:     }
 9258:     my ($othertitle,$usertypes,$types) =
 9259:         &Apache::loncommon::sorted_inst_types($dom);
 9260:     my $rownum = 8;
 9261:     if (ref($types) eq 'ARRAY') {
 9262:         $rownum += scalar(@{$types});
 9263:     }
 9264:     my @css_class = ('LC_odd_row','LC_even_row');
 9265:     my $balnum = 0;
 9266:     my $islast;
 9267:     my (@toshow,$disabledtext);
 9268:     if (keys(%currbalancer) > 0) {
 9269:         @toshow = sort(keys(%currbalancer));
 9270:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 9271:             push(@toshow,'');
 9272:         }
 9273:     } else {
 9274:         @toshow = ('');
 9275:         $disabledtext = &mt('No existing load balancer');
 9276:     }
 9277:     foreach my $lonhost (@toshow) {
 9278:         if ($balnum == scalar(@toshow)-1) {
 9279:             $islast = 1;
 9280:         } else {
 9281:             $islast = 0;
 9282:         }
 9283:         my $cssidx = $balnum%2;
 9284:         my $targets_div_style = 'display: none';
 9285:         my $disabled_div_style = 'display: block';
 9286:         my $homedom_div_style = 'display: none';
 9287:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 9288:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9289:                       '<p>';
 9290:         if ($lonhost eq '') {
 9291:             $datatable .= '<span class="LC_nobreak">';
 9292:             if (keys(%currbalancer) > 0) {
 9293:                 $datatable .= &mt('Add balancer:');
 9294:             } else {
 9295:                 $datatable .= &mt('Enable balancer:');
 9296:             }
 9297:             $datatable .= '&nbsp;'.
 9298:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 9299:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 9300:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 9301:                           '<option value="" selected="selected">'.&mt('None').
 9302:                           '</option>'."\n";
 9303:             foreach my $server (sort(keys(%servers))) {
 9304:                 next if ($currbalancer{$server});
 9305:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 9306:             }
 9307:             $datatable .=
 9308:                 '</select>'."\n".
 9309:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 9310:         } else {
 9311:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 9312:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 9313:                            &mt('Stop balancing').'</label>'.
 9314:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 9315:             $targets_div_style = 'display: block';
 9316:             $disabled_div_style = 'display: none';
 9317:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 9318:                 $homedom_div_style = 'display: block';
 9319:             }
 9320:         }
 9321:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9322:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 9323:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 9324:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 9325:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 9326:         my @sparestypes = ('primary','default');
 9327:         my %typetitles = &sparestype_titles();
 9328:         my %hostherechecked = (
 9329:                                   no => ' checked="checked"',
 9330:                               );
 9331:         my %balcookiechecked = (
 9332:                                   no => ' checked="checked"', 
 9333:                                );
 9334:         foreach my $sparetype (@sparestypes) {
 9335:             my $targettable;
 9336:             for (my $i=0; $i<$numspares; $i++) {
 9337:                 my $checked;
 9338:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 9339:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9340:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9341:                             $checked = ' checked="checked"';
 9342:                         }
 9343:                     }
 9344:                 }
 9345:                 my ($chkboxval,$disabled);
 9346:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 9347:                     $chkboxval = $spares[$i];
 9348:                 }
 9349:                 if (exists($currbalancer{$spares[$i]})) {
 9350:                     $disabled = ' disabled="disabled"';
 9351:                 }
 9352:                 $targettable .=
 9353:                     '<td><span class="LC_nobreak"><label>'.
 9354:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 9355:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 9356:                     '</span></label></span></td>';
 9357:                 my $rem = $i%($numinrow);
 9358:                 if ($rem == 0) {
 9359:                     if (($i > 0) && ($i < $numspares-1)) {
 9360:                         $targettable .= '</tr>';
 9361:                     }
 9362:                     if ($i < $numspares-1) {
 9363:                         $targettable .= '<tr>';
 9364:                     }
 9365:                 }
 9366:             }
 9367:             if ($targettable ne '') {
 9368:                 my $rem = $numspares%($numinrow);
 9369:                 my $colsleft = $numinrow - $rem;
 9370:                 if ($colsleft > 1 ) {
 9371:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9372:                                     '&nbsp;</td>';
 9373:                 } elsif ($colsleft == 1) {
 9374:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 9375:                 }
 9376:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 9377:                                '<table><tr>'.$targettable.'</tr></table><br />';
 9378:             }
 9379:             $hostherechecked{$sparetype} = '';
 9380:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 9381:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9382:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9383:                         $hostherechecked{$sparetype} = ' checked="checked"';
 9384:                         $hostherechecked{'no'} = '';
 9385:                     }
 9386:                 }
 9387:             }
 9388:         }
 9389:         if ($currcookies{$lonhost}) {
 9390:             %balcookiechecked = (
 9391:                                     yes => ' checked="checked"',
 9392:                                 );
 9393:         }
 9394:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 9395:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 9396:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 9397:         foreach my $sparetype (@sparestypes) {
 9398:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 9399:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 9400:                           '</i></label><br />';
 9401:         }
 9402:         $datatable .= &mt('Use balancer cookie').'<br />'.
 9403:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 9404:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 9405:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 9406:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 9407:                       '</div></td></tr>'.
 9408:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 9409:                                            $othertitle,$usertypes,$types,\%servers,
 9410:                                            \%currbalancer,$lonhost,
 9411:                                            $targets_div_style,$homedom_div_style,
 9412:                                            $css_class[$cssidx],$balnum,$islast);
 9413:         $$rowtotal += $rownum;
 9414:         $balnum ++;
 9415:     }
 9416:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 9417:     return $datatable;
 9418: }
 9419: 
 9420: sub get_loadbalancers_config {
 9421:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 9422:     return unless ((ref($servers) eq 'HASH') &&
 9423:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 9424:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 9425:                    (ref($currcookies) eq 'HASH'));
 9426:     if (keys(%{$existing}) > 0) {
 9427:         my $oldlonhost;
 9428:         foreach my $key (sort(keys(%{$existing}))) {
 9429:             if ($key eq 'lonhost') {
 9430:                 $oldlonhost = $existing->{'lonhost'};
 9431:                 $currbalancer->{$oldlonhost} = 1;
 9432:             } elsif ($key eq 'targets') {
 9433:                 if ($oldlonhost) {
 9434:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 9435:                 }
 9436:             } elsif ($key eq 'rules') {
 9437:                 if ($oldlonhost) {
 9438:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 9439:                 }
 9440:             } elsif (ref($existing->{$key}) eq 'HASH') {
 9441:                 $currbalancer->{$key} = 1;
 9442:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 9443:                 $currrules->{$key} = $existing->{$key}{'rules'};
 9444:                 if ($existing->{$key}{'cookie'}) {
 9445:                     $currcookies->{$key} = 1;
 9446:                 }
 9447:             }
 9448:         }
 9449:     } else {
 9450:         my ($balancerref,$targetsref) =
 9451:                 &Apache::lonnet::get_lonbalancer_config($servers);
 9452:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 9453:             foreach my $server (sort(keys(%{$balancerref}))) {
 9454:                 $currbalancer->{$server} = 1;
 9455:                 $currtargets->{$server} = $targetsref->{$server};
 9456:             }
 9457:         }
 9458:     }
 9459:     return;
 9460: }
 9461: 
 9462: sub loadbalancing_rules {
 9463:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 9464:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 9465:         $css_class,$balnum,$islast) = @_;
 9466:     my $output;
 9467:     my $num = 0;
 9468:     my ($alltypes,$othertypes,$titles) =
 9469:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 9470:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 9471:         foreach my $type (@{$alltypes}) {
 9472:             $num ++;
 9473:             my $current;
 9474:             if (ref($currrules) eq 'HASH') {
 9475:                 $current = $currrules->{$type};
 9476:             }
 9477:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9478:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 9479:                     $current = '';
 9480:                 }
 9481:             }
 9482:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 9483:                                              $servers,$currbalancer,$lonhost,$dom,
 9484:                                              $targets_div_style,$homedom_div_style,
 9485:                                              $css_class,$balnum,$num,$islast);
 9486:         }
 9487:     }
 9488:     return $output;
 9489: }
 9490: 
 9491: sub loadbalancing_titles {
 9492:     my ($dom,$intdom,$usertypes,$types) = @_;
 9493:     my %othertypes = (
 9494:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 9495:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 9496:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 9497:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 9498:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 9499:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 9500:                      );
 9501:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 9502:     my @available;
 9503:     if (ref($types) eq 'ARRAY') {
 9504:         @available = @{$types};
 9505:     }
 9506:     unless (grep(/^default$/,@available)) {
 9507:         push(@available,'default');
 9508:     }
 9509:     unshift(@alltypes,@available);
 9510:     my %titles;
 9511:     foreach my $type (@alltypes) {
 9512:         if ($type =~ /^_LC_/) {
 9513:             $titles{$type} = $othertypes{$type};
 9514:         } elsif ($type eq 'default') {
 9515:             $titles{$type} = &mt('All users from [_1]',$dom);
 9516:             if (ref($types) eq 'ARRAY') {
 9517:                 if (@{$types} > 0) {
 9518:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 9519:                 }
 9520:             }
 9521:         } elsif (ref($usertypes) eq 'HASH') {
 9522:             $titles{$type} = $usertypes->{$type};
 9523:         }
 9524:     }
 9525:     return (\@alltypes,\%othertypes,\%titles);
 9526: }
 9527: 
 9528: sub loadbalance_rule_row {
 9529:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 9530:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 9531:     my @rulenames;
 9532:     my %ruletitles = &offloadtype_text();
 9533:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 9534:         @rulenames = ('balancer','offloadedto','specific');
 9535:     } else {
 9536:         @rulenames = ('default','homeserver');
 9537:         if ($type eq '_LC_external') {
 9538:             push(@rulenames,'externalbalancer');
 9539:         } else {
 9540:             push(@rulenames,'specific');
 9541:         }
 9542:         push(@rulenames,'none');
 9543:     }
 9544:     my $style = $targets_div_style;
 9545:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9546:         $style = $homedom_div_style;
 9547:     }
 9548:     my $space;
 9549:     if ($islast && $num == 1) {
 9550:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 9551:     }
 9552:     my $output =
 9553:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 9554:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 9555:         '<td valaign="top">'.$space.
 9556:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 9557:     for (my $i=0; $i<@rulenames; $i++) {
 9558:         my $rule = $rulenames[$i];
 9559:         my ($checked,$extra);
 9560:         if ($rulenames[$i] eq 'default') {
 9561:             $rule = '';
 9562:         }
 9563:         if ($rulenames[$i] eq 'specific') {
 9564:             if (ref($servers) eq 'HASH') {
 9565:                 my $default;
 9566:                 if (($current ne '') && (exists($servers->{$current}))) {
 9567:                     $checked = ' checked="checked"';
 9568:                 }
 9569:                 unless ($checked) {
 9570:                     $default = ' selected="selected"';
 9571:                 }
 9572:                 $extra =
 9573:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9574:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9575:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 9576:                     '<option value=""'.$default.'></option>'."\n";
 9577:                 foreach my $server (sort(keys(%{$servers}))) {
 9578:                     if (ref($currbalancer) eq 'HASH') {
 9579:                         next if (exists($currbalancer->{$server}));
 9580:                     }
 9581:                     my $selected;
 9582:                     if ($server eq $current) {
 9583:                         $selected = ' selected="selected"';
 9584:                     }
 9585:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 9586:                 }
 9587:                 $extra .= '</select>';
 9588:             }
 9589:         } elsif ($rule eq $current) {
 9590:             $checked = ' checked="checked"';
 9591:         }
 9592:         $output .= '<span class="LC_nobreak"><label>'.
 9593:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 9594:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 9595:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 9596:                    ')"'.$checked.' />&nbsp;';
 9597:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 9598:             $output .= $ruletitles{'particular'};
 9599:         } else {
 9600:             $output .= $ruletitles{$rulenames[$i]};
 9601:         }
 9602:         $output .= '</label>'.$extra.'</span><br />'."\n";
 9603:     }
 9604:     $output .= '</div></td></tr>'."\n";
 9605:     return $output;
 9606: }
 9607: 
 9608: sub offloadtype_text {
 9609:     my %ruletitles = &Apache::lonlocal::texthash (
 9610:            'default'          => 'Offloads to default destinations',
 9611:            'homeserver'       => "Offloads to user's home server",
 9612:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 9613:            'specific'         => 'Offloads to specific server',
 9614:            'none'             => 'No offload',
 9615:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 9616:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 9617:            'particular'       => 'Session hosted (after re-auth) on server:',
 9618:     );
 9619:     return %ruletitles;
 9620: }
 9621: 
 9622: sub sparestype_titles {
 9623:     my %typestitles = &Apache::lonlocal::texthash (
 9624:                           'primary' => 'primary',
 9625:                           'default' => 'default',
 9626:                       );
 9627:     return %typestitles;
 9628: }
 9629: 
 9630: sub contact_titles {
 9631:     my %titles = &Apache::lonlocal::texthash (
 9632:                    'supportemail'    => 'Support E-mail address',
 9633:                    'adminemail'      => 'Default Server Admin E-mail address',
 9634:                    'errormail'       => 'Error reports to be e-mailed to',
 9635:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 9636:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 9637:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 9638:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 9639:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 9640:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 9641:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 9642:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 9643:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 9644:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 9645:                    'errorweights'    => 'Weights used to compute error count',
 9646:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 9647:                  );
 9648:     my %short_titles = &Apache::lonlocal::texthash (
 9649:                            adminemail   => 'Admin E-mail address',
 9650:                            supportemail => 'Support E-mail',
 9651:                        );   
 9652:     return (\%titles,\%short_titles);
 9653: }
 9654: 
 9655: sub helpform_fields {
 9656:     my %titles =  &Apache::lonlocal::texthash (
 9657:                        'username'   => 'Name',
 9658:                        'user'       => 'Username/domain',
 9659:                        'phone'      => 'Phone',
 9660:                        'cc'         => 'Cc e-mail',
 9661:                        'course'     => 'Course Details',
 9662:                        'section'    => 'Sections',
 9663:                        'screenshot' => 'File upload',
 9664:     );
 9665:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 9666:     my %possoptions = (
 9667:                         username     => ['yes','no','req'],
 9668:                         phone        => ['yes','no','req'],
 9669:                         user         => ['yes','no'],
 9670:                         cc           => ['yes','no'],
 9671:                         course       => ['yes','no'],
 9672:                         section      => ['yes','no'],
 9673:                         screenshot   => ['yes','no'],
 9674:                       );
 9675:     my %fieldoptions = &Apache::lonlocal::texthash (
 9676:                          'yes'  => 'Optional',
 9677:                          'req'  => 'Required',
 9678:                          'no'   => "Not shown",
 9679:     );
 9680:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 9681: }
 9682: 
 9683: sub tool_titles {
 9684:     my %titles = &Apache::lonlocal::texthash (
 9685:                      aboutme    => 'Personal web page',
 9686:                      blog       => 'Blog',
 9687:                      webdav     => 'WebDAV',
 9688:                      portfolio  => 'Portfolio',
 9689:                      official   => 'Official courses (with institutional codes)',
 9690:                      unofficial => 'Unofficial courses',
 9691:                      community  => 'Communities',
 9692:                      textbook   => 'Textbook courses',
 9693:                      placement  => 'Placement tests',
 9694:                  );
 9695:     return %titles;
 9696: }
 9697: 
 9698: sub courserequest_titles {
 9699:     my %titles = &Apache::lonlocal::texthash (
 9700:                                    official   => 'Official',
 9701:                                    unofficial => 'Unofficial',
 9702:                                    community  => 'Communities',
 9703:                                    textbook   => 'Textbook',
 9704:                                    placement  => 'Placement tests',
 9705:                                    lti        => 'LTI Provider',
 9706:                                    norequest  => 'Not allowed',
 9707:                                    approval   => 'Approval by DC',
 9708:                                    validate   => 'With validation',
 9709:                                    autolimit  => 'Numerical limit',
 9710:                                    unlimited  => '(blank for unlimited)',
 9711:                  );
 9712:     return %titles;
 9713: }
 9714: 
 9715: sub authorrequest_titles {
 9716:     my %titles = &Apache::lonlocal::texthash (
 9717:                                    norequest  => 'Not allowed',
 9718:                                    approval   => 'Approval by Dom. Coord.',
 9719:                                    automatic  => 'Automatic approval',
 9720:                  );
 9721:     return %titles;
 9722: }
 9723: 
 9724: sub courserequest_conditions {
 9725:     my %conditions = &Apache::lonlocal::texthash (
 9726:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 9727:        validate   => '(Processing of request subject to institutional validation).',
 9728:                  );
 9729:     return %conditions;
 9730: }
 9731: 
 9732: 
 9733: sub print_usercreation {
 9734:     my ($position,$dom,$settings,$rowtotal) = @_;
 9735:     my $numinrow = 4;
 9736:     my $datatable;
 9737:     if ($position eq 'top') {
 9738:         $$rowtotal ++;
 9739:         my $rowcount = 0;
 9740:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 9741:         if (ref($rules) eq 'HASH') {
 9742:             if (keys(%{$rules}) > 0) {
 9743:                 $datatable .= &user_formats_row('username',$settings,$rules,
 9744:                                                 $ruleorder,$numinrow,$rowcount);
 9745:                 $$rowtotal ++;
 9746:                 $rowcount ++;
 9747:             }
 9748:         }
 9749:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 9750:         if (ref($idrules) eq 'HASH') {
 9751:             if (keys(%{$idrules}) > 0) {
 9752:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 9753:                                                 $idruleorder,$numinrow,$rowcount);
 9754:                 $$rowtotal ++;
 9755:                 $rowcount ++;
 9756:             }
 9757:         }
 9758:         if ($rowcount == 0) {
 9759:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 9760:             $$rowtotal ++;
 9761:             $rowcount ++;
 9762:         }
 9763:     } elsif ($position eq 'middle') {
 9764:         my @creators = ('author','course','requestcrs');
 9765:         my ($rules,$ruleorder) =
 9766:             &Apache::lonnet::inst_userrules($dom,'username');
 9767:         my %lt = &usercreation_types();
 9768:         my %checked;
 9769:         if (ref($settings) eq 'HASH') {
 9770:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 9771:                 foreach my $item (@creators) {
 9772:                     $checked{$item} = $settings->{'cancreate'}{$item};
 9773:                 }
 9774:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 9775:                 foreach my $item (@creators) {
 9776:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 9777:                         $checked{$item} = 'none';
 9778:                     }
 9779:                 }
 9780:             }
 9781:         }
 9782:         my $rownum = 0;
 9783:         foreach my $item (@creators) {
 9784:             $rownum ++;
 9785:             if ($checked{$item} eq '') {
 9786:                 $checked{$item} = 'any';
 9787:             }
 9788:             my $css_class;
 9789:             if ($rownum%2) {
 9790:                 $css_class = '';
 9791:             } else {
 9792:                 $css_class = ' class="LC_odd_row" ';
 9793:             }
 9794:             $datatable .= '<tr'.$css_class.'>'.
 9795:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 9796:                          '</span></td><td style="text-align: right">';
 9797:             my @options = ('any');
 9798:             if (ref($rules) eq 'HASH') {
 9799:                 if (keys(%{$rules}) > 0) {
 9800:                     push(@options,('official','unofficial'));
 9801:                 }
 9802:             }
 9803:             push(@options,'none');
 9804:             foreach my $option (@options) {
 9805:                 my $type = 'radio';
 9806:                 my $check = ' ';
 9807:                 if ($checked{$item} eq $option) {
 9808:                     $check = ' checked="checked" ';
 9809:                 } 
 9810:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9811:                               '<input type="'.$type.'" name="can_createuser_'.
 9812:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 9813:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 9814:             }
 9815:             $datatable .= '</td></tr>';
 9816:         }
 9817:     } else {
 9818:         my @contexts = ('author','course','domain');
 9819:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9820:         my %checked;
 9821:         if (ref($settings) eq 'HASH') {
 9822:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9823:                 foreach my $item (@contexts) {
 9824:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9825:                         foreach my $auth (@authtypes) {
 9826:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9827:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9828:                             }
 9829:                         }
 9830:                     }
 9831:                 }
 9832:             }
 9833:         } else {
 9834:             foreach my $item (@contexts) {
 9835:                 foreach my $auth (@authtypes) {
 9836:                     $checked{$item}{$auth} = ' checked="checked" ';
 9837:                 }
 9838:             }
 9839:         }
 9840:         my %title = &context_names();
 9841:         my %authname = &authtype_names();
 9842:         my $rownum = 0;
 9843:         my $css_class; 
 9844:         foreach my $item (@contexts) {
 9845:             if ($rownum%2) {
 9846:                 $css_class = '';
 9847:             } else {
 9848:                 $css_class = ' class="LC_odd_row" ';
 9849:             }
 9850:             $datatable .=   '<tr'.$css_class.'>'.
 9851:                             '<td>'.$title{$item}.
 9852:                             '</td><td class="LC_left_item">'.
 9853:                             '<span class="LC_nobreak">';
 9854:             foreach my $auth (@authtypes) {
 9855:                 $datatable .= '<label>'. 
 9856:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9857:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9858:                               $authname{$auth}.'</label>&nbsp;';
 9859:             }
 9860:             $datatable .= '</span></td></tr>';
 9861:             $rownum ++;
 9862:         }
 9863:         $$rowtotal += $rownum;
 9864:     }
 9865:     return $datatable;
 9866: }
 9867: 
 9868: sub print_selfcreation {
 9869:     my ($position,$dom,$settings,$rowtotal) = @_;
 9870:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9871:         $emaildomain,$datatable);
 9872:     if (ref($settings) eq 'HASH') {
 9873:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9874:             $createsettings = $settings->{'cancreate'};
 9875:             if (ref($createsettings) eq 'HASH') {
 9876:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9877:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9878:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9879:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9880:                         @selfcreate = ('email','login','sso');
 9881:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9882:                         @selfcreate = ($createsettings->{'selfcreate'});
 9883:                     }
 9884:                 }
 9885:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9886:                     $processing = $createsettings->{'selfcreateprocessing'};
 9887:                 }
 9888:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9889:                     $emailoptions = $createsettings->{'emailoptions'};
 9890:                 }
 9891:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9892:                     $emailverified = $createsettings->{'emailverified'};
 9893:                 }
 9894:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9895:                     $emaildomain = $createsettings->{'emaildomain'};
 9896:                 }
 9897:             }
 9898:         }
 9899:     }
 9900:     my %radiohash;
 9901:     my $numinrow = 4;
 9902:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9903:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9904:     if ($position eq 'top') {
 9905:         my %choices = &Apache::lonlocal::texthash (
 9906:                                                       cancreate_login      => 'Institutional Login',
 9907:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9908:                                                   );
 9909:         my @toggles = sort(keys(%choices));
 9910:         my %defaultchecked = (
 9911:                                'cancreate_login' => 'off',
 9912:                                'cancreate_sso'   => 'off',
 9913:                              );
 9914:         my ($onclick,$itemcount);
 9915:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9916:                                                      \%choices,$itemcount,$onclick);
 9917:         $$rowtotal += $itemcount;
 9918:         
 9919:         if (ref($usertypes) eq 'HASH') {
 9920:             if (keys(%{$usertypes}) > 0) {
 9921:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9922:                                              $dom,$numinrow,$othertitle,
 9923:                                              'statustocreate',$rowtotal);
 9924:                 $$rowtotal ++;
 9925:             }
 9926:         }
 9927:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9928:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9929:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9930:         my $rem;
 9931:         my $numperrow = 2;
 9932:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9933:         $datatable .= '<tr'.$css_class.'>'.
 9934:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9935:                      '<td class="LC_left_item">'."\n".
 9936:                      '<table>'."\n";
 9937:         for (my $i=0; $i<@fields; $i++) {
 9938:             $rem = $i%($numperrow);
 9939:             if ($rem == 0) {
 9940:                 if ($i > 0) {
 9941:                     $datatable .= '</tr>';
 9942:                 }
 9943:                 $datatable .= '<tr>';
 9944:             }
 9945:             my $currval;
 9946:             if (ref($createsettings) eq 'HASH') {
 9947:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 9948:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 9949:                 }
 9950:             }
 9951:             $datatable .= '<td class="LC_left_item">'.
 9952:                           '<span class="LC_nobreak">'.
 9953:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 9954:                           'value="'.$currval.'" size="10" />&nbsp;'.
 9955:                           $fieldtitles{$fields[$i]}.'</span></td>';
 9956:         }
 9957:         my $colsleft = $numperrow - $rem;
 9958:         if ($colsleft > 1 ) {
 9959:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9960:                          '&nbsp;</td>';
 9961:         } elsif ($colsleft == 1) {
 9962:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 9963:         }
 9964:         $datatable .= '</tr></table></td></tr>';
 9965:         $$rowtotal ++;
 9966:     } elsif ($position eq 'middle') {
 9967:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 9968:         my @posstypes;
 9969:         if (ref($types) eq 'ARRAY') {
 9970:             @posstypes = @{$types};
 9971:         }
 9972:         unless (grep(/^default$/,@posstypes)) {
 9973:             push(@posstypes,'default');
 9974:         }
 9975:         my %usertypeshash;
 9976:         if (ref($usertypes) eq 'HASH') {
 9977:             %usertypeshash = %{$usertypes};
 9978:         }
 9979:         $usertypeshash{'default'} = $othertitle;
 9980:         foreach my $status (@posstypes) {
 9981:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 9982:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 9983:             $$rowtotal ++;
 9984:         }
 9985:     } else {
 9986:         my %choices = &Apache::lonlocal::texthash (
 9987:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 9988:                                                   );
 9989:         my @toggles = sort(keys(%choices));
 9990:         my %defaultchecked = (
 9991:                                'cancreate_email' => 'off',
 9992:                              );
 9993:         my $customclass = 'LC_selfcreate_email';
 9994:         my $classprefix = 'LC_canmodify_emailusername_';
 9995:         my $optionsprefix = 'LC_options_emailusername_';
 9996:         my $display = 'none';
 9997:         my $rowstyle = 'display:none';
 9998:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 9999:             $display = 'block';
10000:             $rowstyle = 'display:table-row';
10001:         }
10002:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
10003:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
10004:                                                      \%choices,$$rowtotal,$onclick);
10005:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
10006:                                          $rowstyle);
10007:         $$rowtotal ++;
10008:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
10009:                                       $rowstyle);
10010:         $$rowtotal ++;
10011:         my (@ordered,@posstypes,%usertypeshash);
10012:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10013:         my ($emailrules,$emailruleorder) =
10014:             &Apache::lonnet::inst_userrules($dom,'email');
10015:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
10016:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
10017:         if (ref($types) eq 'ARRAY') {
10018:             @posstypes = @{$types};
10019:         }
10020:         if (@posstypes) {
10021:             unless (grep(/^default$/,@posstypes)) {
10022:                 push(@posstypes,'default');
10023:             }
10024:             if (ref($usertypes) eq 'HASH') {
10025:                 %usertypeshash = %{$usertypes};
10026:             }
10027:             my $currassign;
10028:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
10029:                 $currassign = {
10030:                                   selfassign => $domdefaults{'inststatusguest'},
10031:                               };
10032:                 @ordered = @{$domdefaults{'inststatusguest'}};
10033:             } else {
10034:                 $currassign = { selfassign => [] };
10035:             }
10036:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
10037:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
10038:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
10039:                                          $numinrow,$othertitle,'selfassign',
10040:                                          $rowtotal,$onclicktypes,$customclass,
10041:                                          $rowstyle);
10042:             $$rowtotal ++;
10043:             $usertypeshash{'default'} = $othertitle;
10044:             foreach my $status (@posstypes) {
10045:                 my $css_class;
10046:                 if ($$rowtotal%2) {
10047:                     $css_class = 'LC_odd_row ';
10048:                 }
10049:                 $css_class .= $customclass;
10050:                 my $rowid = $optionsprefix.$status;
10051:                 my $hidden = 1;
10052:                 my $currstyle = 'display:none';
10053:                 if (grep(/^\Q$status\E$/,@ordered)) {
10054:                     $currstyle = $rowstyle;
10055:                     $hidden = 0; 
10056:                 }
10057:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10058:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
10059:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
10060:                 unless ($hidden) {
10061:                     $$rowtotal ++;
10062:                 }
10063:             }
10064:         } else {
10065:             my $css_class;
10066:             if ($$rowtotal%2) {
10067:                 $css_class = 'LC_odd_row ';
10068:             }
10069:             $css_class .= $customclass;
10070:             $usertypeshash{'default'} = $othertitle;
10071:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10072:                                          $emailrules,$emailruleorder,$settings,'default','',
10073:                                          $othertitle,$css_class,$rowstyle,$intdom);
10074:             $$rowtotal ++;
10075:         }
10076:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
10077:         $numinrow = 1;
10078:         if (@posstypes) {
10079:             foreach my $status (@posstypes) {
10080:                 my $rowid = $classprefix.$status;
10081:                 my $datarowstyle = 'display:none';
10082:                 if (grep(/^\Q$status\E$/,@ordered)) { 
10083:                     $datarowstyle = $rowstyle; 
10084:                 }
10085:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
10086:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10087:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
10088:                 unless ($datarowstyle eq 'display:none') {
10089:                     $$rowtotal ++;
10090:                 }
10091:             }
10092:         } else {
10093:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
10094:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10095:                                                    $infotitles,'',$customclass,$rowstyle);
10096:         }
10097:     }
10098:     return $datatable;
10099: }
10100: 
10101: sub selfcreate_javascript {
10102:     return <<"ENDSCRIPT";
10103: 
10104: <script type="text/javascript">
10105: // <![CDATA[
10106: 
10107: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
10108:     var x = document.getElementsByClassName(target);
10109:     var insttypes = 0;
10110:     var insttypeRegExp = new RegExp(prefix);
10111:     if ((x.length != undefined) && (x.length > 0)) {
10112:         if (form.elements[radio].length != undefined) {
10113:             for (var i=0; i<form.elements[radio].length; i++) {
10114:                 if (form.elements[radio][i].checked) {
10115:                     if (form.elements[radio][i].value == 1) {
10116:                         for (var j=0; j<x.length; j++) {
10117:                             if (x[j].id == 'undefined') {
10118:                                 x[j].style.display = 'table-row';
10119:                             } else if (insttypeRegExp.test(x[j].id)) {
10120:                                 insttypes ++;
10121:                             } else {
10122:                                 x[j].style.display = 'table-row';
10123:                             }
10124:                         }
10125:                     } else {
10126:                         for (var j=0; j<x.length; j++) {
10127:                             x[j].style.display = 'none';
10128:                         }
10129:                     }
10130:                     break;
10131:                 }
10132:             }
10133:             if (insttypes > 0) {
10134:                 toggleDataRow(form,checkbox,target,altprefix);
10135:                 toggleDataRow(form,checkbox,target,prefix,1);
10136:             }
10137:         }
10138:     }
10139:     return;
10140: }
10141: 
10142: function toggleDataRow(form,checkbox,target,prefix,docount) {
10143:     if (form.elements[checkbox].length != undefined) {
10144:         var count = 0;
10145:         if (docount) {
10146:             for (var i=0; i<form.elements[checkbox].length; i++) {
10147:                 if (form.elements[checkbox][i].checked) {
10148:                     count ++;
10149:                 }
10150:             }
10151:         }
10152:         for (var i=0; i<form.elements[checkbox].length; i++) {
10153:             var type = form.elements[checkbox][i].value;
10154:             if (document.getElementById(prefix+type)) {
10155:                 if (form.elements[checkbox][i].checked) {
10156:                     document.getElementById(prefix+type).style.display = 'table-row';
10157:                     if (count % 2 == 1) {
10158:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
10159:                     } else {
10160:                         document.getElementById(prefix+type).className = target;
10161:                     }
10162:                     count ++;
10163:                 } else {
10164:                     document.getElementById(prefix+type).style.display = 'none';
10165:                 }
10166:             }
10167:         }
10168:     }
10169:     return;
10170: }
10171: 
10172: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
10173:     var caller = radio+'_'+status;
10174:     if (form.elements[caller].length != undefined) {
10175:         for (var i=0; i<form.elements[caller].length; i++) {
10176:             if (form.elements[caller][i].checked) {
10177:                 if (document.getElementById(altprefix+'_inst_'+status)) {
10178:                     var curr = form.elements[caller][i].value;
10179:                     if (prefix) {
10180:                         document.getElementById(prefix+'_'+status).style.display = 'none';
10181:                     }
10182:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
10183:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
10184:                     if (curr == 'custom') {
10185:                         if (prefix) { 
10186:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
10187:                         }
10188:                     } else if (curr == 'inst') {
10189:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
10190:                     } else if (curr == 'noninst') {
10191:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
10192:                     }
10193:                     break;
10194:                 }
10195:             }
10196:         }
10197:     }
10198: }
10199: 
10200: // ]]>
10201: </script>
10202: 
10203: ENDSCRIPT
10204: }
10205: 
10206: sub noninst_users {
10207:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
10208:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
10209:     my $class = 'LC_left_item';
10210:     if ($css_class) {
10211:         $css_class = ' class="'.$css_class.'"'; 
10212:     }
10213:     if ($rowid) {
10214:         $rowid = ' id="'.$rowid.'"';
10215:     }
10216:     if ($rowstyle) {
10217:         $rowstyle = ' style="'.$rowstyle.'"';
10218:     }
10219:     my ($output,$description);
10220:     if ($type eq 'default') {
10221:         $description = &mt('Requests for: [_1]',$typetitle);
10222:     } else {
10223:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
10224:     }
10225:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
10226:               "<td>$description</td>\n".           
10227:               '<td class="'.$class.'" colspan="2">'.
10228:               '<table><tr>';
10229:     my %headers = &Apache::lonlocal::texthash( 
10230:               approve  => 'Processing',
10231:               email    => 'E-mail',
10232:               username => 'Username',
10233:     );
10234:     foreach my $item ('approve','email','username') {
10235:         $output .= '<th>'.$headers{$item}.'</th>';
10236:     }
10237:     $output .= '</tr><tr>';
10238:     foreach my $item ('approve','email','username') {
10239:         $output .= '<td style="vertical-align: top">';
10240:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
10241:         if ($item eq 'approve') {
10242:             %choices = &Apache::lonlocal::texthash (
10243:                                                      automatic => 'Automatically approved',
10244:                                                      approval  => 'Queued for approval',
10245:                                                    );
10246:             @options = ('automatic','approval');
10247:             $hashref = $processing;
10248:             $defoption = 'automatic';
10249:             $name = 'cancreate_emailprocess_'.$type;
10250:         } elsif ($item eq 'email') {
10251:             %choices = &Apache::lonlocal::texthash (
10252:                                                      any     => 'Any e-mail',
10253:                                                      inst    => 'Institutional only',
10254:                                                      noninst => 'Non-institutional only',
10255:                                                      custom  => 'Custom restrictions',
10256:                                                    );
10257:             @options = ('any','inst','noninst');
10258:             my $showcustom;
10259:             if (ref($emailrules) eq 'HASH') {
10260:                 if (keys(%{$emailrules}) > 0) {
10261:                     push(@options,'custom');
10262:                     $showcustom = 'cancreate_emailrule';
10263:                     if (ref($settings) eq 'HASH') {
10264:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
10265:                             foreach my $rule (@{$settings->{'email_rule'}}) {
10266:                                 if (exists($emailrules->{$rule})) {
10267:                                     $hascustom ++;
10268:                                 }
10269:                             }
10270:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
10271:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
10272:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
10273:                                     if (exists($emailrules->{$rule})) {
10274:                                         $hascustom ++;
10275:                                     }
10276:                                 }
10277:                             }
10278:                         }
10279:                     }
10280:                 }
10281:             }
10282:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
10283:                                                      "'cancreate_emaildomain','$type'".');"';
10284:             $hashref = $emailoptions;
10285:             $defoption = 'any';
10286:             $name = 'cancreate_emailoptions_'.$type;
10287:         } elsif ($item eq 'username') {
10288:             %choices = &Apache::lonlocal::texthash (
10289:                                                      all    => 'Same as e-mail',
10290:                                                      first  => 'Omit @domain',
10291:                                                      free   => 'Free to choose',
10292:                                                    );
10293:             @options = ('all','first','free');
10294:             $hashref = $emailverified;
10295:             $defoption = 'all';
10296:             $name = 'cancreate_usernameoptions_'.$type;
10297:         }
10298:         foreach my $option (@options) {
10299:             my $checked;
10300:             if (ref($hashref) eq 'HASH') {
10301:                 if ($type eq '') {
10302:                     if (!exists($hashref->{'default'})) {
10303:                         if ($option eq $defoption) {
10304:                             $checked = ' checked="checked"';
10305:                         }
10306:                     } else {
10307:                         if ($hashref->{'default'} eq $option) {
10308:                             $checked = ' checked="checked"';
10309:                         }
10310:                     }
10311:                 } else {
10312:                     if (!exists($hashref->{$type})) {
10313:                         if ($option eq $defoption) {
10314:                             $checked = ' checked="checked"';
10315:                         }
10316:                     } else {
10317:                         if ($hashref->{$type} eq $option) {
10318:                             $checked = ' checked="checked"';
10319:                         }
10320:                     }
10321:                 }
10322:             } elsif (($item eq 'email') && ($hascustom)) {
10323:                 if ($option eq 'custom') {
10324:                     $checked = ' checked="checked"';
10325:                 }
10326:             } elsif ($option eq $defoption) {
10327:                 $checked = ' checked="checked"';
10328:             }
10329:             $output .= '<span class="LC_nobreak"><label>'.
10330:                        '<input type="radio" name="'.$name.'"'.
10331:                        $checked.' value="'.$option.'"'.$onclick.' />'.
10332:                        $choices{$option}.'</label></span><br />';
10333:             if ($item eq 'email') {
10334:                 if ($option eq 'custom') {
10335:                     my $id = 'cancreate_emailrule_'.$type;
10336:                     my $display = 'none';
10337:                     if ($checked) {
10338:                         $display = 'inline';
10339:                     }
10340:                     my $numinrow = 2;
10341:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
10342:                                '<legend>'.&mt('Disallow').'</legend><table>'.
10343:                                &user_formats_row('email',$settings,$emailrules,
10344:                                                  $emailruleorder,$numinrow,'',$type);
10345:                               '</table></fieldset>';
10346:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
10347:                     my %text = &Apache::lonlocal::texthash (
10348:                                                              inst    => 'must end:',
10349:                                                              noninst => 'cannot end:',
10350:                                                            );
10351:                     my $value;
10352:                     if (ref($emaildomain) eq 'HASH') {
10353:                         if (ref($emaildomain->{$type}) eq 'HASH') {
10354:                             $value = $emaildomain->{$type}->{$option}; 
10355:                         }
10356:                     }
10357:                     if ($value eq '') {
10358:                         $value = '@'.$intdom;
10359:                     }
10360:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
10361:                     my $display = 'none';
10362:                     if ($checked) {
10363:                         $display = 'inline';
10364:                     }
10365:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
10366:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
10367:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
10368:                                '</div>';
10369:                 }
10370:             }
10371:         }
10372:         $output .= '</td>'."\n";
10373:     }
10374:     $output .= "</tr></table></td></tr>\n";
10375:     return $output;
10376: }
10377: 
10378: sub captcha_choice {
10379:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
10380:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
10381:         $vertext,$currver);
10382:     my %lt = &captcha_phrases();
10383:     $keyentry = 'hidden';
10384:     my $colspan=2;
10385:     if ($context eq 'cancreate') {
10386:         $rowname = &mt('CAPTCHA validation');
10387:     } elsif ($context eq 'login') {
10388:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
10389:     } elsif ($context eq 'passwords') {
10390:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
10391:         $colspan=1;
10392:     }
10393:     if (ref($settings) eq 'HASH') {
10394:         if ($settings->{'captcha'}) {
10395:             $checked{$settings->{'captcha'}} = ' checked="checked"';
10396:         } else {
10397:             $checked{'original'} = ' checked="checked"';
10398:         }
10399:         if ($settings->{'captcha'} eq 'recaptcha') {
10400:             $pubtext = $lt{'pub'};
10401:             $privtext = $lt{'priv'};
10402:             $keyentry = 'text';
10403:             $vertext = $lt{'ver'};
10404:             $currver = $settings->{'recaptchaversion'};
10405:             if ($currver ne '2') {
10406:                 $currver = 1;
10407:             }
10408:         }
10409:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
10410:             $currpub = $settings->{'recaptchakeys'}{'public'};
10411:             $currpriv = $settings->{'recaptchakeys'}{'private'};
10412:         }
10413:     } else {
10414:         $checked{'original'} = ' checked="checked"';
10415:     }
10416:     my $css_class;
10417:     if ($itemcount%2) {
10418:         $css_class = 'LC_odd_row';
10419:     }
10420:     if ($customcss) {
10421:         $css_class .= " $customcss";
10422:     }
10423:     $css_class =~ s/^\s+//;
10424:     if ($css_class) {
10425:         $css_class = ' class="'.$css_class.'"';
10426:     }
10427:     if ($rowstyle) {
10428:         $css_class .= ' style="'.$rowstyle.'"';
10429:     }
10430:     my $output = '<tr'.$css_class.'>'.
10431:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
10432:                  '<table><tr><td>'."\n";
10433:     foreach my $option ('original','recaptcha','notused') {
10434:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
10435:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
10436:                    $lt{$option}.'</label></span>';
10437:         unless ($option eq 'notused') {
10438:             $output .= ('&nbsp;'x2)."\n";
10439:         }
10440:     }
10441: #
10442: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
10443: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
10444: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
10445: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
10446: #
10447:     $output .= '</td></tr>'."\n".
10448:                '<tr><td class="LC_zero_height">'."\n".
10449:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
10450:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
10451:                $currpub.'" size="40" /></span><br />'."\n".
10452:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
10453:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
10454:                $currpriv.'" size="40" /></span><br />'.
10455:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
10456:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
10457:                $currver.'" size="3" /></span><br />'.
10458:                '</td></tr></table>'."\n".
10459:                '</td></tr>';
10460:     return $output;
10461: }
10462: 
10463: sub user_formats_row {
10464:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
10465:     my $output;
10466:     my %text = (
10467:                    'username' => 'new usernames',
10468:                    'id'       => 'IDs',
10469:                );
10470:     unless ($type eq 'email') {
10471:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
10472:         $output = '<tr '.$css_class.'>'.
10473:                   '<td><span class="LC_nobreak">'.
10474:                   &mt("Format rules to check for $text{$type}: ").
10475:                   '</td><td class="LC_left_item" colspan="2"><table>';
10476:     }
10477:     my $rem;
10478:     if (ref($ruleorder) eq 'ARRAY') {
10479:         for (my $i=0; $i<@{$ruleorder}; $i++) {
10480:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
10481:                 my $rem = $i%($numinrow);
10482:                 if ($rem == 0) {
10483:                     if ($i > 0) {
10484:                         $output .= '</tr>';
10485:                     }
10486:                     $output .= '<tr>';
10487:                 }
10488:                 my $check = ' ';
10489:                 if (ref($settings) eq 'HASH') {
10490:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
10491:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
10492:                             $check = ' checked="checked" ';
10493:                         }
10494:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
10495:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
10496:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
10497:                                 $check = ' checked="checked" ';
10498:                             }
10499:                         }
10500:                     }
10501:                 }
10502:                 my $name = $type.'_rule';
10503:                 if ($type eq 'email') {
10504:                     $name .= '_'.$status;
10505:                 }
10506:                 $output .= '<td class="LC_left_item">'.
10507:                            '<span class="LC_nobreak"><label>'.
10508:                            '<input type="checkbox" name="'.$name.'" '.
10509:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
10510:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
10511:             }
10512:         }
10513:         $rem = @{$ruleorder}%($numinrow);
10514:     }
10515:     my $colsleft;
10516:     if ($rem) {
10517:         $colsleft = $numinrow - $rem;
10518:     }
10519:     if ($colsleft > 1 ) {
10520:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10521:                    '&nbsp;</td>';
10522:     } elsif ($colsleft == 1) {
10523:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10524:     }
10525:     $output .= '</tr></table>';
10526:     unless ($type eq 'email') {
10527:         $output .= '</td></tr>';
10528:     }
10529:     return $output;
10530: }
10531: 
10532: sub usercreation_types {
10533:     my %lt = &Apache::lonlocal::texthash (
10534:                     author     => 'When adding a co-author',
10535:                     course     => 'When adding a user to a course',
10536:                     requestcrs => 'When requesting a course',
10537:                     any        => 'Any',
10538:                     official   => 'Institutional only ',
10539:                     unofficial => 'Non-institutional only',
10540:                     none       => 'None',
10541:     );
10542:     return %lt;
10543: }
10544: 
10545: sub selfcreation_types {
10546:     my %lt = &Apache::lonlocal::texthash (
10547:                     selfcreate => 'User creates own account',
10548:                     any        => 'Any',
10549:                     official   => 'Institutional only ',
10550:                     unofficial => 'Non-institutional only',
10551:                     email      => 'E-mail address',
10552:                     login      => 'Institutional Login',
10553:                     sso        => 'SSO',
10554:              );
10555: }
10556: 
10557: sub authtype_names {
10558:     my %lt = &Apache::lonlocal::texthash(
10559:                       int    => 'Internal',
10560:                       krb4   => 'Kerberos 4',
10561:                       krb5   => 'Kerberos 5',
10562:                       loc    => 'Local',
10563:                       lti    => 'LTI',
10564:                   );
10565:     return %lt;
10566: }
10567: 
10568: sub context_names {
10569:     my %context_title = &Apache::lonlocal::texthash(
10570:        author => 'Creating users when an Author',
10571:        course => 'Creating users when in a course',
10572:        domain => 'Creating users when a Domain Coordinator',
10573:     );
10574:     return %context_title;
10575: }
10576: 
10577: sub print_usermodification {
10578:     my ($position,$dom,$settings,$rowtotal) = @_;
10579:     my $numinrow = 4;
10580:     my ($context,$datatable,$rowcount);
10581:     if ($position eq 'top') {
10582:         $rowcount = 0;
10583:         $context = 'author'; 
10584:         foreach my $role ('ca','aa') {
10585:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10586:                                                    $numinrow,$rowcount);
10587:             $$rowtotal ++;
10588:             $rowcount ++;
10589:         }
10590:     } elsif ($position eq 'bottom') {
10591:         $context = 'course';
10592:         $rowcount = 0;
10593:         foreach my $role ('st','ep','ta','in','cr') {
10594:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10595:                                                    $numinrow,$rowcount);
10596:             $$rowtotal ++;
10597:             $rowcount ++;
10598:         }
10599:     }
10600:     return $datatable;
10601: }
10602: 
10603: sub print_defaults {
10604:     my ($position,$dom,$settings,$rowtotal) = @_;
10605:     my $rownum = 0;
10606:     my ($datatable,$css_class,$titles);
10607:     unless ($position eq 'bottom') {
10608:         $titles = &defaults_titles($dom);
10609:     }
10610:     if ($position eq 'top') {
10611:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
10612:                      'datelocale_def','portal_def');
10613:         my %defaults;
10614:         if (ref($settings) eq 'HASH') {
10615:             %defaults = %{$settings};
10616:         } else {
10617:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10618:             foreach my $item (@items) {
10619:                 $defaults{$item} = $domdefaults{$item};
10620:             }
10621:         }
10622:         foreach my $item (@items) {
10623:             if ($rownum%2) {
10624:                 $css_class = '';
10625:             } else {
10626:                 $css_class = ' class="LC_odd_row" ';
10627:             }
10628:             $datatable .= '<tr'.$css_class.'>'.
10629:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
10630:                           '</span></td><td class="LC_right_item" colspan="3">';
10631:             if ($item eq 'auth_def') {
10632:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
10633:                 my %shortauth = (
10634:                                  internal => 'int',
10635:                                  krb4 => 'krb4',
10636:                                  krb5 => 'krb5',
10637:                                  localauth  => 'loc',
10638:                                  lti => 'lti',
10639:                                 );
10640:                 my %authnames = &authtype_names();
10641:                 foreach my $auth (@authtypes) {
10642:                     my $checked = ' ';
10643:                     if ($defaults{$item} eq $auth) {
10644:                         $checked = ' checked="checked" ';
10645:                     }
10646:                     $datatable .= '<label><input type="radio" name="'.$item.
10647:                                   '" value="'.$auth.'"'.$checked.'/>'.
10648:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
10649:                 }
10650:             } elsif ($item eq 'timezone_def') {
10651:                 my $includeempty = 1;
10652:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
10653:             } elsif ($item eq 'datelocale_def') {
10654:                 my $includeempty = 1;
10655:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
10656:             } elsif ($item eq 'lang_def') {
10657:                 my $includeempty = 1;
10658:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
10659:             } else {
10660:                 my $size;
10661:                 if ($item eq 'portal_def') {
10662:                     $size = ' size="25"';
10663:                 }
10664:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
10665:                               $defaults{$item}.'"'.$size.' />';
10666:             }
10667:             $datatable .= '</td></tr>';
10668:             $rownum ++;
10669:         }
10670:     } else {
10671:         my %defaults;
10672:         if (ref($settings) eq 'HASH') {
10673:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10674:                 my $maxnum = @{$settings->{'inststatusorder'}};
10675:                 for (my $i=0; $i<$maxnum; $i++) {
10676:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
10677:                     my $item = $settings->{'inststatusorder'}->[$i];
10678:                     my $title = $settings->{'inststatustypes'}->{$item};
10679:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
10680:                     $datatable .= '<tr'.$css_class.'>'.
10681:                                   '<td><span class="LC_nobreak">'.
10682:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
10683:                     for (my $k=0; $k<=$maxnum; $k++) {
10684:                         my $vpos = $k+1;
10685:                         my $selstr;
10686:                         if ($k == $i) {
10687:                             $selstr = ' selected="selected" ';
10688:                         }
10689:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10690:                     }
10691:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
10692:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
10693:                                   &mt('delete').'</span></td>'.
10694:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
10695:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
10696:                                   '</span></td></tr>';
10697:                 }
10698:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
10699:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
10700:                 $datatable .= '<tr '.$css_class.'>'.
10701:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
10702:                 for (my $k=0; $k<=$maxnum; $k++) {
10703:                     my $vpos = $k+1;
10704:                     my $selstr;
10705:                     if ($k == $maxnum) {
10706:                         $selstr = ' selected="selected" ';
10707:                     }
10708:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10709:                 }
10710:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
10711:                               '<input type="text" size="10" name="addinststatus" value="" />'.
10712:                               '&nbsp;'.&mt('(new)').
10713:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
10714:                               &mt('Name displayed').':'.
10715:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
10716:                               '</tr>'."\n";
10717:                 $rownum ++;
10718:             }
10719:         }
10720:     }
10721:     $$rowtotal += $rownum;
10722:     return $datatable;
10723: }
10724: 
10725: sub get_languages_hash {
10726:     my %langchoices;
10727:     foreach my $id (&Apache::loncommon::languageids()) {
10728:         my $code = &Apache::loncommon::supportedlanguagecode($id);
10729:         if ($code ne '') {
10730:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
10731:         }
10732:     }
10733:     return %langchoices;
10734: }
10735: 
10736: sub defaults_titles {
10737:     my ($dom) = @_;
10738:     my %titles = &Apache::lonlocal::texthash (
10739:                    'auth_def'      => 'Default authentication type',
10740:                    'auth_arg_def'  => 'Default authentication argument',
10741:                    'lang_def'      => 'Default language',
10742:                    'timezone_def'  => 'Default timezone',
10743:                    'datelocale_def' => 'Default locale for dates',
10744:                    'portal_def'     => 'Portal/Default URL',
10745:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
10746:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
10747:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
10748:                  );
10749:     if ($dom) {
10750:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
10751:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
10752:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
10753:         $protocol = 'http' if ($protocol ne 'https');
10754:         if ($uint_dom) {
10755:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
10756:                                          $uint_dom);
10757:         }
10758:     }
10759:     return (\%titles);
10760: }
10761: 
10762: sub print_scantron {
10763:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
10764:     if ($position eq 'top') {
10765:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
10766:     } else {
10767:         return &print_scantronconfig($dom,$settings,\$rowtotal);
10768:     }
10769: }
10770: 
10771: sub scantron_javascript {
10772:     return <<"ENDSCRIPT";
10773: 
10774: <script type="text/javascript">
10775: // <![CDATA[
10776: 
10777: function toggleScantron(form) {
10778:     var csvfieldset = new Array();
10779:     if (document.getElementById('scantroncsv_cols')) {
10780:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
10781:     }
10782:     if (document.getElementById('scantroncsv_options')) {
10783:         csvfieldset.push(document.getElementById('scantroncsv_options'));
10784:     }
10785:     if (csvfieldset.length) {
10786:         if (document.getElementById('scantronconfcsv')) {
10787:             var scantroncsv = document.getElementById('scantronconfcsv');
10788:             if (scantroncsv.checked) {
10789:                 for (var i=0; i<csvfieldset.length; i++) {
10790:                     csvfieldset[i].style.display = 'block';
10791:                 }
10792:             } else {
10793:                 for (var i=0; i<csvfieldset.length; i++) {
10794:                     csvfieldset[i].style.display = 'none';
10795:                 }
10796:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
10797:                 if (csvselects.length) {
10798:                     for (var j=0; j<csvselects.length; j++) {
10799:                         csvselects[j].selectedIndex = 0;
10800:                     }
10801:                 }
10802:             }
10803:         }
10804:     }
10805:     return;
10806: }
10807: // ]]>
10808: </script>
10809: 
10810: ENDSCRIPT
10811: 
10812: }
10813: 
10814: sub print_scantronformat {
10815:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10816:     my $itemcount = 1;
10817:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10818:         %confhash);
10819:     my $switchserver = &check_switchserver($dom,$confname);
10820:     my %lt = &Apache::lonlocal::texthash (
10821:                 default => 'Default bubblesheet format file error',
10822:                 custom  => 'Custom bubblesheet format file error',
10823:              );
10824:     my %scantronfiles = (
10825:         default => 'default.tab',
10826:         custom => 'custom.tab',
10827:     );
10828:     foreach my $key (keys(%scantronfiles)) {
10829:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10830:                               .$scantronfiles{$key};
10831:     }
10832:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10833:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10834:         if (!$switchserver) {
10835:             my $servadm = $r->dir_config('lonAdmEMail');
10836:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10837:             if ($configuserok eq 'ok') {
10838:                 if ($author_ok eq 'ok') {
10839:                     my %legacyfile = (
10840:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10841:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10842:                     );
10843:                     my %md5chk;
10844:                     foreach my $type (keys(%legacyfile)) {
10845:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10846:                         chomp($md5chk{$type});
10847:                     }
10848:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10849:                         foreach my $type (keys(%legacyfile)) {
10850:                             ($scantronurls{$type},my $error) =
10851:                                 &legacy_scantronformat($r,$dom,$confname,
10852:                                                  $type,$legacyfile{$type},
10853:                                                  $scantronurls{$type},
10854:                                                  $scantronfiles{$type});
10855:                             if ($error ne '') {
10856:                                 $error{$type} = $error;
10857:                             }
10858:                         }
10859:                         if (keys(%error) == 0) {
10860:                             $is_custom = 1;
10861:                             $confhash{'scantron'}{'scantronformat'} =
10862:                                 $scantronurls{'custom'};
10863:                             my $putresult =
10864:                                 &Apache::lonnet::put_dom('configuration',
10865:                                                          \%confhash,$dom);
10866:                             if ($putresult ne 'ok') {
10867:                                 $error{'custom'} =
10868:                                     '<span class="LC_error">'.
10869:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10870:                             }
10871:                         }
10872:                     } else {
10873:                         ($scantronurls{'default'},my $error) =
10874:                             &legacy_scantronformat($r,$dom,$confname,
10875:                                           'default',$legacyfile{'default'},
10876:                                           $scantronurls{'default'},
10877:                                           $scantronfiles{'default'});
10878:                         if ($error eq '') {
10879:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10880:                             my $putresult =
10881:                                 &Apache::lonnet::put_dom('configuration',
10882:                                                          \%confhash,$dom);
10883:                             if ($putresult ne 'ok') {
10884:                                 $error{'default'} =
10885:                                     '<span class="LC_error">'.
10886:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10887:                             }
10888:                         } else {
10889:                             $error{'default'} = $error;
10890:                         }
10891:                     }
10892:                 }
10893:             }
10894:         } else {
10895:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10896:         }
10897:     }
10898:     if (ref($settings) eq 'HASH') {
10899:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10900:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10901:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10902:                 $scantronurl = '';
10903:             } else {
10904:                 $scantronurl = $settings->{'scantronformat'};
10905:             }
10906:             $is_custom = 1;
10907:         } else {
10908:             $scantronurl = $scantronurls{'default'};
10909:         }
10910:     } else {
10911:         if ($is_custom) {
10912:             $scantronurl = $scantronurls{'custom'};
10913:         } else {
10914:             $scantronurl = $scantronurls{'default'};
10915:         }
10916:     }
10917:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10918:     $datatable .= '<tr'.$css_class.'>';
10919:     if (!$is_custom) {
10920:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
10921:                       '<span class="LC_nobreak">';
10922:         if ($scantronurl) {
10923:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
10924:                                                          undef,undef,undef,undef,'background-color:#ffffff');
10925:         } else {
10926:             $datatable = &mt('File unavailable for display');
10927:         }
10928:         $datatable .= '</span></td>';
10929:         if (keys(%error) == 0) { 
10930:             $datatable .= '<td style="vertical-align: bottom">';
10931:             if (!$switchserver) {
10932:                 $datatable .= &mt('Upload:').'<br />';
10933:             }
10934:         } else {
10935:             my $errorstr;
10936:             foreach my $key (sort(keys(%error))) {
10937:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10938:             }
10939:             $datatable .= '<td>'.$errorstr;
10940:         }
10941:     } else {
10942:         if (keys(%error) > 0) {
10943:             my $errorstr;
10944:             foreach my $key (sort(keys(%error))) {
10945:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10946:             } 
10947:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
10948:         } elsif ($scantronurl) {
10949:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
10950:                                                        undef,undef,undef,undef,'background-color:#ffffff');
10951:             $datatable .= '<td><span class="LC_nobreak">'.
10952:                           $link.
10953:                           '<label><input type="checkbox" name="scantronformat_del"'.
10954:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
10955:                           '<td><span class="LC_nobreak">&nbsp;'.
10956:                           &mt('Replace:').'</span><br />';
10957:         }
10958:     }
10959:     if (keys(%error) == 0) {
10960:         if ($switchserver) {
10961:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
10962:         } else {
10963:             $datatable .='<span class="LC_nobreak">&nbsp;'.
10964:                          '<input type="file" name="scantronformat" /></span>';
10965:         }
10966:     }
10967:     $datatable .= '</td></tr>';
10968:     $$rowtotal ++;
10969:     return $datatable;
10970: }
10971: 
10972: sub legacy_scantronformat {
10973:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
10974:     my ($url,$error);
10975:     my @statinfo = &Apache::lonnet::stat_file($newurl);
10976:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
10977:         (my $result,$url) =
10978:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
10979:                          '','',$newfile);
10980:         if ($result ne 'ok') {
10981:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
10982:         }
10983:     }
10984:     return ($url,$error);
10985: }
10986: 
10987: sub print_scantronconfig {
10988:     my ($dom,$settings,$rowtotal) = @_;
10989:     my $itemcount = 2;
10990:     my $is_checked = ' checked="checked"';
10991:     my %optionson = (
10992:                      hdr => ' checked="checked"',
10993:                      pad => ' checked="checked"',
10994:                      rem => ' checked="checked"',
10995:                     );
10996:     my %optionsoff = (
10997:                       hdr => '',
10998:                       pad => '',
10999:                       rem => '',
11000:                      );
11001:     my $currcsvsty = 'none';
11002:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
11003:     my @fields = &scantroncsv_fields();
11004:     my %titles = &scantronconfig_titles();
11005:     if (ref($settings) eq 'HASH') {
11006:         if (ref($settings->{config}) eq 'HASH') {
11007:             if ($settings->{config}->{dat}) {
11008:                 $checked{'dat'} = $is_checked;
11009:             }
11010:             if (ref($settings->{config}->{csv}) eq 'HASH') {
11011:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
11012:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
11013:                     if (keys(%csvfields) > 0) {
11014:                         $checked{'csv'} = $is_checked;
11015:                         $currcsvsty = 'block';
11016:                     }
11017:                 }
11018:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
11019:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
11020:                     foreach my $option (keys(%optionson)) {
11021:                         unless ($csvoptions{$option}) {
11022:                             $optionsoff{$option} = $optionson{$option};
11023:                             $optionson{$option} = '';
11024:                         }
11025:                     }
11026:                 }
11027:             }
11028:         } else {
11029:             $checked{'dat'} = $is_checked;
11030:         }
11031:     } else {
11032:         $checked{'dat'} = $is_checked;
11033:     }
11034:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
11035:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11036:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
11037:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
11038:     foreach my $item ('dat','csv') {
11039:         my $id;
11040:         if ($item eq 'csv') {
11041:             $id = 'id="scantronconfcsv" ';
11042:         }
11043:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
11044:                       $titles{$item}.'</label>'.('&nbsp;'x3);
11045:         if ($item eq 'csv') {
11046:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
11047:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
11048:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
11049:             foreach my $col (@fields) {
11050:                 my $selnone;
11051:                 if ($csvfields{$col} eq '') {
11052:                     $selnone = ' selected="selected"';
11053:                 }
11054:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
11055:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
11056:                               '<option value=""'.$selnone.'></option>';
11057:                 for (my $i=0; $i<20; $i++) {
11058:                     my $shown = $i+1;
11059:                     my $sel;
11060:                     unless ($selnone) {
11061:                         if (exists($csvfields{$col})) {
11062:                             if ($csvfields{$col} == $i) {
11063:                                 $sel = ' selected="selected"';
11064:                             }
11065:                         }
11066:                     }
11067:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
11068:                 }
11069:                 $datatable .= '</select></td></tr>';
11070:            }
11071:            $datatable .= '</table></fieldset>'.
11072:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
11073:                          '<legend>'.&mt('CSV Options').'</legend>';
11074:            foreach my $option ('hdr','pad','rem') {
11075:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
11076:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
11077:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
11078:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
11079:            }
11080:            $datatable .= '</fieldset>';
11081:            $itemcount ++;
11082:         }
11083:     }
11084:     $datatable .= '</td></tr>';
11085:     $$rowtotal ++;
11086:     return $datatable;
11087: }
11088: 
11089: sub scantronconfig_titles {
11090:     return &Apache::lonlocal::texthash(
11091:                                           dat => 'Standard format (.dat)',
11092:                                           csv => 'Comma separated values (.csv)',
11093:                                           hdr => 'Remove first line in file (contains column titles)',
11094:                                           pad => 'Prepend 0s to PaperID',
11095:                                           rem => 'Remove leading spaces (except Question Response columns)',
11096:                                           CODE => 'CODE',
11097:                                           ID   => 'Student ID',
11098:                                           PaperID => 'Paper ID',
11099:                                           FirstName => 'First Name',
11100:                                           LastName => 'Last Name',
11101:                                           FirstQuestion => 'First Question Response',
11102:                                           Section => 'Section',
11103:     );
11104: }
11105: 
11106: sub scantroncsv_fields {
11107:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
11108: }
11109: 
11110: sub print_coursecategories {
11111:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
11112:     my $datatable;
11113:     if ($position eq 'top') {
11114:         my (%checked);
11115:         my @catitems = ('unauth','auth');
11116:         my @cattypes = ('std','domonly','codesrch','none');
11117:         $checked{'unauth'} = 'std';
11118:         $checked{'auth'} = 'std';
11119:         if (ref($settings) eq 'HASH') {
11120:             foreach my $type (@cattypes) {
11121:                 if ($type eq $settings->{'unauth'}) {
11122:                     $checked{'unauth'} = $type;
11123:                 }
11124:                 if ($type eq $settings->{'auth'}) {
11125:                     $checked{'auth'} = $type;
11126:                 }
11127:             }
11128:         }
11129:         my %lt = &Apache::lonlocal::texthash (
11130:                                                unauth   => 'Catalog type for unauthenticated users',
11131:                                                auth     => 'Catalog type for authenticated users',
11132:                                                none     => 'No catalog',
11133:                                                std      => 'Standard catalog',
11134:                                                domonly  => 'Domain-only catalog',
11135:                                                codesrch => "Code search form",
11136:                                              );
11137:        my $itemcount = 0;
11138:        foreach my $item (@catitems) {
11139:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11140:            $datatable .= '<tr '.$css_class.'>'.
11141:                          '<td>'.$lt{$item}.'</td>'.
11142:                          '<td class="LC_right_item"><span class="LC_nobreak">';
11143:            foreach my $type (@cattypes) {
11144:                my $ischecked;
11145:                if ($checked{$item} eq $type) {
11146:                    $ischecked=' checked="checked"';
11147:                }
11148:                $datatable .= '<label>'.
11149:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
11150:                              ' />'.$lt{$type}.'</label>&nbsp;';
11151:            }
11152:            $datatable .= '</span></td></tr>';
11153:            $itemcount ++;
11154:         }
11155:         $$rowtotal += $itemcount;
11156:     } elsif ($position eq 'middle') {
11157:         my $toggle_cats_crs = ' ';
11158:         my $toggle_cats_dom = ' checked="checked" ';
11159:         my $can_cat_crs = ' ';
11160:         my $can_cat_dom = ' checked="checked" ';
11161:         my $toggle_catscomm_comm = ' ';
11162:         my $toggle_catscomm_dom = ' checked="checked" ';
11163:         my $can_catcomm_comm = ' ';
11164:         my $can_catcomm_dom = ' checked="checked" ';
11165:         my $toggle_catsplace_place = ' ';
11166:         my $toggle_catsplace_dom = ' checked="checked" ';
11167:         my $can_catplace_place = ' ';
11168:         my $can_catplace_dom = ' checked="checked" ';
11169: 
11170:         if (ref($settings) eq 'HASH') {
11171:             if ($settings->{'togglecats'} eq 'crs') {
11172:                 $toggle_cats_crs = $toggle_cats_dom;
11173:                 $toggle_cats_dom = ' ';
11174:             }
11175:             if ($settings->{'categorize'} eq 'crs') {
11176:                 $can_cat_crs = $can_cat_dom;
11177:                 $can_cat_dom = ' ';
11178:             }
11179:             if ($settings->{'togglecatscomm'} eq 'comm') {
11180:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
11181:                 $toggle_catscomm_dom = ' ';
11182:             }
11183:             if ($settings->{'categorizecomm'} eq 'comm') {
11184:                 $can_catcomm_comm = $can_catcomm_dom;
11185:                 $can_catcomm_dom = ' ';
11186:             }
11187:             if ($settings->{'togglecatsplace'} eq 'place') {
11188:                 $toggle_catsplace_place = $toggle_catsplace_dom;
11189:                 $toggle_catsplace_dom = ' ';
11190:             }
11191:             if ($settings->{'categorizeplace'} eq 'place') {
11192:                 $can_catplace_place = $can_catplace_dom;
11193:                 $can_catplace_dom = ' ';
11194:             }
11195:         }
11196:         my %title = &Apache::lonlocal::texthash (
11197:                      togglecats      => 'Show/Hide a course in catalog',
11198:                      togglecatscomm  => 'Show/Hide a community in catalog',
11199:                      togglecatsplace => 'Show/Hide a placement test in catalog',
11200:                      categorize      => 'Assign a category to a course',
11201:                      categorizecomm  => 'Assign a category to a community',
11202:                      categorizeplace => 'Assign a category to a placement test',
11203:                     );
11204:         my %level = &Apache::lonlocal::texthash (
11205:                      dom   => 'Set in Domain',
11206:                      crs   => 'Set in Course',
11207:                      comm  => 'Set in Community',
11208:                      place => 'Set in Placement Test',
11209:                     );
11210:         $datatable = '<tr class="LC_odd_row">'.
11211:                   '<td>'.$title{'togglecats'}.'</td>'.
11212:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11213:                   '<input type="radio" name="togglecats"'.
11214:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11215:                   '<label><input type="radio" name="togglecats"'.
11216:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
11217:                   '</tr><tr>'.
11218:                   '<td>'.$title{'categorize'}.'</td>'.
11219:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11220:                   '<label><input type="radio" name="categorize"'.
11221:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11222:                   '<label><input type="radio" name="categorize"'.
11223:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
11224:                   '</tr><tr class="LC_odd_row">'.
11225:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
11226:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11227:                   '<input type="radio" name="togglecatscomm"'.
11228:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11229:                   '<label><input type="radio" name="togglecatscomm"'.
11230:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
11231:                   '</tr><tr>'.
11232:                   '<td>'.$title{'categorizecomm'}.'</td>'.
11233:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11234:                   '<label><input type="radio" name="categorizecomm"'.
11235:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11236:                   '<label><input type="radio" name="categorizecomm"'.
11237:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
11238:                   '</tr><tr class="LC_odd_row">'.
11239:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
11240:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11241:                   '<input type="radio" name="togglecatsplace"'.
11242:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11243:                   '<label><input type="radio" name="togglecatscomm"'.
11244:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
11245:                   '</tr><tr>'.
11246:                   '<td>'.$title{'categorizeplace'}.'</td>'.
11247:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11248:                   '<label><input type="radio" name="categorizeplace"'.
11249:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11250:                   '<label><input type="radio" name="categorizeplace"'.
11251:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
11252:                   '</tr>';
11253:         $$rowtotal += 6;
11254:     } else {
11255:         my $css_class;
11256:         my $itemcount = 1;
11257:         my $cathash; 
11258:         if (ref($settings) eq 'HASH') {
11259:             $cathash = $settings->{'cats'};
11260:         }
11261:         if (ref($cathash) eq 'HASH') {
11262:             my (@cats,@trails,%allitems,%idx,@jsarray);
11263:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
11264:                                                    \%allitems,\%idx,\@jsarray);
11265:             my $maxdepth = scalar(@cats);
11266:             my $colattrib = '';
11267:             if ($maxdepth > 2) {
11268:                 $colattrib = ' colspan="2" ';
11269:             }
11270:             my @path;
11271:             if (@cats > 0) {
11272:                 if (ref($cats[0]) eq 'ARRAY') {
11273:                     my $numtop = @{$cats[0]};
11274:                     my $maxnum = $numtop;
11275:                     my %default_names = (
11276:                           instcode    => &mt('Official courses'),
11277:                           communities => &mt('Communities'),
11278:                           placement   => &mt('Placement Tests'),
11279:                     );
11280: 
11281:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
11282:                         ($cathash->{'instcode::0'} eq '') ||
11283:                         (!grep(/^communities$/,@{$cats[0]})) || 
11284:                         ($cathash->{'communities::0'} eq '') ||
11285:                         (!grep(/^placement$/,@{$cats[0]})) ||
11286:                         ($cathash->{'placement::0'} eq '')) {
11287:                         $maxnum ++;
11288:                     }
11289:                     my $lastidx;
11290:                     for (my $i=0; $i<$numtop; $i++) {
11291:                         my $parent = $cats[0][$i];
11292:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11293:                         my $item = &escape($parent).'::0';
11294:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
11295:                         $lastidx = $idx{$item};
11296:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11297:                                       .'<select name="'.$item.'"'.$chgstr.'>';
11298:                         for (my $k=0; $k<=$maxnum; $k++) {
11299:                             my $vpos = $k+1;
11300:                             my $selstr;
11301:                             if ($k == $i) {
11302:                                 $selstr = ' selected="selected" ';
11303:                             }
11304:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11305:                         }
11306:                         $datatable .= '</select></span></td><td>';
11307:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
11308:                             $datatable .=  '<span class="LC_nobreak">'
11309:                                            .$default_names{$parent}.'</span>';
11310:                             if ($parent eq 'instcode') {
11311:                                 $datatable .= '<br /><span class="LC_nobreak">('
11312:                                               .&mt('with institutional codes')
11313:                                               .')</span></td><td'.$colattrib.'>';
11314:                             } else {
11315:                                 $datatable .= '<table><tr><td>';
11316:                             }
11317:                             $datatable .= '<span class="LC_nobreak">'
11318:                                           .'<label><input type="radio" name="'
11319:                                           .$parent.'" value="1" checked="checked" />'
11320:                                           .&mt('Display').'</label>';
11321:                             if ($parent eq 'instcode') {
11322:                                 $datatable .= '&nbsp;';
11323:                             } else {
11324:                                 $datatable .= '</span></td></tr><tr><td>'
11325:                                               .'<span class="LC_nobreak">';
11326:                             }
11327:                             $datatable .= '<label><input type="radio" name="'
11328:                                           .$parent.'" value="0" />'
11329:                                           .&mt('Do not display').'</label></span>';
11330:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
11331:                                 $datatable .= '</td></tr></table>';
11332:                             }
11333:                             $datatable .= '</td>';
11334:                         } else {
11335:                             $datatable .= $parent
11336:                                           .'&nbsp;<span class="LC_nobreak"><label>'
11337:                                           .'<input type="checkbox" name="deletecategory" '
11338:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
11339:                         }
11340:                         my $depth = 1;
11341:                         push(@path,$parent);
11342:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
11343:                         pop(@path);
11344:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
11345:                         $itemcount ++;
11346:                     }
11347:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11348:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
11349:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
11350:                     for (my $k=0; $k<=$maxnum; $k++) {
11351:                         my $vpos = $k+1;
11352:                         my $selstr;
11353:                         if ($k == $numtop) {
11354:                             $selstr = ' selected="selected" ';
11355:                         }
11356:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11357:                     }
11358:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
11359:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
11360:                                   .'</tr>'."\n";
11361:                     $itemcount ++;
11362:                     foreach my $default ('instcode','communities','placement') {
11363:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
11364:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
11365:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
11366:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
11367:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
11368:                             for (my $k=0; $k<=$maxnum; $k++) {
11369:                                 my $vpos = $k+1;
11370:                                 my $selstr;
11371:                                 if ($k == $maxnum) {
11372:                                     $selstr = ' selected="selected" ';
11373:                                 }
11374:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11375:                             }
11376:                             $datatable .= '</select></span></td>'.
11377:                                           '<td><span class="LC_nobreak">'.
11378:                                           $default_names{$default}.'</span>';
11379:                             if ($default eq 'instcode') {
11380:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
11381:                                               .&mt('with institutional codes').')</span>';
11382:                             }
11383:                             $datatable .= '</td>'
11384:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
11385:                                           .&mt('Display').'</label>&nbsp;'
11386:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
11387:                                           .&mt('Do not display').'</label></span></td></tr>';
11388:                         }
11389:                     }
11390:                 }
11391:             } else {
11392:                 $datatable .= &initialize_categories($itemcount);
11393:             }
11394:         } else {
11395:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
11396:                           .&initialize_categories($itemcount);
11397:         }
11398:         $$rowtotal += $itemcount;
11399:     }
11400:     return $datatable;
11401: }
11402: 
11403: sub print_serverstatuses {
11404:     my ($dom,$settings,$rowtotal) = @_;
11405:     my $datatable;
11406:     my @pages = &serverstatus_pages();
11407:     my (%namedaccess,%machineaccess);
11408:     foreach my $type (@pages) {
11409:         $namedaccess{$type} = '';
11410:         $machineaccess{$type}= '';
11411:     }
11412:     if (ref($settings) eq 'HASH') {
11413:         foreach my $type (@pages) {
11414:             if (exists($settings->{$type})) {
11415:                 if (ref($settings->{$type}) eq 'HASH') {
11416:                     foreach my $key (keys(%{$settings->{$type}})) {
11417:                         if ($key eq 'namedusers') {
11418:                             $namedaccess{$type} = $settings->{$type}->{$key};
11419:                         } elsif ($key eq 'machines') {
11420:                             $machineaccess{$type} = $settings->{$type}->{$key};
11421:                         }
11422:                     }
11423:                 }
11424:             }
11425:         }
11426:     }
11427:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11428:     my $rownum = 0;
11429:     my $css_class;
11430:     foreach my $type (@pages) {
11431:         $rownum ++;
11432:         $css_class = $rownum%2?' class="LC_odd_row"':'';
11433:         $datatable .= '<tr'.$css_class.'>'.
11434:                       '<td><span class="LC_nobreak">'.
11435:                       $titles->{$type}.'</span></td>'.
11436:                       '<td class="LC_left_item">'.
11437:                       '<input type="text" name="'.$type.'_namedusers" '.
11438:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
11439:                       '<td class="LC_right_item">'.
11440:                       '<span class="LC_nobreak">'.
11441:                       '<input type="text" name="'.$type.'_machines" '.
11442:                       'value="'.$machineaccess{$type}.'" size="10" />'.
11443:                       '</span></td></tr>'."\n";
11444:     }
11445:     $$rowtotal += $rownum;
11446:     return $datatable;
11447: }
11448: 
11449: sub serverstatus_pages {
11450:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
11451:             'checksums','clusterstatus','certstatus','metadata_keywords',
11452:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
11453:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
11454: }
11455: 
11456: sub defaults_javascript {
11457:     my ($settings) = @_;
11458:     return unless (ref($settings) eq 'HASH');
11459:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
11460:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
11461:         if ($maxnum eq '') {
11462:             $maxnum = 0;
11463:         }
11464:         $maxnum ++;
11465:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
11466:         return <<"ENDSCRIPT";
11467: <script type="text/javascript">
11468: // <![CDATA[
11469: function reorderTypes(form,caller) {
11470:     var changedVal;
11471: $jstext 
11472:     var newpos = 'addinststatus_pos';
11473:     var current = new Array;
11474:     var maxh = $maxnum;
11475:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11476:     var oldVal;
11477:     if (caller == newpos) {
11478:         changedVal = newitemVal;
11479:     } else {
11480:         var curritem = 'inststatus_pos_'+caller;
11481:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
11482:         current[newitemVal] = newpos;
11483:     }
11484:     for (var i=0; i<inststatuses.length; i++) {
11485:         if (inststatuses[i] != caller) {
11486:             var elementName = 'inststatus_pos_'+inststatuses[i];
11487:             if (form.elements[elementName]) {
11488:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11489:                 current[currVal] = elementName;
11490:             }
11491:         }
11492:     }
11493:     for (var j=0; j<maxh; j++) {
11494:         if (current[j] == undefined) {
11495:             oldVal = j;
11496:         }
11497:     }
11498:     if (oldVal < changedVal) {
11499:         for (var k=oldVal+1; k<=changedVal ; k++) {
11500:            var elementName = current[k];
11501:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11502:         }
11503:     } else {
11504:         for (var k=changedVal; k<oldVal; k++) {
11505:             var elementName = current[k];
11506:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11507:         }
11508:     }
11509:     return;
11510: }
11511: 
11512: // ]]>
11513: </script>
11514: 
11515: ENDSCRIPT
11516:     }
11517:     return;
11518: }
11519: 
11520: sub passwords_javascript {
11521:     my ($prefix) = @_;
11522:     my %intalert;
11523:     if ($prefix eq 'passwords') {
11524:         %intalert = &Apache::lonlocal::texthash (
11525:             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.',
11526:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
11527:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
11528:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
11529:             passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
11530:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
11531:         );
11532:     } elsif ($prefix eq 'secrets') {
11533:         %intalert = &Apache::lonlocal::texthash (
11534:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
11535:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
11536:         );
11537:     }
11538:     &js_escape(\%intalert);
11539:     my $defmin = $Apache::lonnet::passwdmin;
11540:     my $intauthjs; 
11541:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
11542: 
11543: function warnIntAuth(field) {
11544:     if (field.name == 'intauth_check') {
11545:         if (field.value == '2') {
11546:             alert('$intalert{authcheck}');
11547:         }
11548:     }
11549:     if (field.name == 'intauth_cost') {
11550:         field.value.replace(/\s/g,'');
11551:         if (field.value != '') {
11552:             var regexdigit=/^\\d+\$/;
11553:             if (!regexdigit.test(field.value)) {
11554:                 alert('$intalert{authcost}');
11555:             }
11556:         }
11557:     }
11558:     return;
11559: }
11560: 
11561: ENDSCRIPT
11562: 
11563:      }
11564: 
11565:      $intauthjs .= <<"ENDSCRIPT";
11566: 
11567: function warnInt$prefix(field) {
11568:     field.value.replace(/^\s+/,'');
11569:     field.value.replace(/\s+\$/,'');
11570:     var regexdigit=/^\\d+\$/;
11571:     if (field.name == '$prefix\_min') {
11572:         if (field.value == '') {
11573:             alert('$intalert{passmin}');
11574:             field.value = '$defmin';
11575:         } else {
11576:             if (!regexdigit.test(field.value)) {
11577:                 alert('$intalert{passmin}');
11578:                 field.value = '$defmin';
11579:             }
11580:             var minval = parseInt(field.value,10);
11581:             if (minval < $defmin) {
11582:                 alert('$intalert{passmin}');
11583:                 field.value = '$defmin';
11584:             }
11585:         }
11586:     } else {
11587:         if (field.value == '0') {
11588:             field.value = '';
11589:         }
11590:         if (field.value != '') {
11591:             if (field.name == '$prefix\_expire') {
11592:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
11593:                 if (!regexpposnum.test(field.value)) {
11594:                     alert('$intalert{passexp}');
11595:                     field.value = '';
11596:                 } else {
11597:                     var expval = parseFloat(field.value);
11598:                     if (expval == 0) {
11599:                         alert('$intalert{passexp}');
11600:                         field.value = '';
11601:                     }
11602:                 }
11603:             } else {
11604:                 if (!regexdigit.test(field.value)) {
11605:                     if (field.name == '$prefix\_max') {
11606:                         alert('$intalert{passmax}');
11607:                     } else {
11608:                         if (field.name == '$prefix\_numsaved') {
11609:                             alert('$intalert{passnum}');
11610:                         }
11611:                     }
11612:                     field.value = '';
11613:                 }
11614:             }
11615:         }
11616:     }
11617:     return;
11618: }
11619: 
11620: ENDSCRIPT
11621:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
11622: }
11623: 
11624: sub coursecategories_javascript {
11625:     my ($settings) = @_;
11626:     my ($output,$jstext,$cathash);
11627:     if (ref($settings) eq 'HASH') {
11628:         $cathash = $settings->{'cats'};
11629:     }
11630:     if (ref($cathash) eq 'HASH') {
11631:         my (@cats,@jsarray,%idx);
11632:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
11633:         if (@jsarray > 0) {
11634:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
11635:             for (my $i=0; $i<@jsarray; $i++) {
11636:                 if (ref($jsarray[$i]) eq 'ARRAY') {
11637:                     my $catstr = join('","',@{$jsarray[$i]});
11638:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
11639:                 }
11640:             }
11641:         }
11642:     } else {
11643:         $jstext  = '    var categories = Array(1);'."\n".
11644:                    '    categories[0] = Array("instcode_pos");'."\n"; 
11645:     }
11646:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
11647:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
11648:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
11649:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
11650:     &js_escape(\$instcode_reserved);
11651:     &js_escape(\$communities_reserved);
11652:     &js_escape(\$placement_reserved);
11653:     &js_escape(\$choose_again);
11654:     $output = <<"ENDSCRIPT";
11655: <script type="text/javascript">
11656: // <![CDATA[
11657: function reorderCats(form,parent,item,idx) {
11658:     var changedVal;
11659: $jstext
11660:     var newpos = 'addcategory_pos';
11661:     if (parent == '') {
11662:         var has_instcode = 0;
11663:         var maxtop = categories[idx].length;
11664:         for (var j=0; j<maxtop; j++) {
11665:             if (categories[idx][j] == 'instcode::0') {
11666:                 has_instcode == 1;
11667:             }
11668:         }
11669:         if (has_instcode == 0) {
11670:             categories[idx][maxtop] = 'instcode_pos';
11671:         }
11672:     } else {
11673:         newpos += '_'+parent;
11674:     }
11675:     var maxh = 1 + categories[idx].length;
11676:     var current = new Array;
11677:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11678:     if (item == newpos) {
11679:         changedVal = newitemVal;
11680:     } else {
11681:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
11682:         current[newitemVal] = newpos;
11683:     }
11684:     for (var i=0; i<categories[idx].length; i++) {
11685:         var elementName = categories[idx][i];
11686:         if (elementName != item) {
11687:             if (form.elements[elementName]) {
11688:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11689:                 current[currVal] = elementName;
11690:             }
11691:         }
11692:     }
11693:     var oldVal;
11694:     for (var j=0; j<maxh; j++) {
11695:         if (current[j] == undefined) {
11696:             oldVal = j;
11697:         }
11698:     }
11699:     if (oldVal < changedVal) {
11700:         for (var k=oldVal+1; k<=changedVal ; k++) {
11701:            var elementName = current[k];
11702:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11703:         }
11704:     } else {
11705:         for (var k=changedVal; k<oldVal; k++) {
11706:             var elementName = current[k];
11707:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11708:         }
11709:     }
11710:     return;
11711: }
11712: 
11713: function categoryCheck(form) {
11714:     if (form.elements['addcategory_name'].value == 'instcode') {
11715:         alert('$instcode_reserved\\n$choose_again');
11716:         return false;
11717:     }
11718:     if (form.elements['addcategory_name'].value == 'communities') {
11719:         alert('$communities_reserved\\n$choose_again');
11720:         return false;
11721:     }
11722:     if (form.elements['addcategory_name'].value == 'placement') {
11723:         alert('$placement_reserved\\n$choose_again');
11724:         return false;
11725:     }
11726:     return true;
11727: }
11728: 
11729: // ]]>
11730: </script>
11731: 
11732: ENDSCRIPT
11733:     return $output;
11734: }
11735: 
11736: sub initialize_categories {
11737:     my ($itemcount) = @_;
11738:     my ($datatable,$css_class,$chgstr);
11739:     my %default_names = &Apache::lonlocal::texthash (
11740:                       instcode    => 'Official courses (with institutional codes)',
11741:                       communities => 'Communities',
11742:                       placement   => 'Placement Tests',
11743:                         );
11744:     my %selnum = (
11745:                    instcode    => '0',
11746:                    communities => '1',
11747:                    placement   => '2',
11748:                  );
11749:     my %selected;
11750:     foreach my $default ('instcode','communities','placement') {
11751:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11752:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
11753:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
11754:         $selected{$selnum{$default}} = ' selected="selected"';
11755:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11756:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
11757:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
11758:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
11759:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
11760:                      .'<option value="3">4</option></select>&nbsp;'
11761:                      .$default_names{$default}
11762:                      .'</span></td><td><span class="LC_nobreak">'
11763:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
11764:                      .&mt('Display').'</label>&nbsp;<label>'
11765:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
11766:                  .'</label></span></td></tr>';
11767:         $itemcount ++;
11768:     }
11769:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11770:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
11771:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11772:                   .'<select name="addcategory_pos"'.$chgstr.'>'
11773:                   .'<option value="0">1</option>'
11774:                   .'<option value="1">2</option>'
11775:                   .'<option value="2">3</option>'
11776:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
11777:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
11778:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
11779:                   .'</td></tr>';
11780:     return $datatable;
11781: }
11782: 
11783: sub build_category_rows {
11784:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
11785:     my ($text,$name,$item,$chgstr);
11786:     if (ref($cats) eq 'ARRAY') {
11787:         my $maxdepth = scalar(@{$cats});
11788:         if (ref($cats->[$depth]) eq 'HASH') {
11789:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
11790:                 my $numchildren = @{$cats->[$depth]{$parent}};
11791:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11792:                 $text .= '<td><table class="LC_data_table">';
11793:                 my ($idxnum,$parent_name,$parent_item);
11794:                 my $higher = $depth - 1;
11795:                 if ($higher == 0) {
11796:                     $parent_name = &escape($parent).'::'.$higher;
11797:                 } else {
11798:                     if (ref($path) eq 'ARRAY') {
11799:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11800:                     }
11801:                 }
11802:                 $parent_item = 'addcategory_pos_'.$parent_name;
11803:                 for (my $j=0; $j<=$numchildren; $j++) {
11804:                     if ($j < $numchildren) {
11805:                         $name = $cats->[$depth]{$parent}[$j];
11806:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
11807:                         $idxnum = $idx->{$item};
11808:                     } else {
11809:                         $name = $parent_name;
11810:                         $item = $parent_item;
11811:                     }
11812:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
11813:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
11814:                     for (my $i=0; $i<=$numchildren; $i++) {
11815:                         my $vpos = $i+1;
11816:                         my $selstr;
11817:                         if ($j == $i) {
11818:                             $selstr = ' selected="selected" ';
11819:                         }
11820:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
11821:                     }
11822:                     $text .= '</select>&nbsp;';
11823:                     if ($j < $numchildren) {
11824:                         my $deeper = $depth+1;
11825:                         $text .= $name.'&nbsp;'
11826:                                  .'<label><input type="checkbox" name="deletecategory" value="'
11827:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
11828:                         if(ref($path) eq 'ARRAY') {
11829:                             push(@{$path},$name);
11830:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11831:                             pop(@{$path});
11832:                         }
11833:                     } else {
11834:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11835:                         if ($j == $numchildren) {
11836:                             $text .= $name;
11837:                         } else {
11838:                             $text .= $item;
11839:                         }
11840:                         $text .= '" value="" />';
11841:                     }
11842:                     $text .= '</td></tr>';
11843:                 }
11844:                 $text .= '</table></td>';
11845:             } else {
11846:                 my $higher = $depth-1;
11847:                 if ($higher == 0) {
11848:                     $name = &escape($parent).'::'.$higher;
11849:                 } else {
11850:                     if (ref($path) eq 'ARRAY') {
11851:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11852:                     }
11853:                 }
11854:                 my $colspan;
11855:                 if ($parent ne 'instcode') {
11856:                     $colspan = $maxdepth - $depth - 1;
11857:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11858:                 }
11859:             }
11860:         }
11861:     }
11862:     return $text;
11863: }
11864: 
11865: sub modifiable_userdata_row {
11866:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11867:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11868:     my ($role,$rolename,$statustype);
11869:     $role = $item;
11870:     if ($context eq 'cancreate') {
11871:         if ($item =~ /^(emailusername)_(.+)$/) {
11872:             $role = $1;
11873:             $statustype = $2;
11874:             if (ref($usertypes) eq 'HASH') {
11875:                 if ($usertypes->{$statustype}) {
11876:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11877:                 } else {
11878:                     $rolename = &mt('Data provided by user');
11879:                 }
11880:             }
11881:         }
11882:     } elsif ($context eq 'selfcreate') {
11883:         if (ref($usertypes) eq 'HASH') {
11884:             $rolename = $usertypes->{$role};
11885:         } else {
11886:             $rolename = $role;
11887:         }
11888:     } elsif ($context eq 'lti') {
11889:         $rolename = &mt('Institutional data used (if available)');
11890:     } elsif ($context eq 'privacy') {
11891:         $rolename = $itemdesc;
11892:     } else {
11893:         if ($role eq 'cr') {
11894:             $rolename = &mt('Custom role');
11895:         } else {
11896:             $rolename = &Apache::lonnet::plaintext($role);
11897:         }
11898:     }
11899:     my (@fields,%fieldtitles);
11900:     if (ref($fieldsref) eq 'ARRAY') {
11901:         @fields = @{$fieldsref};
11902:     } else {
11903:         @fields = ('lastname','firstname','middlename','generation',
11904:                    'permanentemail','id');
11905:     }
11906:     if ((ref($titlesref) eq 'HASH')) {
11907:         %fieldtitles = %{$titlesref};
11908:     } else {
11909:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11910:     }
11911:     my $output;
11912:     my $css_class;
11913:     if ($rowcount%2) {
11914:         $css_class = 'LC_odd_row';
11915:     }
11916:     if ($customcss) {
11917:         $css_class .= " $customcss";
11918:     }
11919:     $css_class =~ s/^\s+//;
11920:     if ($css_class) {
11921:         $css_class = ' class="'.$css_class.'"';
11922:     }
11923:     if ($rowstyle) {
11924:         $css_class .= ' style="'.$rowstyle.'"';
11925:     }
11926:     if ($rowid) {
11927:         $rowid = ' id="'.$rowid.'"';
11928:     }
11929:     $output = '<tr '.$css_class.$rowid.'>'.
11930:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
11931:               '<td class="LC_left_item" colspan="2"><table>';
11932:     my $rem;
11933:     my %checks;
11934:     my %current;
11935:     if (ref($settings) eq 'HASH') {
11936:         my $hashref;
11937:         if ($context eq 'lti') {
11938:             if (ref($settings) eq 'HASH') {
11939:                 $hashref = $settings->{'instdata'};
11940:             }
11941:         } elsif ($context eq 'privacy') {
11942:             my ($key,$inner) = split(/_/,$role);
11943:             if (ref($settings) eq 'HASH') {
11944:                 if (ref($settings->{$key}) eq 'HASH') {
11945:                     $hashref = $settings->{$key}->{$inner};
11946:                 }
11947:             }
11948:         } elsif (ref($settings->{$context}) eq 'HASH') {
11949:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
11950:                 $hashref = $settings->{'lti_instdata'};
11951:             }
11952:             if ($role eq 'emailusername') {
11953:                 if ($statustype) {
11954:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
11955:                         $hashref = $settings->{$context}->{$role}->{$statustype};
11956:                     }
11957:                 }
11958:             }
11959:         }
11960:         if (ref($hashref) eq 'HASH') { 
11961:             foreach my $field (@fields) {
11962:                 if ($hashref->{$field}) {
11963:                     if ($role eq 'emailusername') {
11964:                         $checks{$field} = $hashref->{$field};
11965:                     } else {
11966:                         $checks{$field} = ' checked="checked" ';
11967:                     }
11968:                 }
11969:             }
11970:         }
11971:     }
11972:  
11973:     my $total = scalar(@fields);
11974:     for (my $i=0; $i<$total; $i++) {
11975:         $rem = $i%($numinrow);
11976:         if ($rem == 0) {
11977:             if ($i > 0) {
11978:                 $output .= '</tr>';
11979:             }
11980:             $output .= '<tr>';
11981:         }
11982:         my $check = ' ';
11983:         unless ($role eq 'emailusername') {
11984:             if (exists($checks{$fields[$i]})) {
11985:                 $check = $checks{$fields[$i]};
11986:             } elsif ($context eq 'privacy') {
11987:                 if ($role =~ /^priv_(domain|course)$/) {
11988:                     if (ref($settings) ne 'HASH') {
11989:                         $check = ' checked="checked" ';
11990:                     }
11991:                 } elsif ($role =~ /^priv_(author|community)$/) {
11992:                     if (ref($settings) ne 'HASH') {
11993:                         unless ($fields[$i] eq 'id') {
11994:                             $check = ' checked="checked" ';
11995:                         }
11996:                     }
11997:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
11998:                     if (ref($settings) ne 'HASH') {
11999:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
12000:                             $check = ' checked="checked" ';
12001:                         }
12002:                     }
12003:                 }
12004:             } elsif ($context ne 'lti') {
12005:                 if ($role eq 'st') {
12006:                     if (ref($settings) ne 'HASH') {
12007:                         $check = ' checked="checked" '; 
12008:                     }
12009:                 }
12010:             }
12011:         }
12012:         $output .= '<td class="LC_left_item">'.
12013:                    '<span class="LC_nobreak">';
12014:         my $prefix = 'canmodify';
12015:         if ($role eq 'emailusername') {
12016:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
12017:                 $checks{$fields[$i]} = 'omit';
12018:             }
12019:             foreach my $option ('required','optional','omit') {
12020:                 my $checked='';
12021:                 if ($checks{$fields[$i]} eq $option) {
12022:                     $checked='checked="checked" ';
12023:                 }
12024:                 $output .= '<label>'.
12025:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
12026:                            &mt($option).'</label>'.('&nbsp;' x2);
12027:             }
12028:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
12029:         } else {
12030:             if ($context eq 'lti') {
12031:                 $prefix = 'lti';
12032:             } elsif ($context eq 'privacy') {
12033:                 $prefix = 'privacy';
12034:             }
12035:             $output .= '<label>'.
12036:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
12037:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
12038:                        '</label>';
12039:         }
12040:         $output .= '</span></td>';
12041:     }
12042:     $rem = $total%$numinrow;
12043:     my $colsleft;
12044:     if ($rem) {
12045:         $colsleft = $numinrow - $rem;
12046:     }
12047:     if ($colsleft > 1) {
12048:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
12049:                    '&nbsp;</td>';
12050:     } elsif ($colsleft == 1) {
12051:         $output .= '<td class="LC_left_item">&nbsp;</td>';
12052:     }
12053:     $output .= '</tr></table></td></tr>';
12054:     return $output;
12055: }
12056: 
12057: sub insttypes_row {
12058:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
12059:         $customcss,$rowstyle) = @_;
12060:     my %lt = &Apache::lonlocal::texthash (
12061:                       cansearch => 'Users allowed to search',
12062:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
12063:                       lockablenames => 'User preference to lock name',
12064:                       selfassign    => 'Self-reportable affiliations',
12065:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
12066:              );
12067:     my $showdom;
12068:     if ($context eq 'cansearch') {
12069:         $showdom = ' ('.$dom.')';
12070:     }
12071:     my $class = 'LC_left_item';
12072:     if ($context eq 'statustocreate') {
12073:         $class = 'LC_right_item';
12074:     }
12075:     my $css_class;
12076:     if ($$rowtotal%2) {
12077:         $css_class = 'LC_odd_row';
12078:     }
12079:     if ($customcss) {
12080:         $css_class .= ' '.$customcss;
12081:     }
12082:     $css_class =~ s/^\s+//;
12083:     if ($css_class) {
12084:         $css_class = ' class="'.$css_class.'"';
12085:     }
12086:     if ($rowstyle) {
12087:         $css_class .= ' style="'.$rowstyle.'"';
12088:     }
12089:     if ($onclick) {
12090:         $onclick = 'onclick="'.$onclick.'" ';
12091:     }
12092:     my $output = '<tr'.$css_class.'>'.
12093:                  '<td>'.$lt{$context}.$showdom.
12094:                  '</td><td class="'.$class.'" colspan="2"><table>';
12095:     my $rem;
12096:     if (ref($types) eq 'ARRAY') {
12097:         for (my $i=0; $i<@{$types}; $i++) {
12098:             if (defined($usertypes->{$types->[$i]})) {
12099:                 my $rem = $i%($numinrow);
12100:                 if ($rem == 0) {
12101:                     if ($i > 0) {
12102:                         $output .= '</tr>';
12103:                     }
12104:                     $output .= '<tr>';
12105:                 }
12106:                 my $check = ' ';
12107:                 if (ref($settings) eq 'HASH') {
12108:                     if (ref($settings->{$context}) eq 'ARRAY') {
12109:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
12110:                             $check = ' checked="checked" ';
12111:                         }
12112:                     } elsif (ref($settings->{$context}) eq 'HASH') {
12113:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
12114:                             $check = ' checked="checked" ';
12115:                         }
12116:                     } elsif ($context eq 'statustocreate') {
12117:                         $check = ' checked="checked" ';
12118:                     }
12119:                 }
12120:                 $output .= '<td class="LC_left_item">'.
12121:                            '<span class="LC_nobreak"><label>'.
12122:                            '<input type="checkbox" name="'.$context.'" '.
12123:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
12124:                            $usertypes->{$types->[$i]}.'</label></span></td>';
12125:             }
12126:         }
12127:         $rem = @{$types}%($numinrow);
12128:     }
12129:     my $colsleft = $numinrow - $rem;
12130:     if ($context eq 'overrides') {
12131:         if ($colsleft > 1) {
12132:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12133:         } else {
12134:             $output .= '<td class="LC_left_item">';
12135:         }
12136:         $output .= '&nbsp;';  
12137:     } else {
12138:         if ($rem == 0) {
12139:             $output .= '<tr>';
12140:         }
12141:         if ($colsleft > 1) {
12142:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12143:         } else {
12144:             $output .= '<td class="LC_left_item">';
12145:         }
12146:         my $defcheck = ' ';
12147:         if (ref($settings) eq 'HASH') {  
12148:             if (ref($settings->{$context}) eq 'ARRAY') {
12149:                 if (grep(/^default$/,@{$settings->{$context}})) {
12150:                     $defcheck = ' checked="checked" ';
12151:                 }
12152:             } elsif ($context eq 'statustocreate') {
12153:                 $defcheck = ' checked="checked" ';
12154:             }
12155:         }
12156:         $output .= '<span class="LC_nobreak"><label>'.
12157:                    '<input type="checkbox" name="'.$context.'" '.
12158:                    'value="default"'.$defcheck.$onclick.' />'.
12159:                    $othertitle.'</label></span>';
12160:     }
12161:     $output .= '</td></tr></table></td></tr>';
12162:     return $output;
12163: }
12164: 
12165: sub sorted_searchtitles {
12166:     my %searchtitles = &Apache::lonlocal::texthash(
12167:                          'uname' => 'username',
12168:                          'lastname' => 'last name',
12169:                          'lastfirst' => 'last name, first name',
12170:                      );
12171:     my @titleorder = ('uname','lastname','lastfirst');
12172:     return (\%searchtitles,\@titleorder);
12173: }
12174: 
12175: sub sorted_searchtypes {
12176:     my %srchtypes_desc = (
12177:                            exact    => 'is exact match',
12178:                            contains => 'contains ..',
12179:                            begins   => 'begins with ..',
12180:                          );
12181:     my @srchtypeorder = ('exact','begins','contains');
12182:     return (\%srchtypes_desc,\@srchtypeorder);
12183: }
12184: 
12185: sub usertype_update_row {
12186:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
12187:     my $datatable;
12188:     my $numinrow = 4;
12189:     foreach my $type (@{$types}) {
12190:         if (defined($usertypes->{$type})) {
12191:             $$rownums ++;
12192:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
12193:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
12194:                           '</td><td class="LC_left_item"><table>';
12195:             for (my $i=0; $i<@{$fields}; $i++) {
12196:                 my $rem = $i%($numinrow);
12197:                 if ($rem == 0) {
12198:                     if ($i > 0) {
12199:                         $datatable .= '</tr>';
12200:                     }
12201:                     $datatable .= '<tr>';
12202:                 }
12203:                 my $check = ' ';
12204:                 if (ref($settings) eq 'HASH') {
12205:                     if (ref($settings->{'fields'}) eq 'HASH') {
12206:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
12207:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
12208:                                 $check = ' checked="checked" ';
12209:                             }
12210:                         }
12211:                     }
12212:                 }
12213: 
12214:                 if ($i == @{$fields}-1) {
12215:                     my $colsleft = $numinrow - $rem;
12216:                     if ($colsleft > 1) {
12217:                         $datatable .= '<td colspan="'.$colsleft.'">';
12218:                     } else {
12219:                         $datatable .= '<td>';
12220:                     }
12221:                 } else {
12222:                     $datatable .= '<td>';
12223:                 }
12224:                 $datatable .= '<span class="LC_nobreak"><label>'.
12225:                               '<input type="checkbox" name="updateable_'.$type.
12226:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
12227:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
12228:             }
12229:             $datatable .= '</tr></table></td></tr>';
12230:         }
12231:     }
12232:     return $datatable;
12233: }
12234: 
12235: sub modify_login {
12236:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12237:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
12238:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
12239:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
12240:     %title = ( coursecatalog => 'Display course catalog',
12241:                adminmail => 'Display administrator E-mail address',
12242:                helpdesk  => 'Display "Contact Helpdesk" link',
12243:                newuser => 'Link for visitors to create a user account',
12244:                loginheader => 'Log-in box header',
12245:                saml => 'Dual SSO and non-SSO login');
12246:     @offon = ('off','on');
12247:     if (ref($domconfig{login}) eq 'HASH') {
12248:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
12249:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
12250:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
12251:             }
12252:         }
12253:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
12254:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
12255:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
12256:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
12257:                     $saml{$lonhost} = 1;
12258:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
12259:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
12260:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
12261:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
12262:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
12263:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
12264:                 }
12265:             }
12266:         }
12267:     }
12268:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
12269:                                            \%domconfig,\%loginhash);
12270:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12271:     foreach my $item (@toggles) {
12272:         $loginhash{login}{$item} = $env{'form.'.$item};
12273:     }
12274:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
12275:     if (ref($colchanges{'login'}) eq 'HASH') {  
12276:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
12277:                                          \%loginhash);
12278:     }
12279: 
12280:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12281:     my %domservers = &Apache::lonnet::get_servers($dom);
12282:     my @loginvia_attribs = ('serverpath','custompath','exempt');
12283:     if (keys(%servers) > 1) {
12284:         foreach my $lonhost (keys(%servers)) {
12285:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
12286:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
12287:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
12288:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
12289:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
12290:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12291:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12292:                         $changes{'loginvia'}{$lonhost} = 1;
12293:                     } else {
12294:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
12295:                         $changes{'loginvia'}{$lonhost} = 1;
12296:                     }
12297:                 } else {
12298:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12299:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12300:                         $changes{'loginvia'}{$lonhost} = 1;
12301:                     }
12302:                 }
12303:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
12304:                     foreach my $item (@loginvia_attribs) {
12305:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
12306:                     }
12307:                 } else {
12308:                     foreach my $item (@loginvia_attribs) {
12309:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12310:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12311:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
12312:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12313:                                 $new = '/';
12314:                             }
12315:                         }
12316:                         if (($item eq 'custompath') && 
12317:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12318:                             $new = '';
12319:                         }
12320:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
12321:                             $changes{'loginvia'}{$lonhost} = 1;
12322:                         }
12323:                         if ($item eq 'exempt') {
12324:                             $new = &check_exempt_addresses($new);
12325:                         }
12326:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12327:                     }
12328:                 }
12329:             } else {
12330:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12331:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12332:                     $changes{'loginvia'}{$lonhost} = 1;
12333:                     foreach my $item (@loginvia_attribs) {
12334:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12335:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12336:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12337:                                 $new = '/';
12338:                             }
12339:                         }
12340:                         if (($item eq 'custompath') && 
12341:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12342:                             $new = '';
12343:                         }
12344:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12345:                     }
12346:                 }
12347:             }
12348:         }
12349:     }
12350: 
12351:     my $servadm = $r->dir_config('lonAdmEMail');
12352:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
12353:     if (ref($domconfig{'login'}) eq 'HASH') {
12354:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
12355:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
12356:                 if ($lang eq 'nolang') {
12357:                     push(@currlangs,$lang);
12358:                 } elsif (defined($langchoices{$lang})) {
12359:                     push(@currlangs,$lang);
12360:                 } else {
12361:                     next;
12362:                 }
12363:             }
12364:         }
12365:     }
12366:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
12367:     if (@currlangs > 0) {
12368:         foreach my $lang (@currlangs) {
12369:             if (grep(/^\Q$lang\E$/,@delurls)) {
12370:                 $changes{'helpurl'}{$lang} = 1;
12371:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
12372:                 $changes{'helpurl'}{$lang} = 1;
12373:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
12374:                 push(@newlangs,$lang);
12375:             } else {
12376:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12377:             }
12378:         }
12379:     }
12380:     unless (grep(/^nolang$/,@currlangs)) {
12381:         if ($env{'form.loginhelpurl_nolang.filename'}) {
12382:             $changes{'helpurl'}{'nolang'} = 1;
12383:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
12384:             push(@newlangs,'nolang');
12385:         }
12386:     }
12387:     if ($env{'form.loginhelpurl_add_lang'}) {
12388:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
12389:             ($env{'form.loginhelpurl_add_file.filename'})) {
12390:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
12391:             $addedfile = $env{'form.loginhelpurl_add_lang'};
12392:         }
12393:     }
12394:     if ((@newlangs > 0) || ($addedfile)) {
12395:         my $error;
12396:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12397:         if ($configuserok eq 'ok') {
12398:             if ($switchserver) {
12399:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
12400:             } elsif ($author_ok eq 'ok') {
12401:                 my @allnew = @newlangs;
12402:                 if ($addedfile ne '') {
12403:                     push(@allnew,$addedfile);
12404:                 }
12405:                 foreach my $lang (@allnew) {
12406:                     my $formelem = 'loginhelpurl_'.$lang;
12407:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
12408:                         $formelem = 'loginhelpurl_add_file';
12409:                     }
12410:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12411:                                                                "help/$lang",'','',$newfile{$lang});
12412:                     if ($result eq 'ok') {
12413:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
12414:                         $changes{'helpurl'}{$lang} = 1;
12415:                     } else {
12416:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
12417:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12418:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
12419:                             (!grep(/^\Q$lang\E$/,@delurls))) {
12420:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12421:                         }
12422:                     }
12423:                 }
12424:             } else {
12425:                 $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);
12426:             }
12427:         } else {
12428:             $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);
12429:         }
12430:         if ($error) {
12431:             &Apache::lonnet::logthis($error);
12432:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12433:         }
12434:     }
12435: 
12436:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
12437:     if (ref($domconfig{'login'}) eq 'HASH') {
12438:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
12439:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
12440:                 if ($domservers{$lonhost}) {
12441:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12442:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
12443:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
12444:                     }
12445:                 }
12446:             }
12447:         }
12448:     }
12449:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
12450:     foreach my $lonhost (sort(keys(%domservers))) {
12451:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12452:             $changes{'headtag'}{$lonhost} = 1;
12453:         } else {
12454:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
12455:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
12456:             }
12457:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
12458:                 push(@newhosts,$lonhost);
12459:             } elsif ($currheadtagurls{$lonhost}) {
12460:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
12461:                 if ($currexempt{$lonhost}) {
12462:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
12463:                         $changes{'headtag'}{$lonhost} = 1;
12464:                     }
12465:                 } elsif ($possexempt{$lonhost}) {
12466:                     $changes{'headtag'}{$lonhost} = 1;
12467:                 }
12468:                 if ($possexempt{$lonhost}) {
12469:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12470:                 }
12471:             }
12472:         }
12473:     }
12474:     if (@newhosts) {
12475:         my $error;
12476:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12477:         if ($configuserok eq 'ok') {
12478:             if ($switchserver) {
12479:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
12480:             } elsif ($author_ok eq 'ok') {
12481:                 foreach my $lonhost (@newhosts) {
12482:                     my $formelem = 'loginheadtag_'.$lonhost;
12483:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12484:                                                                           "login/headtag/$lonhost",'','',
12485:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
12486:                     if ($result eq 'ok') {
12487:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
12488:                         $changes{'headtag'}{$lonhost} = 1;
12489:                         if ($possexempt{$lonhost}) {
12490:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12491:                         }
12492:                     } else {
12493:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
12494:                                            $newheadtagurls{$lonhost},$result);
12495:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12496:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
12497:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
12498:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
12499:                         }
12500:                     }
12501:                 }
12502:             } else {
12503:                 $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);
12504:             }
12505:         } else {
12506:             $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);
12507:         }
12508:         if ($error) {
12509:             &Apache::lonnet::logthis($error);
12510:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12511:         }
12512:     }
12513:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
12514:     my @newsamlimgs;
12515:     foreach my $lonhost (keys(%domservers)) {
12516:         if ($env{'form.saml_'.$lonhost}) {
12517:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
12518:                 push(@newsamlimgs,$lonhost);
12519:             }
12520:             foreach my $item ('text','alt','url','title','notsso') {
12521:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
12522:             }
12523:             if ($saml{$lonhost}) {
12524:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
12525: #FIXME Need to obsolete published image
12526:                     delete($currsaml{$lonhost}{'img'});
12527:                     $changes{'saml'}{$lonhost} = 1;
12528:                 }
12529:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
12530:                     $changes{'saml'}{$lonhost} = 1;
12531:                 }
12532:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
12533:                     $changes{'saml'}{$lonhost} = 1;
12534:                 }
12535:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
12536:                     $changes{'saml'}{$lonhost} = 1;
12537:                 }
12538:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
12539:                     $changes{'saml'}{$lonhost} = 1;
12540:                 }
12541:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
12542:                     $changes{'saml'}{$lonhost} = 1;
12543:                 }
12544:             } else {
12545:                 $changes{'saml'}{$lonhost} = 1;
12546:             }
12547:             foreach my $item ('text','alt','url','title','notsso') {
12548:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
12549:             }
12550:         } else {
12551:             if ($saml{$lonhost}) {  
12552:                 $changes{'saml'}{$lonhost} = 1;
12553:                 delete($currsaml{$lonhost});
12554:             }
12555:         }
12556:     }
12557:     foreach my $posshost (keys(%currsaml)) {
12558:         unless (exists($domservers{$posshost})) { 
12559:             delete($currsaml{$posshost}); 
12560:         }
12561:     }
12562:     %{$loginhash{'login'}{'saml'}} = %currsaml;
12563:     if (@newsamlimgs) {
12564:         my $error;
12565:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12566:         if ($configuserok eq 'ok') {
12567:             if ($switchserver) {
12568:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
12569:             } elsif ($author_ok eq 'ok') {
12570:                 foreach my $lonhost (@newsamlimgs) {
12571:                     my $formelem = 'saml_img_'.$lonhost;
12572:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12573:                                                         "login/saml/$lonhost",'','',
12574:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
12575:                     if ($result eq 'ok') {
12576:                         $currsaml{$lonhost}{'img'} = $imgurl;
12577:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
12578:                         $changes{'saml'}{$lonhost} = 1;
12579:                     } else {
12580:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
12581:                                            $lonhost,$result);
12582:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12583:                     }
12584:                 }
12585:             } else {
12586:                 $error = &mt("Upload of SSO button image file(s) failed because an author role could not be assigned to a Domain Configuration user ([_1]) in domain: [_2].  Error was: [_3].",$confname,$dom,$author_ok);
12587:             }
12588:         } else {
12589:             $error = &mt("Upload of SSO button image file(s) failed because a Domain Configuration user ([_1]) could not be created in domain: [_2].  Error was: [_3].",$confname,$dom,$configuserok);
12590:         }
12591:         if ($error) {
12592:             &Apache::lonnet::logthis($error);
12593:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12594:         }
12595:     }
12596:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
12597: 
12598:     my $defaulthelpfile = '/adm/loginproblems.html';
12599:     my $defaulttext = &mt('Default in use');
12600: 
12601:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
12602:                                              $dom);
12603:     if ($putresult eq 'ok') {
12604:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12605:         my %defaultchecked = (
12606:                     'coursecatalog' => 'on',
12607:                     'helpdesk'      => 'on',
12608:                     'adminmail'     => 'off',
12609:                     'newuser'       => 'off',
12610:         );
12611:         if (ref($domconfig{'login'}) eq 'HASH') {
12612:             foreach my $item (@toggles) {
12613:                 if ($defaultchecked{$item} eq 'on') { 
12614:                     if (($domconfig{'login'}{$item} eq '0') &&
12615:                         ($env{'form.'.$item} eq '1')) {
12616:                         $changes{$item} = 1;
12617:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12618:                               $domconfig{'login'}{$item} eq '1') &&
12619:                              ($env{'form.'.$item} eq '0')) {
12620:                         $changes{$item} = 1;
12621:                     }
12622:                 } elsif ($defaultchecked{$item} eq 'off') {
12623:                     if (($domconfig{'login'}{$item} eq '1') &&
12624:                         ($env{'form.'.$item} eq '0')) {
12625:                         $changes{$item} = 1;
12626:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12627:                               $domconfig{'login'}{$item} eq '0') &&
12628:                              ($env{'form.'.$item} eq '1')) {
12629:                         $changes{$item} = 1;
12630:                     }
12631:                 }
12632:             }
12633:         }
12634:         if (keys(%changes) > 0 || $colchgtext) {
12635:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12636:             if (exists($changes{'saml'})) {
12637:                 my $hostid_in_use;
12638:                 my @hosts = &Apache::lonnet::current_machine_ids();
12639:                 if (@hosts > 1) {
12640:                     foreach my $hostid (@hosts) {
12641:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
12642:                             $hostid_in_use = $hostid;
12643:                             last;
12644:                         }
12645:                     }
12646:                 } else {
12647:                     $hostid_in_use = $r->dir_config('lonHostID');
12648:                 }
12649:                 if (($hostid_in_use) &&
12650:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
12651:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
12652:                 }
12653:                 if (ref($lastactref) eq 'HASH') {
12654:                     if (ref($changes{'saml'}) eq 'HASH') {
12655:                         my %updates;
12656:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
12657:                         $lastactref->{'samllanding'} = \%updates;
12658:                     }
12659:                 }
12660:             }
12661:             if (ref($lastactref) eq 'HASH') {
12662:                 $lastactref->{'domainconfig'} = 1;
12663:             }
12664:             $resulttext = &mt('Changes made:').'<ul>';
12665:             foreach my $item (sort(keys(%changes))) {
12666:                 if ($item eq 'loginvia') {
12667:                     if (ref($changes{$item}) eq 'HASH') {
12668:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
12669:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12670:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
12671:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
12672:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
12673:                                     $protocol = 'http' if ($protocol ne 'https');
12674:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
12675: 
12676:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
12677:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
12678:                                     } else {
12679:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
12680:                                     }
12681:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
12682:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
12683:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
12684:                                     }
12685:                                     $resulttext .= '</li>';
12686:                                 } else {
12687:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
12688:                                 }
12689:                             } else {
12690:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
12691:                             }
12692:                         }
12693:                         $resulttext .= '</ul></li>';
12694:                     }
12695:                 } elsif ($item eq 'helpurl') {
12696:                     if (ref($changes{$item}) eq 'HASH') {
12697:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
12698:                             if (grep(/^\Q$lang\E$/,@delurls)) {
12699:                                 my ($chg,$link);
12700:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
12701:                                 if ($lang eq 'nolang') {
12702:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
12703:                                 } else {
12704:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
12705:                                 }
12706:                                 $resulttext .= '<li>'.$chg.'</li>';
12707:                             } else {
12708:                                 my $chg;
12709:                                 if ($lang eq 'nolang') {
12710:                                     $chg = &mt('custom log-in help file for no preferred language');
12711:                                 } else {
12712:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
12713:                                 }
12714:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
12715:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
12716:                                                       '?inhibitmenu=yes',$chg,600,500).
12717:                                                '</li>';
12718:                             }
12719:                         }
12720:                     }
12721:                 } elsif ($item eq 'headtag') {
12722:                     if (ref($changes{$item}) eq 'HASH') {
12723:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12724:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12725:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
12726:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12727:                                 $resulttext .= '<li><a href="'.
12728:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
12729:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
12730:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
12731:                                 if ($possexempt{$lonhost}) {
12732:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
12733:                                 } else {
12734:                                     $resulttext .= &mt('included for any client IP');
12735:                                 }
12736:                                 $resulttext .= '</li>';
12737:                             }
12738:                         }
12739:                     }
12740:                 } elsif ($item eq 'saml') {
12741:                     if (ref($changes{$item}) eq 'HASH') {
12742:                         my %notlt = (
12743:                                        text   => 'Text for log-in by SSO',
12744:                                        img    => 'SSO button image',
12745:                                        alt    => 'Alt text for button image',
12746:                                        url    => 'SSO URL',
12747:                                        title  => 'Tooltip for SSO link',
12748:                                        notsso => 'Text for non-SSO log-in',
12749:                                     );
12750:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12751:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
12752:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
12753:                                                '<ul>';
12754:                                 foreach my $key ('text','img','alt','url','title','notsso') {
12755:                                     if ($currsaml{$lonhost}{$key} eq '') {
12756:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
12757:                                     } else {
12758:                                         my $value = "'$currsaml{$lonhost}{$key}'";
12759:                                         if ($key eq 'img') {
12760:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
12761:                                         }
12762:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
12763:                                                                   $value).'</li>';
12764:                                     }
12765:                                 }
12766:                                 $resulttext .= '</ul></li>';
12767:                             } else {
12768:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
12769:                             }
12770:                         }
12771:                     }
12772:                 } elsif ($item eq 'captcha') {
12773:                     if (ref($loginhash{'login'}) eq 'HASH') {
12774:                         my $chgtxt;
12775:                         if ($loginhash{'login'}{$item} eq 'notused') {
12776:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
12777:                         } else {
12778:                             my %captchas = &captcha_phrases();
12779:                             if ($captchas{$loginhash{'login'}{$item}}) {
12780:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
12781:                             } else {
12782:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
12783:                             }
12784:                         }
12785:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12786:                     }
12787:                 } elsif ($item eq 'recaptchakeys') {
12788:                     if (ref($loginhash{'login'}) eq 'HASH') {
12789:                         my ($privkey,$pubkey);
12790:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
12791:                             $pubkey = $loginhash{'login'}{$item}{'public'};
12792:                             $privkey = $loginhash{'login'}{$item}{'private'};
12793:                         }
12794:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
12795:                         if (!$pubkey) {
12796:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
12797:                         } else {
12798:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
12799:                         }
12800:                         if (!$privkey) {
12801:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
12802:                         } else {
12803:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
12804:                         }
12805:                         $chgtxt .= '</ul>';
12806:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12807:                     }
12808:                 } elsif ($item eq 'recaptchaversion') {
12809:                     if (ref($loginhash{'login'}) eq 'HASH') {
12810:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
12811:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
12812:                                            '</li>';
12813:                         }
12814:                     }
12815:                 } else {
12816:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
12817:                 }
12818:             }
12819:             $resulttext .= $colchgtext.'</ul>';
12820:         } else {
12821:             $resulttext = &mt('No changes made to log-in page settings');
12822:         }
12823:     } else {
12824:         $resulttext = '<span class="LC_error">'.
12825: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12826:     }
12827:     if ($errors) {
12828:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12829:                        $errors.'</ul>';
12830:     }
12831:     return $resulttext;
12832: }
12833: 
12834: sub check_exempt_addresses {
12835:     my ($iplist) = @_;
12836:     $iplist =~ s/^\s+//;
12837:     $iplist =~ s/\s+$//;
12838:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12839:     my (@okips,$new);
12840:     foreach my $ip (@poss_ips) {
12841:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12842:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12843:                 push(@okips,$ip);
12844:             }
12845:         }
12846:     }
12847:     if (@okips > 0) {
12848:         $new = join(',',@okips);
12849:     } else {
12850:         $new = '';
12851:     }
12852:     return $new;
12853: }
12854: 
12855: sub color_font_choices {
12856:     my %choices =
12857:         &Apache::lonlocal::texthash (
12858:             img => "Header",
12859:             bgs => "Background colors",
12860:             links => "Link colors",
12861:             images => "Images",
12862:             font => "Font color",
12863:             fontmenu => "Font menu",
12864:             pgbg => "Page",
12865:             tabbg => "Header",
12866:             sidebg => "Border",
12867:             link => "Link",
12868:             alink => "Active link",
12869:             vlink => "Visited link",
12870:         );
12871:     return %choices;
12872: }
12873: 
12874: sub modify_ipaccess {
12875:     my ($dom,$lastactref,%domconfig) = @_;
12876:     my (@allpos,%changes,%confhash,$errors,$resulttext);
12877:     my (@items,%deletions,%itemids,@warnings);
12878:     my ($typeorder,$types) = &commblocktype_text();
12879:     if ($env{'form.ipaccess_add'}) {
12880:         my $name = $env{'form.ipaccess_name_add'};
12881:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
12882:         if ($newid) {
12883:             $itemids{'add'} = $newid;
12884:             push(@items,'add');
12885:             $changes{$newid} = 1;
12886:         } else {
12887:             $error = &mt('Failed to acquire unique ID for new IP access control item');
12888:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12889:         }
12890:     }
12891:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
12892:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
12893:         if (@todelete) {
12894:             map { $deletions{$_} = 1; } @todelete;
12895:         }
12896:         my $maxnum = $env{'form.ipaccess_maxnum'};
12897:         for (my $i=0; $i<$maxnum; $i++) {
12898:             my $itemid = $env{'form.ipaccess_id_'.$i};
12899:             $itemid =~ s/\D+//g;
12900:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12901:                 if ($deletions{$itemid}) {
12902:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
12903:                 } else {
12904:                     push(@items,$i);
12905:                     $itemids{$i} = $itemid;
12906:                 }
12907:             }
12908:         }
12909:     }
12910:     foreach my $idx (@items) {
12911:         my $itemid = $itemids{$idx};
12912:         next unless ($itemid);
12913:         my %current;
12914:         unless ($idx eq 'add') {
12915:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12916:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
12917:             }
12918:         }
12919:         my $position = $env{'form.ipaccess_pos_'.$itemid};
12920:         $position =~ s/\D+//g;
12921:         if ($position ne '') {
12922:             $allpos[$position] = $itemid;
12923:         }
12924:         my $name = $env{'form.ipaccess_name_'.$idx};
12925:         $name =~ s/^\s+|\s+$//g;
12926:         $confhash{$itemid}{'name'} = $name;
12927:         my $possrange = $env{'form.ipaccess_range_'.$idx};
12928:         $possrange =~ s/^\s+|\s+$//g;
12929:         unless ($possrange eq '') {
12930:             $possrange =~ s/[\r\n]+/\s/g;
12931:             $possrange =~ s/\s*-\s*/-/g;
12932:             $possrange =~ s/\s+/,/g;
12933:             $possrange =~ s/,+/,/g;
12934:             if ($possrange ne '') {
12935:                 my (@ok,$count);
12936:                 $count = 0; 
12937:                 foreach my $poss (split(/\,/,$possrange)) {
12938:                     $count ++;
12939:                     $poss = &validate_ip_pattern($poss);
12940:                     if ($poss ne '') {
12941:                         push(@ok,$poss);
12942:                     }
12943:                 }
12944:                 my $diff = $count - scalar(@ok);
12945:                 if ($diff) {
12946:                     $errors .= '<li><span class="LC_error">'.
12947:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
12948:                                    $diff,$name).
12949:                                '</span></li>';
12950:                 }
12951:                 if (@ok) {
12952:                     my @cidr_list;
12953:                     foreach my $item (@ok) {
12954:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
12955:                     }
12956:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
12957:                 }
12958:             }
12959:         }
12960:         foreach my $field ('name','ip') {
12961:             unless (($idx eq 'add') || ($changes{$itemid})) {
12962:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
12963:                     $changes{$itemid} = 1;
12964:                     last;
12965:                 }
12966:             }
12967:         }
12968:         $confhash{$itemid}{'commblocks'} = {};
12969:          
12970:         my %commblocks;
12971:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);  
12972:         foreach my $type (@{$typeorder}) {
12973:             if ($commblocks{$type}) {
12974:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
12975:             }
12976:             unless (($idx eq 'add') || ($changes{$itemid})) {
12977:                 if (ref($current{'commblocks'}) eq 'HASH') {
12978:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
12979:                         $changes{$itemid} = 1;
12980:                     }
12981:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
12982:                     $changes{$itemid} = 1;
12983:                 }
12984:             }
12985:         }
12986:         $confhash{$itemid}{'courses'} = {};
12987:         my %crsdeletions;
12988:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
12989:         if (@delcrs) {
12990:             map { $crsdeletions{$_} = 1; } @delcrs;
12991:         }
12992:         if (ref($current{'courses'}) eq 'HASH') {
12993:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
12994:                 if ($crsdeletions{$cid}) {
12995:                     $changes{$itemid} = 1;
12996:                 } else {
12997:                     $confhash{$itemid}{'courses'}{$cid} = 1;
12998:                 }
12999:             }
13000:         }
13001:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
13002:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
13003:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) && 
13004:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
13005:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
13006:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
13007:                 $errors .= '<li><span class="LC_error">'.
13008:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
13009:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
13010:                            '</span></li>';
13011:             } else {
13012:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
13013:                 $changes{$itemid} = 1;
13014:             }
13015:         }
13016:     }
13017:     if (@allpos > 0) {
13018:         my $idx = 0;
13019:         foreach my $itemid (@allpos) {
13020:             if ($itemid ne '') {
13021:                 $confhash{$itemid}{'order'} = $idx;
13022:                 unless ($changes{$itemid}) {
13023:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
13024:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
13025:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
13026:                                 $changes{$itemid} = 1;
13027:                             }
13028:                         }
13029:                     }
13030:                 }
13031:                 $idx ++;
13032:             }
13033:         }
13034:     }
13035:     if (keys(%changes)) {
13036:         my %defaultshash = (
13037:                               ipaccess => \%confhash,
13038:                            );
13039:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
13040:                                                  $dom);
13041:         if ($putresult eq 'ok') {
13042:             my $cachetime = 1800;
13043:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
13044:             if (ref($lastactref) eq 'HASH') {
13045:                 $lastactref->{'ipaccess'} = 1;
13046:             }
13047:             $resulttext = &mt('Changes made:').'<ul>';
13048:             my %bynum;
13049:             foreach my $itemid (sort(keys(%changes))) {
13050:                 if (ref($confhash{$itemid}) eq 'HASH') {
13051:                     my $position = $confhash{$itemid}{'order'};
13052:                     if ($position =~ /^\d+$/) {
13053:                         $bynum{$position} = $itemid;
13054:                     }
13055:                 }
13056:             }
13057:             if (keys(%deletions)) {
13058:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
13059:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13060:                 }
13061:             }
13062:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13063:                 my $itemid = $bynum{$pos};
13064:                 if (ref($confhash{$itemid}) eq 'HASH') {
13065:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
13066:                     my $position = $pos + 1;
13067:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13068:                     if ($confhash{$itemid}{'ip'} eq '') {
13069:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
13070:                     } else {
13071:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
13072:                     }
13073:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
13074:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
13075:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
13076:                                        '</li>';
13077:                     } else {
13078:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
13079:                     }
13080:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
13081:                         my @courses;
13082:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
13083:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1}); 
13084:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
13085:                         }
13086:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
13087:                                              join('</li><li>',@courses).'</li></ul>';
13088:                     } else {
13089:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
13090:                     }
13091:                     $resulttext .= '</ul></li>';
13092:                 }
13093:             }
13094:             $resulttext .= '</ul>';
13095:         } else {
13096:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13097:         }
13098:     } else {
13099:         $resulttext = &mt('No changes made');
13100:     }
13101:     if ($errors) {
13102:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13103:                        $errors.'</ul></p>';
13104:     }
13105:     return $resulttext;
13106: }
13107: 
13108: sub get_ipaccess_id {
13109:     my ($domain,$location) = @_;
13110:     # get lock on ipaccess db
13111:     my $lockhash = {
13112:                       lock => $env{'user.name'}.
13113:                               ':'.$env{'user.domain'},
13114:                    };
13115:     my $tries = 0;
13116:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13117:     my ($id,$error);
13118: 
13119:     while (($gotlock ne 'ok') && ($tries<10)) {
13120:         $tries ++;
13121:         sleep (0.1);
13122:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13123:     }
13124:     if ($gotlock eq 'ok') {
13125:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
13126:         if ($currids{'lock'}) {
13127:             delete($currids{'lock'});
13128:             if (keys(%currids)) {
13129:                 my @curr = sort { $a <=> $b } keys(%currids);
13130:                 if ($curr[-1] =~ /^\d+$/) {
13131:                     $id = 1 + $curr[-1];
13132:                 }
13133:             } else {
13134:                 $id = 1;
13135:             }
13136:             if ($id) {
13137:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
13138:                     $error = 'nostore';
13139:                 }
13140:             } else {
13141:                 $error = 'nonumber';
13142:             }
13143:         }
13144:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
13145:     } else {
13146:         $error = 'nolock';
13147:     }
13148:     return ($id,$error);
13149: }
13150: 
13151: sub modify_rolecolors {
13152:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
13153:     my ($resulttext,%rolehash);
13154:     $rolehash{'rolecolors'} = {};
13155:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
13156:         if ($domconfig{'rolecolors'} eq '') {
13157:             $domconfig{'rolecolors'} = {};
13158:         }
13159:     }
13160:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
13161:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
13162:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
13163:                                              $dom);
13164:     if ($putresult eq 'ok') {
13165:         if (keys(%changes) > 0) {
13166:             &Apache::loncommon::devalidate_domconfig_cache($dom);
13167:             if (ref($lastactref) eq 'HASH') {
13168:                 $lastactref->{'domainconfig'} = 1;
13169:             }
13170:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
13171:                                              $rolehash{'rolecolors'});
13172:         } else {
13173:             $resulttext = &mt('No changes made to default color schemes');
13174:         }
13175:     } else {
13176:         $resulttext = '<span class="LC_error">'.
13177: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13178:     }
13179:     if ($errors) {
13180:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13181:                        $errors.'</ul>';
13182:     }
13183:     return $resulttext;
13184: }
13185: 
13186: sub modify_colors {
13187:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
13188:     my (%changes,%choices);
13189:     my @bgs;
13190:     my @links = ('link','alink','vlink');
13191:     my @logintext;
13192:     my @images;
13193:     my $servadm = $r->dir_config('lonAdmEMail');
13194:     my $errors;
13195:     my %defaults;
13196:     foreach my $role (@{$roles}) {
13197:         if ($role eq 'login') {
13198:             %choices = &login_choices();
13199:             @logintext = ('textcol','bgcol');
13200:         } else {
13201:             %choices = &color_font_choices();
13202:         }
13203:         if ($role eq 'login') {
13204:             @images = ('img','logo','domlogo','login');
13205:             @bgs = ('pgbg','mainbg','sidebg');
13206:         } else {
13207:             @images = ('img');
13208:             @bgs = ('pgbg','tabbg','sidebg');
13209:         }
13210:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
13211:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
13212:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
13213:         }
13214:         if ($role eq 'login') {
13215:             foreach my $item (@logintext) {
13216:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13217:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13218:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13219:                 }
13220:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
13221:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13222:                 }
13223:             }
13224:         } else {
13225:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
13226:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
13227:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
13228:             }
13229:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
13230:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
13231:             }
13232:         }
13233:         foreach my $item (@bgs) {
13234:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13235:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13236:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13237:             }
13238:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
13239:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13240:             }
13241:         }
13242:         foreach my $item (@links) {
13243:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13244:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13245:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13246:             }
13247:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
13248:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13249:             }
13250:         }
13251:         my ($configuserok,$author_ok,$switchserver) = 
13252:             &config_check($dom,$confname,$servadm);
13253:         my ($width,$height) = &thumb_dimensions();
13254:         if (ref($domconfig->{$role}) ne 'HASH') {
13255:             $domconfig->{$role} = {};
13256:         }
13257:         foreach my $img (@images) {
13258:             if ($role eq 'login') {
13259:                 if (($img eq 'img') || ($img eq 'logo')) {  
13260:                     if (defined($env{'form.login_showlogo_'.$img})) {
13261:                         $confhash->{$role}{'showlogo'}{$img} = 1;
13262:                     } else { 
13263:                         $confhash->{$role}{'showlogo'}{$img} = 0;
13264:                     }
13265:                 }
13266:                 if ($env{'form.login_alt_'.$img} ne '') {
13267:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
13268:                 }
13269:             }
13270: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
13271: 		 && !defined($domconfig->{$role}{$img})
13272: 		 && !$env{'form.'.$role.'_del_'.$img}
13273: 		 && $env{'form.'.$role.'_import_'.$img}) {
13274: 		# import the old configured image from the .tab setting
13275: 		# if they haven't provided a new one 
13276: 		$domconfig->{$role}{$img} = 
13277: 		    $env{'form.'.$role.'_import_'.$img};
13278: 	    }
13279:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
13280:                 my $error;
13281:                 if ($configuserok eq 'ok') {
13282:                     if ($switchserver) {
13283:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
13284:                     } else {
13285:                         if ($author_ok eq 'ok') {
13286:                             my ($result,$logourl) = 
13287:                                 &publishlogo($r,'upload',$role.'_'.$img,
13288:                                            $dom,$confname,$img,$width,$height);
13289:                             if ($result eq 'ok') {
13290:                                 $confhash->{$role}{$img} = $logourl;
13291:                                 $changes{$role}{'images'}{$img} = 1;
13292:                             } else {
13293:                                 $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);
13294:                             }
13295:                         } else {
13296:                             $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);
13297:                         }
13298:                     }
13299:                 } else {
13300:                     $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);
13301:                 }
13302:                 if ($error) {
13303:                     &Apache::lonnet::logthis($error);
13304:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13305:                 }
13306:             } elsif ($domconfig->{$role}{$img} ne '') {
13307:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
13308:                     my $error;
13309:                     if ($configuserok eq 'ok') {
13310: # is confname an author?
13311:                         if ($switchserver eq '') {
13312:                             if ($author_ok eq 'ok') {
13313:                                 my ($result,$logourl) = 
13314:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
13315:                                             $dom,$confname,$img,$width,$height);
13316:                                 if ($result eq 'ok') {
13317:                                     $confhash->{$role}{$img} = $logourl;
13318: 				    $changes{$role}{'images'}{$img} = 1;
13319:                                 }
13320:                             }
13321:                         }
13322:                     }
13323:                 }
13324:             }
13325:         }
13326:         if (ref($domconfig) eq 'HASH') {
13327:             if (ref($domconfig->{$role}) eq 'HASH') {
13328:                 foreach my $img (@images) {
13329:                     if ($domconfig->{$role}{$img} ne '') {
13330:                         if ($env{'form.'.$role.'_del_'.$img}) {
13331:                             $confhash->{$role}{$img} = '';
13332:                             $changes{$role}{'images'}{$img} = 1;
13333:                         } else {
13334:                             if ($confhash->{$role}{$img} eq '') {
13335:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
13336:                             }
13337:                         }
13338:                     } else {
13339:                         if ($env{'form.'.$role.'_del_'.$img}) {
13340:                             $confhash->{$role}{$img} = '';
13341:                             $changes{$role}{'images'}{$img} = 1;
13342:                         } 
13343:                     }
13344:                     if ($role eq 'login') {
13345:                         if (($img eq 'logo') || ($img eq 'img')) {
13346:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
13347:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
13348:                                     $domconfig->{$role}{'showlogo'}{$img}) {
13349:                                     $changes{$role}{'showlogo'}{$img} = 1; 
13350:                                 }
13351:                             } else {
13352:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13353:                                     $changes{$role}{'showlogo'}{$img} = 1;
13354:                                 }
13355:                             }
13356:                         }
13357:                         if ($img ne 'login') {
13358:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
13359:                                 if ($confhash->{$role}{'alttext'}{$img} ne
13360:                                     $domconfig->{$role}{'alttext'}{$img}) {
13361:                                     $changes{$role}{'alttext'}{$img} = 1;
13362:                                 }
13363:                             } else {
13364:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13365:                                     $changes{$role}{'alttext'}{$img} = 1;
13366:                                 }
13367:                             }
13368:                         }
13369:                     }
13370:                 }
13371:                 if ($domconfig->{$role}{'font'} ne '') {
13372:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
13373:                         $changes{$role}{'font'} = 1;
13374:                     }
13375:                 } else {
13376:                     if ($confhash->{$role}{'font'}) {
13377:                         $changes{$role}{'font'} = 1;
13378:                     }
13379:                 }
13380:                 if ($role ne 'login') {
13381:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
13382:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
13383:                             $changes{$role}{'fontmenu'} = 1;
13384:                         }
13385:                     } else {
13386:                         if ($confhash->{$role}{'fontmenu'}) {
13387:                             $changes{$role}{'fontmenu'} = 1;
13388:                         }
13389:                     }
13390:                 }
13391:                 foreach my $item (@bgs) {
13392:                     if ($domconfig->{$role}{$item} ne '') {
13393:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13394:                             $changes{$role}{'bgs'}{$item} = 1;
13395:                         } 
13396:                     } else {
13397:                         if ($confhash->{$role}{$item}) {
13398:                             $changes{$role}{'bgs'}{$item} = 1;
13399:                         }
13400:                     }
13401:                 }
13402:                 foreach my $item (@links) {
13403:                     if ($domconfig->{$role}{$item} ne '') {
13404:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13405:                             $changes{$role}{'links'}{$item} = 1;
13406:                         }
13407:                     } else {
13408:                         if ($confhash->{$role}{$item}) {
13409:                             $changes{$role}{'links'}{$item} = 1;
13410:                         }
13411:                     }
13412:                 }
13413:                 foreach my $item (@logintext) {
13414:                     if ($domconfig->{$role}{$item} ne '') {
13415:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13416:                             $changes{$role}{'logintext'}{$item} = 1;
13417:                         }
13418:                     } else {
13419:                         if ($confhash->{$role}{$item}) {
13420:                             $changes{$role}{'logintext'}{$item} = 1;
13421:                         }
13422:                     }
13423:                 }
13424:             } else {
13425:                 &default_change_checker($role,\@images,\@links,\@bgs,
13426:                                         \@logintext,$confhash,\%changes); 
13427:             }
13428:         } else {
13429:             &default_change_checker($role,\@images,\@links,\@bgs,
13430:                                     \@logintext,$confhash,\%changes); 
13431:         }
13432:     }
13433:     return ($errors,%changes);
13434: }
13435: 
13436: sub config_check {
13437:     my ($dom,$confname,$servadm) = @_;
13438:     my ($configuserok,$author_ok,$switchserver,%currroles);
13439:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
13440:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
13441:                                                    $confname,$servadm);
13442:     if ($configuserok eq 'ok') {
13443:         $switchserver = &check_switchserver($dom,$confname);
13444:         if ($switchserver eq '') {
13445:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
13446:         }
13447:     }
13448:     return ($configuserok,$author_ok,$switchserver);
13449: }
13450: 
13451: sub default_change_checker {
13452:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
13453:     foreach my $item (@{$links}) {
13454:         if ($confhash->{$role}{$item}) {
13455:             $changes->{$role}{'links'}{$item} = 1;
13456:         }
13457:     }
13458:     foreach my $item (@{$bgs}) {
13459:         if ($confhash->{$role}{$item}) {
13460:             $changes->{$role}{'bgs'}{$item} = 1;
13461:         }
13462:     }
13463:     foreach my $item (@{$logintext}) {
13464:         if ($confhash->{$role}{$item}) {
13465:             $changes->{$role}{'logintext'}{$item} = 1;
13466:         }
13467:     }
13468:     foreach my $img (@{$images}) {
13469:         if ($env{'form.'.$role.'_del_'.$img}) {
13470:             $confhash->{$role}{$img} = '';
13471:             $changes->{$role}{'images'}{$img} = 1;
13472:         }
13473:         if ($role eq 'login') {
13474:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13475:                 $changes->{$role}{'showlogo'}{$img} = 1;
13476:             }
13477:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
13478:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13479:                     $changes->{$role}{'alttext'}{$img} = 1;
13480:                 }
13481:             }
13482:         }
13483:     }
13484:     if ($confhash->{$role}{'font'}) {
13485:         $changes->{$role}{'font'} = 1;
13486:     }
13487: }
13488: 
13489: sub display_colorchgs {
13490:     my ($dom,$changes,$roles,$confhash) = @_;
13491:     my (%choices,$resulttext);
13492:     if (!grep(/^login$/,@{$roles})) {
13493:         $resulttext = &mt('Changes made:').'<br />';
13494:     }
13495:     foreach my $role (@{$roles}) {
13496:         if ($role eq 'login') {
13497:             %choices = &login_choices();
13498:         } else {
13499:             %choices = &color_font_choices();
13500:         }
13501:         if (ref($changes->{$role}) eq 'HASH') {
13502:             if ($role ne 'login') {
13503:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
13504:             }
13505:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
13506:                 if ($role ne 'login') {
13507:                     $resulttext .= '<ul>';
13508:                 }
13509:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
13510:                     if ($role ne 'login') {
13511:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
13512:                     }
13513:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
13514:                         if (($role eq 'login') && ($key eq 'showlogo')) {
13515:                             if ($confhash->{$role}{$key}{$item}) {
13516:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
13517:                             } else {
13518:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
13519:                             }
13520:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
13521:                             if ($confhash->{$role}{$key}{$item} ne '') {
13522:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
13523:                                                $confhash->{$role}{$key}{$item}).'</li>';
13524:                             } else {
13525:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
13526:                             }
13527:                         } elsif ($confhash->{$role}{$item} eq '') {
13528:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
13529:                         } else {
13530:                             my $newitem = $confhash->{$role}{$item};
13531:                             if ($key eq 'images') {
13532:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
13533:                             }
13534:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
13535:                         }
13536:                     }
13537:                     if ($role ne 'login') {
13538:                         $resulttext .= '</ul></li>';
13539:                     }
13540:                 } else {
13541:                     if ($confhash->{$role}{$key} eq '') {
13542:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
13543:                     } else {
13544:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
13545:                     }
13546:                 }
13547:                 if ($role ne 'login') {
13548:                     $resulttext .= '</ul>';
13549:                 }
13550:             }
13551:         }
13552:     }
13553:     return $resulttext;
13554: }
13555: 
13556: sub thumb_dimensions {
13557:     return ('200','50');
13558: }
13559: 
13560: sub check_dimensions {
13561:     my ($inputfile) = @_;
13562:     my ($fullwidth,$fullheight);
13563:     if ($inputfile =~ m|^[/\w.\-]+$|) {
13564:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
13565:             my $imageinfo = <PIPE>;
13566:             if (!close(PIPE)) {
13567:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
13568:             }
13569:             chomp($imageinfo);
13570:             my ($fullsize) = 
13571:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
13572:             if ($fullsize) {
13573:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
13574:             }
13575:         }
13576:     }
13577:     return ($fullwidth,$fullheight);
13578: }
13579: 
13580: sub check_configuser {
13581:     my ($uhome,$dom,$confname,$servadm) = @_;
13582:     my ($configuserok,%currroles);
13583:     if ($uhome eq 'no_host') {
13584:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
13585:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
13586:         $configuserok = 
13587:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
13588:                              $configpass,'','','','','',undef,$servadm);
13589:     } else {
13590:         $configuserok = 'ok';
13591:         %currroles = 
13592:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
13593:     }
13594:     return ($configuserok,%currroles);
13595: }
13596: 
13597: sub check_authorstatus {
13598:     my ($dom,$confname,%currroles) = @_;
13599:     my $author_ok;
13600:     if (!$currroles{':'.$dom.':au'}) {
13601:         my $start = time;
13602:         my $end = 0;
13603:         $author_ok = 
13604:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
13605:                                         'au',$end,$start,'','','domconfig');
13606:     } else {
13607:         $author_ok = 'ok';
13608:     }
13609:     return $author_ok;
13610: }
13611: 
13612: sub publishlogo {
13613:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
13614:     my ($output,$fname,$logourl,$madethumb);
13615:     if ($action eq 'upload') {
13616:         $fname=$env{'form.'.$formname.'.filename'};
13617:         chop($env{'form.'.$formname});
13618:     } else {
13619:         ($fname) = ($formname =~ /([^\/]+)$/);
13620:     }
13621:     if ($savefileas ne '') {
13622:         $fname = $savefileas;
13623:     }
13624:     $fname=&Apache::lonnet::clean_filename($fname);
13625: # See if there is anything left
13626:     unless ($fname) { return ('error: no uploaded file'); }
13627:     $fname="$subdir/$fname";
13628:     my $docroot=$r->dir_config('lonDocRoot');
13629:     my $filepath="$docroot/priv";
13630:     my $relpath = "$dom/$confname";
13631:     my ($fnamepath,$file,$fetchthumb);
13632:     $file=$fname;
13633:     if ($fname=~m|/|) {
13634:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
13635:     }
13636:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
13637:     my $count;
13638:     for ($count=5;$count<=$#parts;$count++) {
13639:         $filepath.="/$parts[$count]";
13640:         if ((-e $filepath)!=1) {
13641:             mkdir($filepath,02770);
13642:         }
13643:     }
13644:     # Check for bad extension and disallow upload
13645:     if ($file=~/\.(\w+)$/ &&
13646:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13647:         $output = 
13648:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
13649:     } elsif ($file=~/\.(\w+)$/ &&
13650:         !defined(&Apache::loncommon::fileembstyle($1))) {
13651:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
13652:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
13653:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
13654:     } elsif (-d "$filepath/$file") {
13655:         $output = &mt('Filename is a directory name - rename the file and re-upload');
13656:     } else {
13657:         my $source = $filepath.'/'.$file;
13658:         my $logfile;
13659:         if (!open($logfile,">>",$source.'.log')) {
13660:             return (&mt('No write permission to Authoring Space'));
13661:         }
13662:         print $logfile
13663: "\n================= Publish ".localtime()." ================\n".
13664: $env{'user.name'}.':'.$env{'user.domain'}."\n";
13665: # Save the file
13666:         if (!open(FH,">",$source)) {
13667:             &Apache::lonnet::logthis('Failed to create '.$source);
13668:             return (&mt('Failed to create file'));
13669:         }
13670:         if ($action eq 'upload') {
13671:             if (!print FH ($env{'form.'.$formname})) {
13672:                 &Apache::lonnet::logthis('Failed to write to '.$source);
13673:                 return (&mt('Failed to write file'));
13674:             }
13675:         } else {
13676:             my $original = &Apache::lonnet::filelocation('',$formname);
13677:             if(!copy($original,$source)) {
13678:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
13679:                 return (&mt('Failed to write file'));
13680:             }
13681:         }
13682:         close(FH);
13683:         chmod(0660, $source); # Permissions to rw-rw---.
13684: 
13685:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
13686:         my $copyfile=$targetdir.'/'.$file;
13687: 
13688:         my @parts=split(/\//,$targetdir);
13689:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
13690:         for (my $count=5;$count<=$#parts;$count++) {
13691:             $path.="/$parts[$count]";
13692:             if (!-e $path) {
13693:                 print $logfile "\nCreating directory ".$path;
13694:                 mkdir($path,02770);
13695:             }
13696:         }
13697:         my $versionresult;
13698:         if (-e $copyfile) {
13699:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
13700:         } else {
13701:             $versionresult = 'ok';
13702:         }
13703:         if ($versionresult eq 'ok') {
13704:             if (copy($source,$copyfile)) {
13705:                 print $logfile "\nCopied original source to ".$copyfile."\n";
13706:                 $output = 'ok';
13707:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
13708:                 push(@{$modified_urls},[$copyfile,$source]);
13709:                 my $metaoutput = 
13710:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
13711:                 unless ($registered_cleanup) {
13712:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13713:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13714:                     $registered_cleanup=1;
13715:                 }
13716:             } else {
13717:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
13718:                 $output = &mt('Failed to copy file to RES space').", $!";
13719:             }
13720:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
13721:                 my $inputfile = $filepath.'/'.$file;
13722:                 my $outfile = $filepath.'/'.'tn-'.$file;
13723:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
13724:                 if ($fullwidth ne '' && $fullheight ne '') { 
13725:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
13726:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
13727:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
13728:                         system({$args[0]} @args);
13729:                         chmod(0660, $filepath.'/tn-'.$file);
13730:                         if (-e $outfile) {
13731:                             my $copyfile=$targetdir.'/tn-'.$file;
13732:                             if (copy($outfile,$copyfile)) {
13733:                                 print $logfile "\nCopied source to ".$copyfile."\n";
13734:                                 my $thumb_metaoutput = 
13735:                                     &write_metadata($dom,$confname,$formname,
13736:                                                     $targetdir,'tn-'.$file,$logfile);
13737:                                 push(@{$modified_urls},[$copyfile,$outfile]);
13738:                                 unless ($registered_cleanup) {
13739:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13740:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13741:                                     $registered_cleanup=1;
13742:                                 }
13743:                                 $madethumb = 1;
13744:                             } else {
13745:                                 print $logfile "\nUnable to write ".$copyfile.
13746:                                                ':'.$!."\n";
13747:                             }
13748:                         }
13749:                     }
13750:                 }
13751:             }
13752:         } else {
13753:             $output = $versionresult;
13754:         }
13755:     }
13756:     return ($output,$logourl,$madethumb);
13757: }
13758: 
13759: sub logo_versioning {
13760:     my ($targetdir,$file,$logfile) = @_;
13761:     my $target = $targetdir.'/'.$file;
13762:     my ($maxversion,$fn,$extn,$output);
13763:     $maxversion = 0;
13764:     if ($file =~ /^(.+)\.(\w+)$/) {
13765:         $fn=$1;
13766:         $extn=$2;
13767:     }
13768:     opendir(DIR,$targetdir);
13769:     while (my $filename=readdir(DIR)) {
13770:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
13771:             $maxversion=($1>$maxversion)?$1:$maxversion;
13772:         }
13773:     }
13774:     $maxversion++;
13775:     print $logfile "\nCreating old version ".$maxversion."\n";
13776:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
13777:     if (copy($target,$copyfile)) {
13778:         print $logfile "Copied old target to ".$copyfile."\n";
13779:         $copyfile=$copyfile.'.meta';
13780:         if (copy($target.'.meta',$copyfile)) {
13781:             print $logfile "Copied old target metadata to ".$copyfile."\n";
13782:             $output = 'ok';
13783:         } else {
13784:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
13785:             $output = &mt('Failed to copy old meta').", $!, ";
13786:         }
13787:     } else {
13788:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
13789:         $output = &mt('Failed to copy old target').", $!, ";
13790:     }
13791:     return $output;
13792: }
13793: 
13794: sub write_metadata {
13795:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
13796:     my (%metadatafields,%metadatakeys,$output);
13797:     $metadatafields{'title'}=$formname;
13798:     $metadatafields{'creationdate'}=time;
13799:     $metadatafields{'lastrevisiondate'}=time;
13800:     $metadatafields{'copyright'}='public';
13801:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
13802:                                          $env{'user.domain'};
13803:     $metadatafields{'authorspace'}=$confname.':'.$dom;
13804:     $metadatafields{'domain'}=$dom;
13805:     {
13806:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
13807:         my $mfh;
13808:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
13809:             foreach (sort(keys(%metadatafields))) {
13810:                 unless ($_=~/\./) {
13811:                     my $unikey=$_;
13812:                     $unikey=~/^([A-Za-z]+)/;
13813:                     my $tag=$1;
13814:                     $tag=~tr/A-Z/a-z/;
13815:                     print $mfh "\n\<$tag";
13816:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
13817:                         my $value=$metadatafields{$unikey.'.'.$_};
13818:                         $value=~s/\"/\'\'/g;
13819:                         print $mfh ' '.$_.'="'.$value.'"';
13820:                     }
13821:                     print $mfh '>'.
13822:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
13823:                             .'</'.$tag.'>';
13824:                 }
13825:             }
13826:             $output = 'ok';
13827:             print $logfile "\nWrote metadata";
13828:             close($mfh);
13829:         } else {
13830:             print $logfile "\nFailed to open metadata file";
13831:             $output = &mt('Could not write metadata');
13832:         }
13833:     }
13834:     return $output;
13835: }
13836: 
13837: sub notifysubscribed {
13838:     foreach my $targetsource (@{$modified_urls}){
13839:         next unless (ref($targetsource) eq 'ARRAY');
13840:         my ($target,$source)=@{$targetsource};
13841:         if ($source ne '') {
13842:             if (open(my $logfh,">>",$source.'.log')) {
13843:                 print $logfh "\nCleanup phase: Notifications\n";
13844:                 my @subscribed=&subscribed_hosts($target);
13845:                 foreach my $subhost (@subscribed) {
13846:                     print $logfh "\nNotifying host ".$subhost.':';
13847:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
13848:                     print $logfh $reply;
13849:                 }
13850:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
13851:                 foreach my $subhost (@subscribedmeta) {
13852:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
13853:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
13854:                                                         $subhost);
13855:                     print $logfh $reply;
13856:                 }
13857:                 print $logfh "\n============ Done ============\n";
13858:                 close($logfh);
13859:             }
13860:         }
13861:     }
13862:     return OK;
13863: }
13864: 
13865: sub subscribed_hosts {
13866:     my ($target) = @_;
13867:     my @subscribed;
13868:     if (open(my $fh,"<","$target.subscription")) {
13869:         while (my $subline=<$fh>) {
13870:             if ($subline =~ /^($match_lonid):/) {
13871:                 my $host = $1;
13872:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
13873:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
13874:                         push(@subscribed,$host);
13875:                     }
13876:                 }
13877:             }
13878:         }
13879:     }
13880:     return @subscribed;
13881: }
13882: 
13883: sub check_switchserver {
13884:     my ($dom,$confname) = @_;
13885:     my ($allowed,$switchserver);
13886:     my $home = &Apache::lonnet::homeserver($confname,$dom);
13887:     if ($home eq 'no_host') {
13888:         $home = &Apache::lonnet::domain($dom,'primary');
13889:     }
13890:     my @ids=&Apache::lonnet::current_machine_ids();
13891:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
13892:     if (!$allowed) {
13893: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
13894:     }
13895:     return $switchserver;
13896: }
13897: 
13898: sub modify_quotas {
13899:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13900:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
13901:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
13902:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
13903:         $validationfieldsref);
13904:     if ($action eq 'quotas') {
13905:         $context = 'tools'; 
13906:     } else {
13907:         $context = $action;
13908:     }
13909:     if ($context eq 'requestcourses') {
13910:         @usertools = ('official','unofficial','community','textbook','placement','lti');
13911:         @options =('norequest','approval','validate','autolimit');
13912:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
13913:         %titles = &courserequest_titles();
13914:         $toolregexp = join('|',@usertools);
13915:         %conditions = &courserequest_conditions();
13916:         $confname = $dom.'-domainconfig';
13917:         my $servadm = $r->dir_config('lonAdmEMail');
13918:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13919:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
13920:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
13921:     } elsif ($context eq 'requestauthor') {
13922:         @usertools = ('author');
13923:         %titles = &authorrequest_titles();
13924:     } else {
13925:         @usertools = ('aboutme','blog','webdav','portfolio');
13926:         %titles = &tool_titles();
13927:     }
13928:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13929:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13930:     foreach my $key (keys(%env)) {
13931:         if ($context eq 'requestcourses') {
13932:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
13933:                 my $item = $1;
13934:                 my $type = $2;
13935:                 if ($type =~ /^limit_(.+)/) {
13936:                     $limithash{$item}{$1} = $env{$key};
13937:                 } else {
13938:                     $confhash{$item}{$type} = $env{$key};
13939:                 }
13940:             }
13941:         } elsif ($context eq 'requestauthor') {
13942:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
13943:                 $confhash{$1} = $env{$key};
13944:             }
13945:         } else {
13946:             if ($key =~ /^form\.quota_(.+)$/) {
13947:                 $confhash{'defaultquota'}{$1} = $env{$key};
13948:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
13949:                 $confhash{'authorquota'}{$1} = $env{$key};
13950:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
13951:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
13952:             }
13953:         }
13954:     }
13955:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13956:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
13957:         @approvalnotify = sort(@approvalnotify);
13958:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
13959:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
13960:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
13961:         foreach my $type (@hasuniquecode) {
13962:             if (grep(/^\Q$type\E$/,@crstypes)) {
13963:                 $confhash{'uniquecode'}{$type} = 1;
13964:             }
13965:         }
13966:         my (%newbook,%allpos);
13967:         if ($context eq 'requestcourses') {
13968:             foreach my $type ('textbooks','templates') {
13969:                 @{$allpos{$type}} = (); 
13970:                 my $invalid;
13971:                 if ($type eq 'textbooks') {
13972:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
13973:                 } else {
13974:                     $invalid = &mt('Invalid LON-CAPA course for template');
13975:                 }
13976:                 if ($env{'form.'.$type.'_addbook'}) {
13977:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
13978:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
13979:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
13980:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
13981:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
13982:                         } else {
13983:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
13984:                             my $position = $env{'form.'.$type.'_addbook_pos'};
13985:                             $position =~ s/\D+//g;
13986:                             if ($position ne '') {
13987:                                 $allpos{$type}[$position] = $newbook{$type};
13988:                             }
13989:                         }
13990:                     } else {
13991:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
13992:                     }
13993:                 }
13994:             } 
13995:         }
13996:         if (ref($domconfig{$action}) eq 'HASH') {
13997:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
13998:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
13999:                     $changes{'notify'}{'approval'} = 1;
14000:                 }
14001:             } else {
14002:                 if ($confhash{'notify'}{'approval'}) {
14003:                     $changes{'notify'}{'approval'} = 1;
14004:                 }
14005:             }
14006:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
14007:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
14008:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
14009:                         unless ($confhash{'uniquecode'}{$crstype}) {
14010:                             $changes{'uniquecode'} = 1;
14011:                         }
14012:                     }
14013:                     unless ($changes{'uniquecode'}) {
14014:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
14015:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
14016:                                 $changes{'uniquecode'} = 1;
14017:                             }
14018:                         }
14019:                     }
14020:                } else {
14021:                    $changes{'uniquecode'} = 1;
14022:                }
14023:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
14024:                 $changes{'uniquecode'} = 1;
14025:             }
14026:             if ($context eq 'requestcourses') {
14027:                 foreach my $type ('textbooks','templates') {
14028:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
14029:                         my %deletions;
14030:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
14031:                         if (@todelete) {
14032:                             map { $deletions{$_} = 1; } @todelete;
14033:                         }
14034:                         my %imgdeletions;
14035:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
14036:                         if (@todeleteimages) {
14037:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
14038:                         }
14039:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
14040:                         for (my $i=0; $i<=$maxnum; $i++) {
14041:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
14042:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
14043:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
14044:                                 if ($deletions{$key}) {
14045:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
14046:                                         #FIXME need to obsolete item in RES space
14047:                                     }
14048:                                     next;
14049:                                 } else {
14050:                                     my $newpos = $env{'form.'.$itemid};
14051:                                     $newpos =~ s/\D+//g;
14052:                                     foreach my $item ('subject','title','publisher','author') {
14053:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14054:                                                  ($type eq 'templates'));
14055:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
14056:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
14057:                                             $changes{$type}{$key} = 1;
14058:                                         }
14059:                                     }
14060:                                     $allpos{$type}[$newpos] = $key;
14061:                                 }
14062:                                 if ($imgdeletions{$key}) {
14063:                                     $changes{$type}{$key} = 1;
14064:                                     #FIXME need to obsolete item in RES space
14065:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
14066:                                     my ($cdom,$cnum) = split(/_/,$key);
14067:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14068:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14069:                                     } else {
14070:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
14071:                                                                                       $cdom,$cnum,$type,$configuserok,
14072:                                                                                       $switchserver,$author_ok);
14073:                                         if ($imgurl) {
14074:                                             $confhash{$type}{$key}{'image'} = $imgurl;
14075:                                             $changes{$type}{$key} = 1; 
14076:                                         }
14077:                                         if ($error) {
14078:                                             &Apache::lonnet::logthis($error);
14079:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14080:                                         }
14081:                                     }
14082:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
14083:                                     $confhash{$type}{$key}{'image'} = 
14084:                                         $domconfig{$action}{$type}{$key}{'image'};
14085:                                 }
14086:                             }
14087:                         }
14088:                     }
14089:                 }
14090:             }
14091:         } else {
14092:             if ($confhash{'notify'}{'approval'}) {
14093:                 $changes{'notify'}{'approval'} = 1;
14094:             }
14095:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
14096:                 $changes{'uniquecode'} = 1;
14097:             }
14098:         }
14099:         if ($context eq 'requestcourses') {
14100:             foreach my $type ('textbooks','templates') {
14101:                 if ($newbook{$type}) {
14102:                     $changes{$type}{$newbook{$type}} = 1;
14103:                     foreach my $item ('subject','title','publisher','author') {
14104:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14105:                                  ($type eq 'template'));
14106:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
14107:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
14108:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
14109:                         }
14110:                     }
14111:                     if ($type eq 'textbooks') {
14112:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
14113:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
14114:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14115:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14116:                             } else {
14117:                                 my ($imageurl,$error) =
14118:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
14119:                                                             $configuserok,$switchserver,$author_ok);
14120:                                 if ($imageurl) {
14121:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
14122:                                 }
14123:                                 if ($error) {
14124:                                     &Apache::lonnet::logthis($error);
14125:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14126:                                 }
14127:                             }
14128:                         }
14129:                     }
14130:                 }
14131:                 if (@{$allpos{$type}} > 0) {
14132:                     my $idx = 0;
14133:                     foreach my $item (@{$allpos{$type}}) {
14134:                         if ($item ne '') {
14135:                             $confhash{$type}{$item}{'order'} = $idx;
14136:                             if (ref($domconfig{$action}) eq 'HASH') {
14137:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
14138:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
14139:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
14140:                                             $changes{$type}{$item} = 1;
14141:                                         }
14142:                                     }
14143:                                 }
14144:                             }
14145:                             $idx ++;
14146:                         }
14147:                     }
14148:                 }
14149:             }
14150:             if (ref($validationitemsref) eq 'ARRAY') {
14151:                 foreach my $item (@{$validationitemsref}) {
14152:                     if ($item eq 'fields') {
14153:                         my @changed;
14154:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
14155:                         if (@{$confhash{'validation'}{$item}} > 0) {
14156:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
14157:                         }
14158:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14159:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14160:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
14161:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
14162:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
14163:                                 } else {
14164:                                     @changed = @{$confhash{'validation'}{$item}};
14165:                                 }
14166:                             } else {
14167:                                 @changed = @{$confhash{'validation'}{$item}};
14168:                             }
14169:                         } else {
14170:                             @changed = @{$confhash{'validation'}{$item}};
14171:                         }
14172:                         if (@changed) {
14173:                             if ($confhash{'validation'}{$item}) {
14174:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
14175:                             } else {
14176:                                 $changes{'validation'}{$item} = &mt('None');
14177:                             }
14178:                         }
14179:                     } else {
14180:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
14181:                         if ($item eq 'markup') {
14182:                             if ($env{'form.requestcourses_validation_'.$item}) {
14183:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
14184:                             }
14185:                         }
14186:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14187:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14188:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
14189:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14190:                                 }
14191:                             } else {
14192:                                 if ($confhash{'validation'}{$item} ne '') {
14193:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14194:                                 }
14195:                             }
14196:                         } else {
14197:                             if ($confhash{'validation'}{$item} ne '') {
14198:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14199:                             }
14200:                         }
14201:                     }
14202:                 }
14203:             }
14204:             if ($env{'form.validationdc'}) {
14205:                 my $newval = $env{'form.validationdc'};
14206:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
14207:                 if (exists($domcoords{$newval})) {
14208:                     $confhash{'validation'}{'dc'} = $newval;
14209:                 }
14210:             }
14211:             if (ref($confhash{'validation'}) eq 'HASH') {
14212:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14213:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14214:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14215:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
14216:                                 if ($confhash{'validation'}{'dc'} eq '') {
14217:                                     $changes{'validation'}{'dc'} = &mt('None');
14218:                                 } else {
14219:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14220:                                 }
14221:                             }
14222:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
14223:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14224:                         }
14225:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
14226:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14227:                     }
14228:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
14229:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14230:                 }
14231:             } else {
14232:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14233:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14234:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14235:                             $changes{'validation'}{'dc'} = &mt('None');
14236:                         }
14237:                     }
14238:                 }
14239:             }
14240:         }
14241:     } else {
14242:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
14243:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
14244:     }
14245:     foreach my $item (@usertools) {
14246:         foreach my $type (@{$types},'default','_LC_adv') {
14247:             my $unset; 
14248:             if ($context eq 'requestcourses') {
14249:                 $unset = '0';
14250:                 if ($type eq '_LC_adv') {
14251:                     $unset = '';
14252:                 }
14253:                 if ($confhash{$item}{$type} eq 'autolimit') {
14254:                     $confhash{$item}{$type} .= '=';
14255:                     unless ($limithash{$item}{$type} =~ /\D/) {
14256:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
14257:                     }
14258:                 }
14259:             } elsif ($context eq 'requestauthor') {
14260:                 $unset = '0';
14261:                 if ($type eq '_LC_adv') {
14262:                     $unset = '';
14263:                 }
14264:             } else {
14265:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
14266:                     $confhash{$item}{$type} = 1;
14267:                 } else {
14268:                     $confhash{$item}{$type} = 0;
14269:                 }
14270:             }
14271:             if (ref($domconfig{$action}) eq 'HASH') {
14272:                 if ($action eq 'requestauthor') {
14273:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
14274:                         $changes{$type} = 1;
14275:                     }
14276:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
14277:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
14278:                         $changes{$item}{$type} = 1;
14279:                     }
14280:                 } else {
14281:                     if ($context eq 'requestcourses') {
14282:                         if ($confhash{$item}{$type} ne $unset) {
14283:                             $changes{$item}{$type} = 1;
14284:                         }
14285:                     } else {
14286:                         if (!$confhash{$item}{$type}) {
14287:                             $changes{$item}{$type} = 1;
14288:                         }
14289:                     }
14290:                 }
14291:             } else {
14292:                 if ($context eq 'requestcourses') {
14293:                     if ($confhash{$item}{$type} ne $unset) {
14294:                         $changes{$item}{$type} = 1;
14295:                     }
14296:                 } elsif ($context eq 'requestauthor') {
14297:                     if ($confhash{$type} ne $unset) {
14298:                         $changes{$type} = 1;
14299:                     }
14300:                 } else {
14301:                     if (!$confhash{$item}{$type}) {
14302:                         $changes{$item}{$type} = 1;
14303:                     }
14304:                 }
14305:             }
14306:         }
14307:     }
14308:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
14309:         if (ref($domconfig{'quotas'}) eq 'HASH') {
14310:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14311:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
14312:                     if (exists($confhash{'defaultquota'}{$key})) {
14313:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
14314:                             $changes{'defaultquota'}{$key} = 1;
14315:                         }
14316:                     } else {
14317:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
14318:                     }
14319:                 }
14320:             } else {
14321:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
14322:                     if (exists($confhash{'defaultquota'}{$key})) {
14323:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
14324:                             $changes{'defaultquota'}{$key} = 1;
14325:                         }
14326:                     } else {
14327:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
14328:                     }
14329:                 }
14330:             }
14331:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14332:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
14333:                     if (exists($confhash{'authorquota'}{$key})) {
14334:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
14335:                             $changes{'authorquota'}{$key} = 1;
14336:                         }
14337:                     } else {
14338:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
14339:                     }
14340:                 }
14341:             }
14342:         }
14343:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
14344:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
14345:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14346:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14347:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
14348:                             $changes{'defaultquota'}{$key} = 1;
14349:                         }
14350:                     } else {
14351:                         if (!exists($domconfig{'quotas'}{$key})) {
14352:                             $changes{'defaultquota'}{$key} = 1;
14353:                         }
14354:                     }
14355:                 } else {
14356:                     $changes{'defaultquota'}{$key} = 1;
14357:                 }
14358:             }
14359:         }
14360:         if (ref($confhash{'authorquota'}) eq 'HASH') {
14361:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
14362:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14363:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14364:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
14365:                             $changes{'authorquota'}{$key} = 1;
14366:                         }
14367:                     } else {
14368:                         $changes{'authorquota'}{$key} = 1;
14369:                     }
14370:                 } else {
14371:                     $changes{'authorquota'}{$key} = 1;
14372:                 }
14373:             }
14374:         }
14375:     }
14376: 
14377:     if ($context eq 'requestauthor') {
14378:         $domdefaults{'requestauthor'} = \%confhash;
14379:     } else {
14380:         foreach my $key (keys(%confhash)) {
14381:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
14382:                 $domdefaults{$key} = $confhash{$key};
14383:             }
14384:         }
14385:     }
14386: 
14387:     my %quotahash = (
14388:                       $action => { %confhash }
14389:                     );
14390:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
14391:                                              $dom);
14392:     if ($putresult eq 'ok') {
14393:         if (keys(%changes) > 0) {
14394:             my $cachetime = 24*60*60;
14395:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14396:             if (ref($lastactref) eq 'HASH') {
14397:                 $lastactref->{'domdefaults'} = 1;
14398:             }
14399:             $resulttext = &mt('Changes made:').'<ul>';
14400:             unless (($context eq 'requestcourses') ||
14401:                     ($context eq 'requestauthor')) {
14402:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
14403:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
14404:                     foreach my $type (@{$types},'default') {
14405:                         if (defined($changes{'defaultquota'}{$type})) {
14406:                             my $typetitle = $usertypes->{$type};
14407:                             if ($type eq 'default') {
14408:                                 $typetitle = $othertitle;
14409:                             }
14410:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
14411:                         }
14412:                     }
14413:                     $resulttext .= '</ul></li>';
14414:                 }
14415:                 if (ref($changes{'authorquota'}) eq 'HASH') {
14416:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
14417:                     foreach my $type (@{$types},'default') {
14418:                         if (defined($changes{'authorquota'}{$type})) {
14419:                             my $typetitle = $usertypes->{$type};
14420:                             if ($type eq 'default') {
14421:                                 $typetitle = $othertitle;
14422:                             }
14423:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
14424:                         }
14425:                     }
14426:                     $resulttext .= '</ul></li>';
14427:                 }
14428:             }
14429:             my %newenv;
14430:             foreach my $item (@usertools) {
14431:                 my (%haschgs,%inconf);
14432:                 if ($context eq 'requestauthor') {
14433:                     %haschgs = %changes;
14434:                     %inconf = %confhash;
14435:                 } else {
14436:                     if (ref($changes{$item}) eq 'HASH') {
14437:                         %haschgs = %{$changes{$item}};
14438:                     }
14439:                     if (ref($confhash{$item}) eq 'HASH') {
14440:                         %inconf = %{$confhash{$item}};
14441:                     }
14442:                 }
14443:                 if (keys(%haschgs) > 0) {
14444:                     my $newacc = 
14445:                         &Apache::lonnet::usertools_access($env{'user.name'},
14446:                                                           $env{'user.domain'},
14447:                                                           $item,'reload',$context);
14448:                     if (($context eq 'requestcourses') ||
14449:                         ($context eq 'requestauthor')) {
14450:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
14451:                             $newenv{'environment.canrequest.'.$item} = $newacc;
14452:                         }
14453:                     } else {
14454:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
14455:                             $newenv{'environment.availabletools.'.$item} = $newacc;
14456:                         }
14457:                     }
14458:                     unless ($context eq 'requestauthor') {
14459:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
14460:                     }
14461:                     foreach my $type (@{$types},'default','_LC_adv') {
14462:                         if ($haschgs{$type}) {
14463:                             my $typetitle = $usertypes->{$type};
14464:                             if ($type eq 'default') {
14465:                                 $typetitle = $othertitle;
14466:                             } elsif ($type eq '_LC_adv') {
14467:                                 $typetitle = 'LON-CAPA Advanced Users'; 
14468:                             }
14469:                             if ($inconf{$type}) {
14470:                                 if ($context eq 'requestcourses') {
14471:                                     my $cond;
14472:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
14473:                                         if ($1 eq '') {
14474:                                             $cond = &mt('(Automatic processing of any request).');
14475:                                         } else {
14476:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
14477:                                         }
14478:                                     } else { 
14479:                                         $cond = $conditions{$inconf{$type}};
14480:                                     }
14481:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
14482:                                 } elsif ($context eq 'requestauthor') {
14483:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
14484:                                                              $titles{$inconf{$type}},$typetitle);
14485: 
14486:                                 } else {
14487:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
14488:                                 }
14489:                             } else {
14490:                                 if ($type eq '_LC_adv') {
14491:                                     if ($inconf{$type} eq '0') {
14492:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14493:                                     } else { 
14494:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
14495:                                     }
14496:                                 } else {
14497:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14498:                                 }
14499:                             }
14500:                         }
14501:                     }
14502:                     unless ($context eq 'requestauthor') {
14503:                         $resulttext .= '</ul></li>';
14504:                     }
14505:                 }
14506:             }
14507:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
14508:                 if (ref($changes{'notify'}) eq 'HASH') {
14509:                     if ($changes{'notify'}{'approval'}) {
14510:                         if (ref($confhash{'notify'}) eq 'HASH') {
14511:                             if ($confhash{'notify'}{'approval'}) {
14512:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
14513:                             } else {
14514:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
14515:                             }
14516:                         }
14517:                     }
14518:                 }
14519:             }
14520:             if ($action eq 'requestcourses') {
14521:                 my @offon = ('off','on');
14522:                 if ($changes{'uniquecode'}) {
14523:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
14524:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
14525:                         $resulttext .= '<li>'.
14526:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
14527:                                        '</li>';
14528:                     } else {
14529:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
14530:                                        '</li>';
14531:                     }
14532:                 }
14533:                 foreach my $type ('textbooks','templates') {
14534:                     if (ref($changes{$type}) eq 'HASH') {
14535:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
14536:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
14537:                             my %coursehash = &Apache::lonnet::coursedescription($key);
14538:                             my $coursetitle = $coursehash{'description'};
14539:                             my $position = $confhash{$type}{$key}{'order'} + 1;
14540:                             $resulttext .= '<li>';
14541:                             foreach my $item ('subject','title','publisher','author') {
14542:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
14543:                                          ($type eq 'templates'));
14544:                                 my $name = $item.':';
14545:                                 $name =~ s/^(\w)/\U$1/;
14546:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
14547:                             }
14548:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
14549:                             if ($type eq 'textbooks') {
14550:                                 if ($confhash{$type}{$key}{'image'}) {
14551:                                     $resulttext .= ' '.&mt('Image: [_1]',
14552:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
14553:                                                    ' alt="Textbook cover" />').'<br />';
14554:                                 }
14555:                             }
14556:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
14557:                         }
14558:                         $resulttext .= '</ul></li>';
14559:                     }
14560:                 }
14561:                 if (ref($changes{'validation'}) eq 'HASH') {
14562:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
14563:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
14564:                         foreach my $item (@{$validationitemsref}) {
14565:                             if (exists($changes{'validation'}{$item})) {
14566:                                 if ($item eq 'markup') {
14567:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14568:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
14569:                                 } else {
14570:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14571:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
14572:                                 }
14573:                             }
14574:                         }
14575:                         if (exists($changes{'validation'}{'dc'})) {
14576:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
14577:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
14578:                         }
14579:                     }
14580:                 }
14581:             }
14582:             $resulttext .= '</ul>';
14583:             if (keys(%newenv)) {
14584:                 &Apache::lonnet::appenv(\%newenv);
14585:             }
14586:         } else {
14587:             if ($context eq 'requestcourses') {
14588:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
14589:             } elsif ($context eq 'requestauthor') {
14590:                 $resulttext = &mt('No changes made to rights to request author space.');
14591:             } else {
14592:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
14593:             }
14594:         }
14595:     } else {
14596:         $resulttext = '<span class="LC_error">'.
14597: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14598:     }
14599:     if ($errors) {
14600:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
14601:                        '<ul>'.$errors.'</ul></p>';
14602:     }
14603:     return $resulttext;
14604: }
14605: 
14606: sub process_textbook_image {
14607:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
14608:     my $filename = $env{'form.'.$caller.'.filename'};
14609:     my ($error,$url);
14610:     my ($width,$height) = (50,50);
14611:     if ($configuserok eq 'ok') {
14612:         if ($switchserver) {
14613:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
14614:                          $switchserver);
14615:         } elsif ($author_ok eq 'ok') {
14616:             my ($result,$imageurl) =
14617:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14618:                              "$type/$cdom/$cnum/cover",$width,$height);
14619:             if ($result eq 'ok') {
14620:                 $url = $imageurl;
14621:             } else {
14622:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14623:             }
14624:         } else {
14625:             $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);
14626:         }
14627:     } else {
14628:         $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);
14629:     }
14630:     return ($url,$error);
14631: }
14632: 
14633: sub modify_ltitools {
14634:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14635:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14636:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14637:     my $confname = $dom.'-domainconfig';
14638:     my $servadm = $r->dir_config('lonAdmEMail');
14639:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14640:     my (%posslti,%possfield);
14641:     my @courseroles = ('cc','in','ta','ep','st');
14642:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
14643:     map { $posslti{$_} = 1; } @ltiroles;
14644:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
14645:     map { $possfield{$_} = 1; } @allfields;
14646:     my %lt = &ltitools_names(); 
14647:     if ($env{'form.ltitools_add'}) {
14648:         my $title = $env{'form.ltitools_add_title'};
14649:         $title =~ s/(`)/'/g;
14650:         ($newid,my $error) = &get_ltitools_id($dom,$title);
14651:         if ($newid) {
14652:             my $position = $env{'form.ltitools_add_pos'};
14653:             $position =~ s/\D+//g;
14654:             if ($position ne '') {
14655:                 $allpos[$position] = $newid;
14656:             }
14657:             $changes{$newid} = 1;
14658:             foreach my $item ('title','url','key','secret','lifetime') {
14659:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
14660:                 if ($item eq 'lifetime') {
14661:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
14662:                 }
14663:                 if ($env{'form.ltitools_add_'.$item}) {
14664:                     if (($item eq 'key') || ($item eq 'secret')) {
14665:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14666:                     } else {
14667:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14668:                     }
14669:                 }
14670:             }
14671:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
14672:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
14673:             }
14674:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
14675:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
14676:             }
14677:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
14678:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
14679:             } else {
14680:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
14681:             }
14682:             foreach my $item ('width','height','linktext','explanation') {
14683:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
14684:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
14685:                 if (($item eq 'width') || ($item eq 'height')) {
14686:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
14687:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
14688:                     }
14689:                 } else {
14690:                     if ($env{'form.ltitools_add_'.$item} ne '') {
14691:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
14692:                     }
14693:                 }
14694:             }
14695:             if ($env{'form.ltitools_add_target'} eq 'window') {
14696:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14697:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
14698:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14699:             } else {
14700:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
14701:             }
14702:             foreach my $item ('passback','roster') {
14703:                 if ($env{'form.ltitools_'.$item.'_add'}) {
14704:                     $confhash{$newid}{$item} = 1;
14705:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
14706:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
14707:                         $lifetime =~ s/^\s+|\s+$//g;
14708:                         if ($lifetime =~ /^\d+\.?\d*$/) {
14709:                             $confhash{$newid}{$item.'valid'} = $lifetime;
14710:                         }
14711:                     }
14712:                 }
14713:             }
14714:             if ($env{'form.ltitools_add_image.filename'} ne '') {
14715:                 my ($imageurl,$error) =
14716:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
14717:                                             $configuserok,$switchserver,$author_ok);
14718:                 if ($imageurl) {
14719:                     $confhash{$newid}{'image'} = $imageurl;
14720:                 }
14721:                 if ($error) {
14722:                     &Apache::lonnet::logthis($error);
14723:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14724:                 }
14725:             }
14726:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
14727:             foreach my $field (@fields) {
14728:                 if ($possfield{$field}) {
14729:                     if ($field eq 'roles') {
14730:                         foreach my $role (@courseroles) {
14731:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
14732:                             if (($choice ne '') && ($posslti{$choice})) {
14733:                                 $confhash{$newid}{'roles'}{$role} = $choice;
14734:                                 if ($role eq 'cc') {
14735:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
14736:                                 }
14737:                             }
14738:                         }
14739:                     } else {
14740:                         $confhash{$newid}{'fields'}{$field} = 1;
14741:                     }
14742:                 }
14743:             }
14744:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
14745:                 if ($confhash{$newid}{'fields'}{'user'}) {
14746:                     if ($env{'form.ltitools_userincdom_add'}) {
14747:                         $confhash{$newid}{'incdom'} = 1;
14748:                     }
14749:                 }
14750:             }
14751:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
14752:             foreach my $item (@courseconfig) {
14753:                 $confhash{$newid}{'crsconf'}{$item} = 1;
14754:             }
14755:             if ($env{'form.ltitools_add_custom'}) {
14756:                 my $name = $env{'form.ltitools_add_custom_name'};
14757:                 my $value = $env{'form.ltitools_add_custom_value'};
14758:                 $value =~ s/(`)/'/g;
14759:                 $name =~ s/(`)/'/g;
14760:                 $confhash{$newid}{'custom'}{$name} = $value;
14761:             }
14762:         } else {
14763:             my $error = &mt('Failed to acquire unique ID for new external tool');   
14764:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14765:         }
14766:     }
14767:     if (ref($domconfig{$action}) eq 'HASH') {
14768:         my %deletions;
14769:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
14770:         if (@todelete) {
14771:             map { $deletions{$_} = 1; } @todelete;
14772:         }
14773:         my %customadds;
14774:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
14775:         if (@newcustom) {
14776:             map { $customadds{$_} = 1; } @newcustom;
14777:         } 
14778:         my %imgdeletions;
14779:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
14780:         if (@todeleteimages) {
14781:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14782:         }
14783:         my $maxnum = $env{'form.ltitools_maxnum'};
14784:         for (my $i=0; $i<=$maxnum; $i++) {
14785:             my $itemid = $env{'form.ltitools_id_'.$i};
14786:             $itemid =~ s/\D+//g;
14787:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14788:                 if ($deletions{$itemid}) {
14789:                     if ($domconfig{$action}{$itemid}{'image'}) {
14790:                         #FIXME need to obsolete item in RES space
14791:                     }
14792:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
14793:                     next;
14794:                 } else {
14795:                     my $newpos = $env{'form.ltitools_'.$itemid};
14796:                     $newpos =~ s/\D+//g;
14797:                     foreach my $item ('title','url','lifetime') {
14798:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14799:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14800:                             $changes{$itemid} = 1;
14801:                         }
14802:                     }
14803:                     foreach my $item ('key','secret') {
14804:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14805:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
14806:                             $changes{$itemid} = 1;
14807:                         }
14808:                     }
14809:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
14810:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
14811:                     }
14812:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
14813:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
14814:                     }
14815:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
14816:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
14817:                     } else {
14818:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
14819:                     }
14820:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
14821:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
14822:                             $changes{$itemid} = 1;
14823:                         }
14824:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
14825:                         $changes{$itemid} = 1;
14826:                     }
14827:                     foreach my $size ('width','height') {
14828:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
14829:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
14830:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
14831:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
14832:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14833:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
14834:                                     $changes{$itemid} = 1;
14835:                                 }
14836:                             } else {
14837:                                 $changes{$itemid} = 1;
14838:                             }
14839:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14840:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
14841:                                 $changes{$itemid} = 1;
14842:                             }
14843:                         }
14844:                     }
14845:                     foreach my $item ('linktext','explanation') {
14846:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
14847:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
14848:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
14849:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14850:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14851:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
14852:                                     $changes{$itemid} = 1;
14853:                                 }
14854:                             } else {
14855:                                 $changes{$itemid} = 1;
14856:                             }
14857:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14858:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
14859:                                 $changes{$itemid} = 1;
14860:                             }
14861:                         }
14862:                     }
14863:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
14864:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14865:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
14866:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14867:                     } else {
14868:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
14869:                     }
14870:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14871:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
14872:                             $changes{$itemid} = 1;
14873:                         }
14874:                     } else {
14875:                         $changes{$itemid} = 1;
14876:                     }
14877:                     foreach my $extra ('passback','roster') {
14878:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
14879:                             $confhash{$itemid}{$extra} = 1;
14880:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
14881:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
14882:                                 $lifetime =~ s/^\s+|\s+$//g;
14883:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
14884:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
14885:                                 }
14886:                             }
14887:                         }
14888:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
14889:                             $changes{$itemid} = 1;
14890:                         }
14891:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
14892:                             $changes{$itemid} = 1;
14893:                         }
14894:                     }
14895:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
14896:                     foreach my $item ('label','title','target','linktext','explanation','append') {
14897:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
14898:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
14899:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
14900:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
14901:                                     $changes{$itemid} = 1;
14902:                                 }
14903:                             } else {
14904:                                 $changes{$itemid} = 1;
14905:                             }
14906:                         }
14907:                     }
14908:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
14909:                     foreach my $field (@fields) {
14910:                         if ($possfield{$field}) {
14911:                             if ($field eq 'roles') {
14912:                                 foreach my $role (@courseroles) {
14913:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
14914:                                     if (($choice ne '') && ($posslti{$choice})) {
14915:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
14916:                                         if ($role eq 'cc') {
14917:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
14918:                                         }
14919:                                     }
14920:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
14921:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
14922:                                             $changes{$itemid} = 1;
14923:                                         }
14924:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
14925:                                         $changes{$itemid} = 1;
14926:                                     }
14927:                                 }
14928:                             } else {
14929:                                 $confhash{$itemid}{'fields'}{$field} = 1;
14930:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
14931:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
14932:                                         $changes{$itemid} = 1;
14933:                                     }
14934:                                 } else {
14935:                                     $changes{$itemid} = 1;
14936:                                 }
14937:                             }
14938:                         }
14939:                     }
14940:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
14941:                         if ($confhash{$itemid}{'fields'}{'user'}) {
14942:                             if ($env{'form.ltitools_userincdom_'.$i}) {
14943:                                 $confhash{$itemid}{'incdom'} = 1;
14944:                             }
14945:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
14946:                                 $changes{$itemid} = 1;
14947:                             }
14948:                         }
14949:                     }
14950:                     $allpos[$newpos] = $itemid;
14951:                 }
14952:                 if ($imgdeletions{$itemid}) {
14953:                     $changes{$itemid} = 1;
14954:                     #FIXME need to obsolete item in RES space
14955:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
14956:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
14957:                                                                  $itemid,$configuserok,$switchserver,
14958:                                                                  $author_ok);
14959:                     if ($imgurl) {
14960:                         $confhash{$itemid}{'image'} = $imgurl;
14961:                         $changes{$itemid} = 1;
14962:                     }
14963:                     if ($error) {
14964:                         &Apache::lonnet::logthis($error);
14965:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14966:                     }
14967:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
14968:                     $confhash{$itemid}{'image'} =
14969:                        $domconfig{$action}{$itemid}{'image'};
14970:                 }
14971:                 if ($customadds{$i}) {
14972:                     my $name = $env{'form.ltitools_custom_name_'.$i};
14973:                     $name =~ s/(`)/'/g;
14974:                     $name =~ s/^\s+//;
14975:                     $name =~ s/\s+$//;
14976:                     my $value = $env{'form.ltitools_custom_value_'.$i};
14977:                     $value =~ s/(`)/'/g;
14978:                     $value =~ s/^\s+//;
14979:                     $value =~ s/\s+$//;
14980:                     if ($name ne '') {
14981:                         $confhash{$itemid}{'custom'}{$name} = $value;
14982:                         $changes{$itemid} = 1;
14983:                     }
14984:                 }
14985:                 my %customdels;
14986:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
14987:                 if (@customdeletions) {
14988:                     $changes{$itemid} = 1;
14989:                 }
14990:                 map { $customdels{$_} = 1; } @customdeletions;
14991:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
14992:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
14993:                         unless ($customdels{$key}) {
14994:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
14995:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
14996:                             }
14997:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
14998:                                 $changes{$itemid} = 1;
14999:                             }
15000:                         }
15001:                     }
15002:                 }
15003:                 unless ($changes{$itemid}) {
15004:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
15005:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
15006:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
15007:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
15008:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
15009:                                         $changes{$itemid} = 1;
15010:                                         last;
15011:                                     }
15012:                                 }
15013:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
15014:                                 $changes{$itemid} = 1;
15015:                             }
15016:                         }
15017:                         last if ($changes{$itemid});
15018:                     }
15019:                 }
15020:             }
15021:         }
15022:     }
15023:     if (@allpos > 0) {
15024:         my $idx = 0;
15025:         foreach my $itemid (@allpos) {
15026:             if ($itemid ne '') {
15027:                 $confhash{$itemid}{'order'} = $idx;
15028:                 if (ref($domconfig{$action}) eq 'HASH') {
15029:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15030:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
15031:                             $changes{$itemid} = 1;
15032:                         }
15033:                     }
15034:                 }
15035:                 $idx ++;
15036:             }
15037:         }
15038:     }
15039:     my %ltitoolshash = (
15040:                           $action => { %confhash }
15041:                        );
15042:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
15043:                                              $dom);
15044:     if ($putresult eq 'ok') {
15045:         my %ltienchash = (
15046:                              $action => { %encconfig }
15047:                          );
15048:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
15049:         if (keys(%changes) > 0) {
15050:             my $cachetime = 24*60*60;
15051:             my %ltiall = %confhash;
15052:             foreach my $id (keys(%ltiall)) {
15053:                 if (ref($encconfig{$id}) eq 'HASH') {
15054:                     foreach my $item ('key','secret') {
15055:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
15056:                     }
15057:                 }
15058:             }
15059:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
15060:             if (ref($lastactref) eq 'HASH') {
15061:                 $lastactref->{'ltitools'} = 1;
15062:             }
15063:             $resulttext = &mt('Changes made:').'<ul>';
15064:             my %bynum;
15065:             foreach my $itemid (sort(keys(%changes))) {
15066:                 my $position = $confhash{$itemid}{'order'};
15067:                 $bynum{$position} = $itemid;
15068:             }
15069:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15070:                 my $itemid = $bynum{$pos}; 
15071:                 if (ref($confhash{$itemid}) ne 'HASH') {
15072:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
15073:                 } else {
15074:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
15075:                     if ($confhash{$itemid}{'image'}) {
15076:                         $resulttext .= '&nbsp;'.
15077:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
15078:                                        ' alt="'.&mt('Tool Provider icon').'" />';
15079:                     }
15080:                     $resulttext .= '</li><ul>';
15081:                     my $position = $pos + 1;
15082:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15083:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
15084:                         if ($confhash{$itemid}{$item} ne '') {
15085:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15086:                         }
15087:                     }
15088:                     if ($encconfig{$itemid}{'key'} ne '') {
15089:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
15090:                     }
15091:                     if ($encconfig{$itemid}{'secret'} ne '') {
15092:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15093:                         my $num = length($encconfig{$itemid}{'secret'});
15094:                         $resulttext .= ('*'x$num).'</li>';
15095:                     }
15096:                     $resulttext .= '<li>'.&mt('Configurable in course:');
15097:                     my @possconfig = ('label','title','target','linktext','explanation','append');
15098:                     my $numconfig = 0; 
15099:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
15100:                         foreach my $item (@possconfig) {
15101:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
15102:                                 $numconfig ++;
15103:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
15104:                             }
15105:                         }
15106:                     }
15107:                     if (!$numconfig) {
15108:                         $resulttext .= '&nbsp;'.&mt('None');
15109:                     }
15110:                     $resulttext .= '</li>';
15111:                     foreach my $item ('passback','roster') {
15112:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
15113:                         if ($confhash{$itemid}{$item}) {
15114:                             $resulttext .= &mt('Yes');
15115:                             if ($confhash{$itemid}{$item.'valid'}) {
15116:                                 if ($item eq 'passback') {
15117:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
15118:                                                            $confhash{$itemid}{$item.'valid'});
15119:                                 } else {
15120:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
15121:                                                            $confhash{$itemid}{$item.'valid'});
15122:                                 }
15123:                             }
15124:                         } else {
15125:                             $resulttext .= &mt('No');
15126:                         }
15127:                         $resulttext .= '</li>';
15128:                     }
15129:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
15130:                         my $displaylist;
15131:                         if ($confhash{$itemid}{'display'}{'target'}) {
15132:                             $displaylist = &mt('Display target').':&nbsp;'.
15133:                                            $confhash{$itemid}{'display'}{'target'}.',';
15134:                         }
15135:                         foreach my $size ('width','height') { 
15136:                             if ($confhash{$itemid}{'display'}{$size}) {
15137:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
15138:                                                 $confhash{$itemid}{'display'}{$size}.',';
15139:                             }
15140:                         }
15141:                         if ($displaylist) {
15142:                             $displaylist =~ s/,$//;
15143:                             $resulttext .= '<li>'.$displaylist.'</li>';
15144:                         }
15145:                         foreach my $item ('linktext','explanation') {
15146:                             if ($confhash{$itemid}{'display'}{$item}) {
15147:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
15148:                             }
15149:                         }
15150:                     }
15151:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
15152:                         my $fieldlist;
15153:                         foreach my $field (@allfields) {
15154:                             if ($confhash{$itemid}{'fields'}{$field}) {
15155:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
15156:                             }
15157:                         }
15158:                         if ($fieldlist) {
15159:                             $fieldlist =~ s/,$//;
15160:                             if ($confhash{$itemid}{'fields'}{'user'}) {
15161:                                 if ($confhash{$itemid}{'incdom'}) {
15162:                                     $fieldlist .= ' ('.&mt('username:domain').')';
15163:                                 } else {
15164:                                     $fieldlist .= ' ('.&mt('username').')';
15165:                                 }
15166:                             }
15167:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
15168:                         }
15169:                     }
15170:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
15171:                         my $rolemaps;
15172:                         foreach my $role (@courseroles) {
15173:                             if ($confhash{$itemid}{'roles'}{$role}) {
15174:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15175:                                              $confhash{$itemid}{'roles'}{$role}.',';
15176:                             }
15177:                         }
15178:                         if ($rolemaps) {
15179:                             $rolemaps =~ s/,$//; 
15180:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15181:                         }
15182:                     }
15183:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
15184:                         my $customlist;
15185:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
15186:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
15187:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
15188:                             } 
15189:                         }
15190:                         if ($customlist) {
15191:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15192:                         }
15193:                     } 
15194:                     $resulttext .= '</ul></li>';
15195:                 }
15196:             }
15197:             $resulttext .= '</ul>';
15198:         } else {
15199:             $resulttext = &mt('No changes made.');
15200:         }
15201:     } else {
15202:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15203:     }
15204:     if ($errors) {
15205:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15206:                        $errors.'</ul>';
15207:     }
15208:     return $resulttext;
15209: }
15210: 
15211: sub process_ltitools_image {
15212:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
15213:     my $filename = $env{'form.'.$caller.'.filename'};
15214:     my ($error,$url);
15215:     my ($width,$height) = (21,21);
15216:     if ($configuserok eq 'ok') {
15217:         if ($switchserver) {
15218:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
15219:                          $switchserver);
15220:         } elsif ($author_ok eq 'ok') {
15221:             my ($result,$imageurl,$madethumb) =
15222:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15223:                              "ltitools/$itemid/icon",$width,$height);
15224:             if ($result eq 'ok') {
15225:                 if ($madethumb) {
15226:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15227:                     my $imagethumb = "$path/tn-".$imagefile;
15228:                     $url = $imagethumb;
15229:                 } else {
15230:                     $url = $imageurl;
15231:                 }
15232:             } else {
15233:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15234:             }
15235:         } else {
15236:             $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);
15237:         }
15238:     } else {
15239:         $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);
15240:     }
15241:     return ($url,$error);
15242: }
15243: 
15244: sub get_ltitools_id {
15245:     my ($cdom,$title) = @_;
15246:     # get lock on ltitools db
15247:     my $lockhash = {
15248:                       lock => $env{'user.name'}.
15249:                               ':'.$env{'user.domain'},
15250:                    };
15251:     my $tries = 0;
15252:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15253:     my ($id,$error);
15254:  
15255:     while (($gotlock ne 'ok') && ($tries<10)) {
15256:         $tries ++;
15257:         sleep (0.1);
15258:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15259:     }
15260:     if ($gotlock eq 'ok') {
15261:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
15262:         if ($currids{'lock'}) {
15263:             delete($currids{'lock'});
15264:             if (keys(%currids)) {
15265:                 my @curr = sort { $a <=> $b } keys(%currids);
15266:                 if ($curr[-1] =~ /^\d+$/) {
15267:                     $id = 1 + $curr[-1];
15268:                 }
15269:             } else {
15270:                 $id = 1;
15271:             }
15272:             if ($id) {
15273:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
15274:                     $error = 'nostore';
15275:                 }
15276:             } else {
15277:                 $error = 'nonumber';
15278:             }
15279:         }
15280:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
15281:     } else {
15282:         $error = 'nolock';
15283:     }
15284:     return ($id,$error);
15285: }
15286: 
15287: sub modify_proctoring {
15288:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15289:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15290:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
15291:     my $confname = $dom.'-domainconfig';
15292:     my $servadm = $r->dir_config('lonAdmEMail');
15293:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
15294:     my %providernames = &proctoring_providernames();
15295:     my $maxnum = scalar(keys(%providernames));
15296: 
15297:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
15298:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
15299:     if (ref($requref) eq 'HASH') {
15300:         %requserfields = %{$requref};
15301:     }
15302:     if (ref($opturef) eq 'HASH') {
15303:         %optuserfields = %{$opturef};
15304:     }
15305:     if (ref($defref) eq 'HASH') {
15306:         %defaults = %{$defref};
15307:     }
15308:     if (ref($extref) eq 'HASH') {
15309:         %extended = %{$extref};
15310:     }
15311:     if (ref($crsref) eq 'HASH') {
15312:         %crsconf = %{$crsref};
15313:     }
15314:     if (ref($rolesref) eq 'ARRAY') {
15315:         @courseroles = @{$rolesref};
15316:     }
15317:     if (ref($ltiref) eq 'ARRAY') {
15318:         @ltiroles = @{$ltiref};
15319:     }
15320: 
15321:     if (ref($domconfig{$action}) eq 'HASH') {
15322:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
15323:         if (@todeleteimages) {
15324:             map { $imgdeletions{$_} = 1; } @todeleteimages;
15325:         }
15326:     }
15327:     my %customadds;
15328:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
15329:     if (@newcustom) {
15330:         map { $customadds{$_} = 1; } @newcustom;
15331:     }
15332:     foreach my $provider (sort(keys(%providernames))) {
15333:         $confhash{$provider} = {};
15334:         my $pos = $env{'form.proctoring_pos_'.$provider};
15335:         $pos =~ s/\D+//g;
15336:         $allpos[$pos] = $provider;
15337:         my (%current,%currentenc);
15338:         my $showroles = 0;
15339:         if (ref($domconfig{$action}) eq 'HASH') {
15340:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15341:                 %current = %{$domconfig{$action}{$provider}};
15342:                 foreach my $item ('key','secret') { 
15343:                     $currentenc{$item} = $current{$item};
15344:                     delete($current{$item});
15345:                 }
15346:             }
15347:         }
15348:         if ($env{'form.proctoring_available_'.$provider}) {
15349:             $confhash{$provider}{'available'} = 1;
15350:             unless ($current{'available'}) {
15351:                 $changes{$provider} = 1;
15352:             }
15353:         } else {
15354:             %{$confhash{$provider}} = %current;
15355:             %{$encconfhash{$provider}} = %currentenc;
15356:             $confhash{$provider}{'available'} = 0;
15357:             if ($current{'available'}) {
15358:                 $changes{$provider} = 1;
15359:             }
15360:         }
15361:         if ($confhash{$provider}{'available'}) {
15362:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
15363:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
15364:                 if ($field eq 'lifetime') {
15365:                     if ($possval =~ /^\d+$/) {
15366:                         $confhash{$provider}{$field} = $possval;
15367:                     }
15368:                 } elsif ($field eq 'version') {
15369:                     if ($possval =~ /^\d+\.\d+$/) {
15370:                         $confhash{$provider}{$field} = $possval;
15371:                     }
15372:                 } elsif ($field eq 'sigmethod') {
15373:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
15374:                         $confhash{$provider}{$field} = $possval;
15375:                     }
15376:                 } elsif ($field eq 'url') {
15377:                     $confhash{$provider}{$field} = $possval;
15378:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
15379:                     $encconfhash{$provider}{$field} = $possval;
15380:                     unless ($currentenc{$field} eq $possval) {
15381:                         $changes{$provider} = 1;
15382:                     }
15383:                 }
15384:                 unless (($field eq 'key') || ($field eq 'secret')) {
15385:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
15386:                         $changes{$provider} = 1;
15387:                     }
15388:                 }
15389:             }
15390:             if ($imgdeletions{$provider}) {
15391:                 $changes{$provider} = 1;
15392:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
15393:                 my ($imageurl,$error) =
15394:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
15395:                                               $configuserok,$switchserver,$author_ok);
15396:                 if ($imageurl) {
15397:                     $confhash{$provider}{'image'} = $imageurl;
15398:                     $changes{$provider} = 1; 
15399:                 }
15400:                 if ($error) {
15401:                     &Apache::lonnet::logthis($error);
15402:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15403:                 }
15404:             } elsif (exists($current{'image'})) {
15405:                 $confhash{$provider}{'image'} = $current{'image'};
15406:             }
15407:             if (ref($requserfields{$provider}) eq 'ARRAY') {
15408:                 if (@{$requserfields{$provider}} > 0) {
15409:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
15410:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
15411:                             $confhash{$provider}{'incdom'} = 1;
15412:                         }
15413:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
15414:                             $changes{$provider} = 1;
15415:                         }
15416:                     }
15417:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
15418:                         $showroles = 1;
15419:                     }
15420:                 }
15421:             }
15422:             $confhash{$provider}{'fields'} = [];
15423:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
15424:                 if (@{$optuserfields{$provider}} > 0) {
15425:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
15426:                     foreach my $field (@{$optuserfields{$provider}}) {
15427:                         if (grep(/^\Q$field\E$/,@optfields)) {
15428:                             push(@{$confhash{$provider}{'fields'}},$field);
15429:                         }
15430:                     }
15431:                 }
15432:                 if (ref($current{'fields'}) eq 'ARRAY') {
15433:                     unless ($changes{$provider}) {
15434:                         my @new = sort(@{$confhash{$provider}{'fields'}});
15435:                         my @old = sort(@{$current{'fields'}}); 
15436:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15437:                         if (@diffs) {
15438:                             $changes{$provider} = 1;
15439:                         }
15440:                     }
15441:                 } elsif (@{$confhash{$provider}{'fields'}}) {
15442:                     $changes{$provider} = 1;
15443:                 }
15444:             }
15445:             if (ref($defaults{$provider}) eq 'ARRAY') {  
15446:                 if (@{$defaults{$provider}} > 0) {
15447:                     my %options;
15448:                     if (ref($extended{$provider}) eq 'HASH') {
15449:                         %options = %{$extended{$provider}};
15450:                     }
15451:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
15452:                     foreach my $field (@{$defaults{$provider}}) {
15453:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
15454:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
15455:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
15456:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
15457:                             }
15458:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
15459:                             foreach my $inner (keys(%{$options{$field}})) {
15460:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
15461:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
15462:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
15463:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
15464:                                     }
15465:                                 } else {
15466:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
15467:                                 }
15468:                             }
15469:                         } else {
15470:                             if (grep(/^\Q$field\E$/,@checked)) {
15471:                                 push(@{$confhash{$provider}{'defaults'}},$field);
15472:                             }
15473:                         }
15474:                     }
15475:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15476:                         if (ref($current{'defaults'}) eq 'ARRAY') {
15477:                             unless ($changes{$provider}) {
15478:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
15479:                                 my @old = sort(@{$current{'defaults'}});
15480:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15481:                                 if (@diffs) {
15482:                                     $changes{$provider} = 1; 
15483:                                 }
15484:                             }
15485:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
15486:                             if (@{$current{'defaults'}}) {
15487:                                 $changes{$provider} = 1;
15488:                             }
15489:                         }
15490:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15491:                         if (ref($current{'defaults'}) eq 'HASH') {
15492:                             unless ($changes{$provider}) {
15493:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
15494:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
15495:                                         $changes{$provider} = 1;
15496:                                         last;
15497:                                     }
15498:                                 }
15499:                             }
15500:                             unless ($changes{$provider}) {
15501:                                 foreach my $key (keys(%{$current{'defaults'}})) {
15502:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
15503:                                         $changes{$provider} = 1;
15504:                                         last;
15505:                                     }
15506:                                 }
15507:                             }
15508:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
15509:                             $changes{$provider} = 1;
15510:                         }
15511:                     }
15512:                 }
15513:             }
15514:             if (ref($crsconf{$provider}) eq 'ARRAY') {
15515:                 if (@{$crsconf{$provider}} > 0) {
15516:                     $confhash{$provider}{'crsconf'} = [];
15517:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
15518:                     foreach my $crsfield (@{$crsconf{$provider}}) {
15519:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
15520:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
15521:                         }
15522:                     }
15523:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
15524:                         unless ($changes{$provider}) {  
15525:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
15526:                             my @old = sort(@{$current{'crsconf'}});
15527:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15528:                             if (@diffs) {
15529:                                 $changes{$provider} = 1;
15530:                             }
15531:                         }
15532:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
15533:                         $changes{$provider} = 1;
15534:                     }
15535:                 }
15536:             }
15537:             if ($showroles) {
15538:                 $confhash{$provider}{'roles'} = {};
15539:                 foreach my $role (@courseroles) {
15540:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
15541:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
15542:                         $confhash{$provider}{'roles'}{$role} = $poss;
15543:                     }
15544:                 }
15545:                 unless ($changes{$provider}) {
15546:                     if (ref($current{'roles'}) eq 'HASH') {
15547:                         foreach my $role (keys(%{$current{'roles'}})) {
15548:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
15549:                                 $changes{$provider} = 1;
15550:                                 last
15551:                             }
15552:                         }
15553:                         unless ($changes{$provider}) {
15554:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
15555:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
15556:                                     $changes{$provider} = 1;
15557:                                     last;
15558:                                 }
15559:                             }
15560:                         }
15561:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
15562:                         $changes{$provider} = 1;
15563:                     }
15564:                 }
15565:             }
15566:             if (ref($current{'custom'}) eq 'HASH') {
15567:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
15568:                 foreach my $key (keys(%{$current{'custom'}})) {
15569:                     if (grep(/^\Q$key\E$/,@customdels)) {
15570:                         $changes{$provider} = 1;
15571:                     } else {
15572:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
15573:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
15574:                             $changes{$provider} = 1;
15575:                         }
15576:                     }
15577:                 }
15578:             }
15579:             if ($customadds{$provider}) {
15580:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
15581:                 $name =~ s/(`)/'/g;
15582:                 $name =~ s/^\s+//;
15583:                 $name =~ s/\s+$//;
15584:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
15585:                 $value =~ s/(`)/'/g;
15586:                 $value =~ s/^\s+//;
15587:                 $value =~ s/\s+$//;
15588:                 if ($name ne '') {
15589:                     $confhash{$provider}{'custom'}{$name} = $value;
15590:                     $changes{$provider} = 1;
15591:                 }
15592:             }
15593:         }
15594:     }
15595:     if (@allpos > 0) {
15596:         my $idx = 0;
15597:         foreach my $provider (@allpos) {
15598:             if ($provider ne '') {
15599:                 $confhash{$provider}{'order'} = $idx;
15600:                 unless ($changes{$provider}) {
15601:                     if (ref($domconfig{$action}) eq 'HASH') {
15602:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15603:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
15604:                                 $changes{$provider} = 1;
15605:                             }
15606:                         }
15607:                     }
15608:                 }
15609:                 $idx ++;
15610:             }
15611:         }
15612:     }
15613:     my %proc_hash = (
15614:                           $action => { %confhash }
15615:                        );
15616:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
15617:                                              $dom);
15618:     if ($putresult eq 'ok') {
15619:         my %proc_enchash = (
15620:                              $action => { %encconfhash }
15621:                          );
15622:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
15623:         if (keys(%changes) > 0) {
15624:             my $cachetime = 24*60*60;
15625:             my %procall = %confhash;
15626:             foreach my $provider (keys(%procall)) {
15627:                 if (ref($encconfhash{$provider}) eq 'HASH') {
15628:                     foreach my $key ('key','secret') {
15629:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
15630:                     }
15631:                 }
15632:             }
15633:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
15634:             if (ref($lastactref) eq 'HASH') {
15635:                 $lastactref->{'proctoring'} = 1;
15636:             }
15637:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
15638:             my %bynum;
15639:             foreach my $provider (sort(keys(%changes))) {
15640:                 my $position = $confhash{$provider}{'order'};
15641:                 $bynum{$position} = $provider;
15642:             }
15643:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15644:                 my $provider = $bynum{$pos};
15645:                 my %lt = &proctoring_titles($provider);
15646:                 my %fieldtitles = &proctoring_fieldtitles($provider);
15647:                 if (!$confhash{$provider}{'available'}) {
15648:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
15649:                 } else {
15650:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
15651:                     if ($confhash{$provider}{'image'}) {
15652:                         $resulttext .= '&nbsp;'.
15653:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
15654:                                        ' alt="'.&mt('Proctoring icon').'" />';
15655:                     }
15656:                     $resulttext .= '<ul>';
15657:                     my $position = $pos + 1;
15658:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15659:                     foreach my $key ('version','sigmethod','url','lifetime') {
15660:                         if ($confhash{$provider}{$key} ne '') {
15661:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
15662:                         }
15663:                     }
15664:                     if ($encconfhash{$provider}{'key'} ne '') {
15665:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
15666:                     }
15667:                     if ($encconfhash{$provider}{'secret'} ne '') {
15668:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15669:                         my $num = length($encconfhash{$provider}{'secret'});
15670:                         $resulttext .= ('*'x$num).'</li>';
15671:                     }
15672:                     my (@fields,$showroles);
15673:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15674:                         push(@fields,@{$requserfields{$provider}});
15675:                     }
15676:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
15677:                         push(@fields,@{$confhash{$provider}{'fields'}});
15678:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
15679:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
15680:                     }
15681:                     if (@fields) {
15682:                         if (grep(/^roles$/,@fields)) {
15683:                             $showroles = 1;
15684:                         }
15685:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
15686:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
15687:                     }
15688:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15689:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
15690:                             if ($confhash{$provider}{'incdom'}) {
15691:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
15692:                             } else { 
15693:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
15694:                             }
15695:                         }
15696:                     }
15697:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15698:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
15699:                             $resulttext .= '<li>'.$lt{'defa'};
15700:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
15701:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
15702:                             }
15703:                             $resulttext =~ s/,$//;
15704:                             $resulttext .= '</li>';
15705:                         }
15706:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15707:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
15708:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
15709:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
15710:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
15711:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
15712:                                 }
15713:                             }
15714:                             $resulttext .= '</ul></li>';
15715:                         }
15716:                     }
15717:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
15718:                         if (@{$crsconf{$provider}} > 0) {
15719:                             $resulttext .= '<li>'.&mt('Configurable in course:');
15720:                             my $numconfig = 0;
15721:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
15722:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
15723:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
15724:                                         $numconfig ++;
15725:                                         if ($provider eq 'examity') {
15726:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
15727:                                         } else {
15728:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
15729:                                         }
15730:                                     }
15731:                                     $resulttext =~ s/,$//;
15732:                                 }
15733:                             }
15734:                             if (!$numconfig) {
15735:                                 $resulttext .= '&nbsp;'.&mt('None');
15736:                             }
15737:                             $resulttext .= '</li>';
15738:                         }
15739:                     }
15740:                     if ($showroles) {
15741:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
15742:                             my $rolemaps;
15743:                             foreach my $role (@courseroles) {
15744:                                 if ($confhash{$provider}{'roles'}{$role}) {
15745:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15746:                                                  $confhash{$provider}{'roles'}{$role}.',';
15747:                                 }
15748:                             }
15749:                             if ($rolemaps) {
15750:                                 $rolemaps =~ s/,$//;
15751:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15752:                             }
15753:                         }
15754:                     }
15755:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
15756:                         my $customlist;
15757:                         if (keys(%{$confhash{$provider}{'custom'}})) {
15758:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
15759:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
15760:                             }
15761:                             $customlist =~ s/,$//;
15762:                         }
15763:                         if ($customlist) {
15764:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15765:                         }
15766:                     } 
15767:                     $resulttext .= '</ul></li>';
15768:                 }
15769:             }
15770:             $resulttext .= '</ul>';
15771:         } else {
15772:             $resulttext = &mt('No changes made.');
15773:         }
15774:     } else {
15775:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15776:     }
15777:     if ($errors) {
15778:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15779:                        $errors.'</ul>';
15780:     }
15781:     return $resulttext;
15782: }
15783: 
15784: sub process_proctoring_image {
15785:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
15786:     my $filename = $env{'form.'.$caller.'.filename'};
15787:     my ($error,$url);
15788:     my ($width,$height) = (21,21);
15789:     if ($configuserok eq 'ok') {
15790:         if ($switchserver) {
15791:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
15792:                          $switchserver);
15793:         } elsif ($author_ok eq 'ok') {
15794:             my ($result,$imageurl,$madethumb) =
15795:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15796:                              "proctoring/$provider/icon",$width,$height);
15797:             if ($result eq 'ok') {
15798:                 if ($madethumb) {
15799:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15800:                     my $imagethumb = "$path/tn-".$imagefile;
15801:                     $url = $imagethumb;
15802:                 } else {
15803:                     $url = $imageurl;
15804:                 }
15805:             } else {
15806:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15807:             }
15808:         } else {
15809:             $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);
15810:         }
15811:     } else {
15812:         $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);
15813:     }
15814:     return ($url,$error);
15815: }
15816: 
15817: sub modify_lti {
15818:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15819:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15820:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
15821:     my (%posslti,%posslticrs,%posscrstype);
15822:     my @courseroles = ('cc','in','ta','ep','st');
15823:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
15824:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
15825:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
15826:     my %coursetypetitles = &Apache::lonlocal::texthash (
15827:                                official   => 'Official',
15828:                                unofficial => 'Unofficial',
15829:                                community  => 'Community',
15830:                                textbook   => 'Textbook',
15831:                                placement  => 'Placement Test',
15832:                                lti        => 'LTI Provider',
15833:     );
15834:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15835:     my %lt = &lti_names();
15836:     map { $posslti{$_} = 1; } @ltiroles;
15837:     map { $posslticrs{$_} = 1; } @lticourseroles;
15838:     map { $posscrstype{$_} = 1; } @coursetypes;
15839: 
15840:     my %menutitles = &ltimenu_titles();
15841: 
15842:     my (%currltisec,%secchanges,%newltisec,%newltienc,%keyset,%newkeyset);
15843:     $newltisec{'private'}{'keys'} = [];
15844:     $newltisec{'encrypt'} = {};
15845:     $newltisec{'rules'} = {};
15846:     $newltisec{'linkprot'} = {};
15847:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
15848:         %currltisec = %{$domconfig{'ltisec'}};
15849:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15850:             foreach my $id (keys(%{$currltisec{'linkprot'}})) {
15851:                 unless ($id =~ /^\d+$/) {
15852:                     delete($currltisec{'linkprot'}{$id});
15853:                 }
15854:             }
15855:         }
15856:         if (ref($currltisec{'private'}) eq 'HASH') {
15857:             if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
15858:                 $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
15859:                 map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
15860:             }
15861:         }
15862:     }
15863:     foreach my $item ('crs','dom','consumers') {
15864:         my $formelement;
15865:         if ($item eq 'consumers') { 
15866:             $formelement = 'form.ltisec_'.$item;
15867:         } else {
15868:             $formelement = 'form.ltisec_'.$item.'linkprot';
15869:         }
15870:         if ($env{$formelement}) {
15871:             $newltisec{'encrypt'}{$item} = 1;
15872:             if (ref($currltisec{'encrypt'}) eq 'HASH') {
15873:                 unless ($currltisec{'encrypt'}{$item}) {
15874:                     $secchanges{'encrypt'} = 1;
15875:                 }
15876:             } else {
15877:                 $secchanges{'encrypt'} = 1;
15878:             }
15879:         } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
15880:             if ($currltisec{'encrypt'}{$item}) {
15881:                 $secchanges{'encrypt'} = 1;
15882:             }
15883:         }
15884:     }
15885:     unless (exists($currltisec{'rules'})) {
15886:         $currltisec{'rules'} = {};
15887:     }
15888:     &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
15889: 
15890:     my @ids=&Apache::lonnet::current_machine_ids();
15891:     my %servers = &Apache::lonnet::get_servers($dom,'library');
15892:    
15893:     foreach my $hostid (keys(%servers)) {
15894:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
15895:             my $newkey;
15896:             my $keyitem = 'form.ltisec_privkey_'.$hostid;
15897:             if (exists($env{$keyitem})) {
15898:                 $env{$keyitem} =~ s/(`)/'/g;
15899:                 if ($keyset{$hostid}) {
15900:                     if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
15901:                         if ($env{$keyitem} ne '') {
15902:                             $secchanges{'private'} = 1;
15903:                             $newkeyset{$hostid} = $env{$keyitem};
15904:                         }
15905:                     }
15906:                 } elsif ($env{$keyitem} ne '') {
15907:                     unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) { 
15908:                         push(@{$newltisec{'private'}{'keys'}},$hostid);
15909:                     }
15910:                     $secchanges{'private'} = 1;
15911:                     $newkeyset{$hostid} = $env{$keyitem};
15912:                 }
15913:             }
15914:         }
15915:     }
15916: 
15917:     my (%linkprotchg,$linkprotoutput,$is_home);
15918:     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
15919:                                                            \%linkprotchg,'domain');
15920:     my $home = &Apache::lonnet::domain($dom,'primary');
15921:     unless (($home eq 'no_host') || ($home eq '')) {
15922:         my @ids=&Apache::lonnet::current_machine_ids();
15923:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
15924:     }
15925: 
15926:     if (keys(%linkprotchg)) {
15927:         $secchanges{'linkprot'} = 1;
15928:         my %oldlinkprot;
15929:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15930:             %oldlinkprot = %{$currltisec{'linkprot'}};
15931:         }
15932:         foreach my $id (keys(%linkprotchg)) {
15933:             if (ref($linkprotchg{$id}) eq 'HASH') {
15934:                 foreach my $inner (keys(%{$linkprotchg{$id}})) {
15935:                     if (($inner eq 'secret') || ($inner eq 'key')) {
15936:                         if ($is_home) {
15937:                             $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
15938:                         }
15939:                     }
15940:                 }
15941:             } else {
15942:                 $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
15943:             }
15944:         }
15945:         $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
15946:         if (keys(%linkprotchg)) {
15947:             %{$newltisec{'linkprot'}} = %linkprotchg;
15948:         }
15949:     }
15950:     if (ref($currltisec{'linkprot'}) eq 'HASH') {
15951:         foreach my $id (%{$currltisec{'linkprot'}}) {
15952:             next if ($id !~ /^\d+$/);
15953:             unless (exists($linkprotchg{$id})) {
15954:                 if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
15955:                     foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
15956:                         if (($inner eq 'secret') || ($inner eq 'key')) {
15957:                             if ($is_home) {
15958:                                 $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
15959:                             }
15960:                         } else {
15961:                             $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
15962:                         }
15963:                     }
15964:                 } else {
15965:                     $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
15966:                 }
15967:             }
15968:         }
15969:     }
15970:     if ($proterror) {
15971:         $errors .= '<li>'.$proterror.'</li>';
15972:     }
15973:     my (@items,%deletions,%itemids);
15974:     if ($env{'form.lti_add'}) {
15975:         my $consumer = $env{'form.lti_consumer_add'};
15976:         $consumer =~ s/(`)/'/g;
15977:         ($newid,my $error) = &get_lti_id($dom,$consumer);
15978:         if ($newid) {
15979:             $itemids{'add'} = $newid;
15980:             push(@items,'add');
15981:             $changes{$newid} = 1;
15982:         } else {
15983:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
15984:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15985:         }
15986:     }
15987:     if (ref($domconfig{$action}) eq 'HASH') {
15988:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
15989:         if (@todelete) {
15990:             map { $deletions{$_} = 1; } @todelete;
15991:         }
15992:         my $maxnum = $env{'form.lti_maxnum'};
15993:         for (my $i=0; $i<$maxnum; $i++) {
15994:             my $itemid = $env{'form.lti_id_'.$i};
15995:             $itemid =~ s/\D+//g;
15996:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15997:                 if ($deletions{$itemid}) {
15998:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
15999:                 } else {
16000:                     push(@items,$i);
16001:                     $itemids{$i} = $itemid;
16002:                 }
16003:             }
16004:         }
16005:     }
16006:     foreach my $idx (@items) {
16007:         my $itemid = $itemids{$idx};
16008:         next unless ($itemid);
16009:         my $position = $env{'form.lti_pos_'.$itemid};
16010:         $position =~ s/\D+//g;
16011:         if ($position ne '') {
16012:             $allpos[$position] = $itemid;
16013:         }
16014:         foreach my $item ('consumer','key','secret','lifetime','requser','crsinc') {
16015:             my $formitem = 'form.lti_'.$item.'_'.$idx;
16016:             $env{$formitem} =~ s/(`)/'/g;
16017:             if ($item eq 'lifetime') {
16018:                 $env{$formitem} =~ s/[^\d.]//g;
16019:             }
16020:             if ($env{$formitem} ne '') {
16021:                 if (($item eq 'key') || ($item eq 'secret')) {
16022:                     $encconfig{$itemid}{$item} = $env{$formitem};
16023:                 } else {
16024:                     $confhash{$itemid}{$item} = $env{$formitem};
16025:                     unless (($idx eq 'add') || ($changes{$itemid})) {
16026:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
16027:                             $changes{$itemid} = 1;
16028:                         }
16029:                     }
16030:                 }
16031:             }
16032:         }
16033:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
16034:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
16035:         }
16036:         if ($confhash{$itemid}{'requser'}) {
16037:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
16038:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid';
16039:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
16040:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
16041:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
16042:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
16043:                 $mapuser =~ s/(`)/'/g;
16044:                 $mapuser =~ s/^\s+|\s+$//g;
16045:                 $confhash{$itemid}{'mapuser'} = $mapuser;
16046:             }
16047:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
16048:             my @makeuser;
16049:             foreach my $ltirole (sort(@possmakeuser)) {
16050:                 if ($posslti{$ltirole}) {
16051:                     push(@makeuser,$ltirole);
16052:                 }
16053:             }
16054:             $confhash{$itemid}{'makeuser'} = \@makeuser;
16055:             if (@makeuser) {
16056:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
16057:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
16058:                     $confhash{$itemid}{'lcauth'} = $lcauth;
16059:                     if ($lcauth ne 'internal') {
16060:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
16061:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
16062:                         $lcauthparm =~ s/`//g;
16063:                         if ($lcauthparm ne '') {
16064:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
16065:                         }
16066:                     }
16067:                 } else {
16068:                     $confhash{$itemid}{'lcauth'} = 'lti';
16069:                 }
16070:             }
16071:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
16072:             if (@possinstdata) {
16073:                 foreach my $field (@possinstdata) {
16074:                     if (exists($fieldtitles{$field})) {
16075:                         push(@{$confhash{$itemid}{'instdata'}});
16076:                     }
16077:                 }
16078:             }
16079:             if ($env{'form.lti_callback_'.$idx}) {
16080:                 if ($env{'form.lti_callbackparam_'.$idx}) {
16081:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
16082:                     $callback =~ s/^\s+|\s+$//g;
16083:                     $confhash{$itemid}{'callback'} = $callback;
16084:                 }
16085:             }
16086:             foreach my $field ('topmenu','inlinemenu') {
16087:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
16088:                     $confhash{$itemid}{$field} = 1;
16089:                 }
16090:             }
16091:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
16092:                 $confhash{$itemid}{lcmenu} = [];
16093:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
16094:                 foreach my $field (@possmenu) {
16095:                     if (exists($menutitles{$field})) {
16096:                         if ($field eq 'grades') {
16097:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
16098:                         }
16099:                         push(@{$confhash{$itemid}{lcmenu}},$field);
16100:                     }
16101:                 }
16102:             }
16103:             if ($confhash{$itemid}{'crsinc'}) {
16104:                 if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
16105:                     ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
16106:                     $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
16107:                 } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
16108:                     my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
16109:                     $mapcrs =~ s/(`)/'/g;
16110:                     $mapcrs =~ s/^\s+|\s+$//g;
16111:                     $confhash{$itemid}{'mapcrs'} = $mapcrs;
16112:                 }
16113:                 my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
16114:                 my @crstypes;
16115:                 foreach my $type (sort(@posstypes)) {
16116:                     if ($posscrstype{$type}) {
16117:                         push(@crstypes,$type);
16118:                     }
16119:                 }
16120:                 $confhash{$itemid}{'mapcrstype'} = \@crstypes;
16121:                 if ($env{'form.lti_storecrs_'.$idx}) {
16122:                     $confhash{$itemid}{'storecrs'} = 1;
16123:                 }       
16124:                 if ($env{'form.lti_makecrs_'.$idx}) {
16125:                     $confhash{$itemid}{'makecrs'} = 1;
16126:                 }
16127:                 foreach my $ltirole (@lticourseroles) {
16128:                     my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
16129:                     if (grep(/^\Q$possrole\E$/,@courseroles)) {
16130:                         $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
16131:                     }
16132:                 }
16133:                 my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
16134:                 my @selfenroll;
16135:                 foreach my $type (sort(@possenroll)) {
16136:                     if ($posslticrs{$type}) {
16137:                         push(@selfenroll,$type);
16138:                     }
16139:                 }
16140:                 $confhash{$itemid}{'selfenroll'} = \@selfenroll;
16141:                 if ($env{'form.lti_crssec_'.$idx}) {
16142:                     if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
16143:                         $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
16144:                     } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
16145:                         my $section = $env{'form.lti_customsection_'.$idx};
16146:                         $section =~ s/(`)/'/g;
16147:                         $section =~ s/^\s+|\s+$//g;
16148:                         if ($section ne '') {
16149:                             $confhash{$itemid}{'section'} = $section;
16150:                         }
16151:                     }
16152:                 }
16153:                 foreach my $field ('passback','roster') {
16154:                     if ($env{'form.lti_'.$field.'_'.$idx}) {
16155:                         $confhash{$itemid}{$field} = 1;
16156:                     }
16157:                 }
16158:                 if ($env{'form.lti_passback_'.$idx}) {
16159:                     if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
16160:                         $confhash{$itemid}{'passbackformat'} = '1.0';
16161:                     } else {
16162:                         $confhash{$itemid}{'passbackformat'} = '1.1';
16163:                     }
16164:                 }
16165:             }
16166:             unless (($idx eq 'add') || ($changes{$itemid})) {
16167:                 if ($confhash{$itemid}{'crsinc'}) {
16168:                     foreach my $field ('mapcrs','storecrs','makecrs','section','passback','roster') {
16169:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16170:                             $changes{$itemid} = 1;
16171:                         }
16172:                     }
16173:                     unless ($changes{$itemid}) {
16174:                         if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
16175:                             if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
16176:                                 $changes{$itemid} = 1;
16177:                             }
16178:                         }
16179:                     }
16180:                     foreach my $field ('mapcrstype','selfenroll') {
16181:                         unless ($changes{$itemid}) {
16182:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16183:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16184:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16185:                                                                                    $confhash{$itemid}{$field});
16186:                                     if (@diffs) {
16187:                                         $changes{$itemid} = 1;
16188:                                     }
16189:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16190:                                     $changes{$itemid} = 1;
16191:                                 }
16192:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16193:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16194:                                     $changes{$itemid} = 1;
16195:                                 }
16196:                             }
16197:                         }
16198:                     }
16199:                     unless ($changes{$itemid}) {
16200:                         if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
16201:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16202:                                 foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
16203:                                     if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
16204:                                         $confhash{$itemid}{'maproles'}{$ltirole}) {
16205:                                         $changes{$itemid} = 1;
16206:                                         last;
16207:                                     }
16208:                                 }
16209:                                 unless ($changes{$itemid}) {
16210:                                     foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
16211:                                         if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
16212:                                             $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
16213:                                             $changes{$itemid} = 1;
16214:                                             last;
16215:                                         }
16216:                                     }
16217:                                 }
16218:                             } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
16219:                                 $changes{$itemid} = 1;
16220:                             }
16221:                         } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16222:                             unless ($changes{$itemid}) {
16223:                                 if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
16224:                                     $changes{$itemid} = 1;
16225:                                 }
16226:                             }
16227:                         }
16228:                     }
16229:                 }
16230:                 unless ($changes{$itemid}) {
16231:                     foreach my $field ('mapuser','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
16232:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16233:                             $changes{$itemid} = 1;
16234:                         }
16235:                     }
16236:                     unless ($changes{$itemid}) {
16237:                         foreach my $field ('makeuser','lcmenu') {
16238:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16239:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16240:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16241:                                                                                    $confhash{$itemid}{$field});
16242:                                     if (@diffs) {
16243:                                         $changes{$itemid} = 1;
16244:                                     }
16245:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16246:                                     $changes{$itemid} = 1;
16247:                                 }
16248:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16249:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16250:                                     $changes{$itemid} = 1;
16251:                                 }
16252:                             }
16253:                         }
16254:                     }
16255:                 }
16256:             }
16257:         }
16258:     }
16259:     if (@allpos > 0) {
16260:         my $idx = 0;
16261:         foreach my $itemid (@allpos) {
16262:             if ($itemid ne '') {
16263:                 $confhash{$itemid}{'order'} = $idx;
16264:                 if (ref($domconfig{$action}) eq 'HASH') {
16265:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16266:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
16267:                             $changes{$itemid} = 1;
16268:                         }
16269:                     }
16270:                 }
16271:                 $idx ++;
16272:             }
16273:         }
16274:     }
16275:     my %ltihash = (
16276:                       $action => { %confhash }
16277:                   );
16278:     my %ltienchash = (
16279:                          $action => { %encconfig }
16280:                      );
16281:     if (keys(%secchanges)) {
16282:         $ltihash{'ltisec'} = \%newltisec;
16283:         if ($secchanges{'linkprot'}) {
16284:             if ($is_home) {
16285:                 $ltienchash{'linkprot'} = \%newltienc;
16286:             }
16287:         }
16288:     }
16289:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
16290:     if ($putresult eq 'ok') {
16291:         my %keystore;
16292:         if (keys(%secchanges)) {
16293:             if ($secchanges{'private'}) {
16294:                 my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
16295:                 foreach my $hostid (keys(%newkeyset)) {
16296:                     my $storehash = {
16297:                                        key => $newkeyset{$hostid},
16298:                                        who => $env{'user.name'}.':'.$env{'user.domain'},
16299:                                     };
16300:                     $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
16301:                                                                     $dom,$hostid);
16302:                 }
16303:             }
16304:             if (ref($lastactref) eq 'HASH') {
16305:                 if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
16306:                     $lastactref->{'domdefaults'} = 1;
16307:                 }
16308:             }
16309:         }
16310:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
16311:         if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
16312:             return &mt('No changes made.');
16313:         }
16314:         $resulttext = &mt('Changes made:').'<ul>';
16315:         if (keys(%secchanges) > 0) {
16316:             foreach my $item (keys(%secchanges)) {
16317:                 if ($item eq 'encrypt') {
16318:                     my %encrypted = (
16319:                               crs  => {
16320:                                         on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
16321:                                         off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
16322:                                       },
16323:                               dom => {
16324:                                        on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
16325:                                        off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
16326:                                      },
16327:                               consumers => {
16328:                                              on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
16329:                                              off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
16330:                                            },
16331:                             );
16332:                     foreach my $type ('crs','dom','consumers') {
16333:                         my $shown = $encrypted{$type}{'off'};
16334:                         if (ref($newltisec{$item}) eq 'HASH') {
16335:                             if ($newltisec{$item}{$type}) {
16336:                                 $shown = $encrypted{$type}{'on'}; 
16337:                             }
16338:                         }
16339:                         $resulttext .= '<li>'.$shown.'</li>';
16340:                     } 
16341:                 } elsif ($item eq 'rules') {
16342:                      my %titles = &Apache::lonlocal::texthash(
16343:                                       min   => 'Minimum password length',
16344:                                       max   => 'Maximum password length',
16345:                                       chars => 'Required characters',
16346:                      );
16347:                      foreach my $rule ('min','max') {
16348:                          if ($newltisec{rules}{$rule} eq '') {
16349:                              if ($rule eq 'min') {
16350:                                  $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
16351:                                                 ' '.&mt('Default of [_1] will be used',
16352:                                                             $Apache::lonnet::passwdmin).'</li>';
16353:                              } else {
16354:                                  $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
16355:                              }
16356:                          } else {
16357:                              $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
16358:                          }
16359:                      }
16360:                      if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
16361:                          if (@{$newltisec{'rules'}{'chars'}} > 0) {
16362:                              my %rulenames = &Apache::lonlocal::texthash(
16363:                                                  uc => 'At least one upper case letter',
16364:                                                  lc => 'At least one lower case letter',
16365:                                                  num => 'At least one number',
16366:                                                  spec => 'At least one non-alphanumeric',
16367:                                              );
16368:                              my $needed = '<ul><li>'.
16369:                                           join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
16370:                                           '</li></ul>';
16371:                              $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
16372:                          } else {
16373:                              $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16374:                          }
16375:                      } else {
16376:                          $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16377:                      }
16378:                 } elsif ($item eq 'private') {
16379:                     if (keys(%newkeyset)) {
16380:                         foreach my $hostid (sort(keys(%newkeyset))) {
16381:                             if ($keystore{$hostid} eq 'ok') {
16382:                                 $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
16383:                             }
16384:                         }
16385:                     }
16386:                 } elsif ($item eq 'linkprot') {
16387:                     $resulttext .= $linkprotoutput;
16388:                 }
16389:             }
16390:         }
16391:         if (keys(%changes) > 0) {
16392:             my $cachetime = 24*60*60;
16393:             my %ltiall = %confhash;
16394:             foreach my $id (keys(%ltiall)) {
16395:                 if (ref($encconfig{$id}) eq 'HASH') {
16396:                     foreach my $item ('key','secret') {
16397:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
16398:                     }
16399:                 }
16400:             }
16401:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
16402:             if (ref($lastactref) eq 'HASH') {
16403:                 $lastactref->{'lti'} = 1;
16404:             }
16405:             my %bynum;
16406:             foreach my $itemid (sort(keys(%changes))) {
16407:                 my $position = $confhash{$itemid}{'order'};
16408:                 $bynum{$position} = $itemid;
16409:             }
16410:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
16411:                 my $itemid = $bynum{$pos};
16412:                 if (ref($confhash{$itemid}) ne 'HASH') {
16413:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
16414:                 } else {
16415:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b><ul>';
16416:                     my $position = $pos + 1;
16417:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
16418:                     foreach my $item ('version','lifetime') {
16419:                         if ($confhash{$itemid}{$item} ne '') {
16420:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
16421:                         }
16422:                     }
16423:                     if ($encconfig{$itemid}{'key'} ne '') {
16424:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
16425:                     }
16426:                     if ($encconfig{$itemid}{'secret'} ne '') {
16427:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
16428:                         my $num = length($encconfig{$itemid}{'secret'});
16429:                         $resulttext .= ('*'x$num).'</li>';
16430:                     }
16431:                     if ($confhash{$itemid}{'requser'}) {
16432:                         if ($confhash{$itemid}{'callback'}) {
16433:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
16434:                         } else {
16435:                             $resulttext .= '<li>'.&mt('Callback to logout LON-CAPA on log out from Consumer').'</li>';
16436:                         }
16437:                         if ($confhash{$itemid}{'mapuser'}) {
16438:                             my $shownmapuser;
16439:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
16440:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
16441:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
16442:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
16443:                             } else {
16444:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
16445:                             }
16446:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
16447:                         }
16448:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
16449:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
16450:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
16451:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
16452:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
16453:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
16454:                                 } else {
16455:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
16456:                                                        $confhash{$itemid}{'lcauth'});
16457:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
16458:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
16459:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
16460:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
16461:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
16462:                                         }
16463:                                     } else {
16464:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
16465:                                     }
16466:                                 }
16467:                                 $resulttext .= '</li>';
16468:                             } else {
16469:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
16470:                             }
16471:                         }
16472:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
16473:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
16474:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
16475:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
16476:                             } else {
16477:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
16478:                             }
16479:                         }
16480:                         foreach my $item ('topmenu','inlinemenu') {
16481:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16482:                             if ($confhash{$itemid}{$item}) {
16483:                                 $resulttext .= &mt('Yes');
16484:                             } else {
16485:                                 $resulttext .= &mt('No');
16486:                             }
16487:                             $resulttext .= '</li>';
16488:                         }
16489:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16490:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16491:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
16492:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
16493:                             } else {
16494:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
16495:                             }
16496:                         }
16497:                         if ($confhash{$itemid}{'crsinc'}) {
16498:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16499:                                 my $rolemaps;
16500:                                 foreach my $role (@ltiroles) {
16501:                                     if ($confhash{$itemid}{'maproles'}{$role}) {
16502:                                         $rolemaps .= ('&nbsp;'x2).$role.'='.
16503:                                                      &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
16504:                                                                                 'Course').',';
16505:                                     }
16506:                                 }
16507:                                 if ($rolemaps) {
16508:                                     $rolemaps =~ s/,$//;
16509:                                     $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
16510:                                 }
16511:                             }
16512:                             if ($confhash{$itemid}{'mapcrs'}) {
16513:                                 $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
16514:                             }
16515:                             if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
16516:                                 if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
16517:                                     $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
16518:                                                    join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
16519:                                                    '</li>';
16520:                                 } else {
16521:                                     $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
16522:                                 }
16523:                             }
16524:                             if ($confhash{$itemid}{'storecrs'}) {
16525:                                 $resulttext .= '<li>'.&mt('Store mapping of course identifier to LON-CAPA CourseID').': '.$confhash{$itemid}{'storecrs'}.'</li>';
16526:                             }
16527:                             if ($confhash{$itemid}{'makecrs'}) {
16528:                                 $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
16529:                             } else {
16530:                                 $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
16531:                             }
16532:                             if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
16533:                                 if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
16534:                                     $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
16535:                                                               join(', ',@{$confhash{$itemid}{'selfenroll'}})).
16536:                                                    '</li>';
16537:                                 } else {
16538:                                     $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
16539:                                 }
16540:                             }
16541:                             if ($confhash{$itemid}{'section'}) {
16542:                                 if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
16543:                                     $resulttext .= '<li>'.&mt('User section from standard field:').
16544:                                                          ' (course_section_sourcedid)'.'</li>';  
16545:                                 } else {
16546:                                     $resulttext .= '<li>'.&mt('User section from:').' '.
16547:                                                           $confhash{$itemid}{'section'}.'</li>';
16548:                                 }
16549:                             } else {
16550:                                 $resulttext .= '<li>'.&mt('No section assignment').'</li>';
16551:                             }
16552:                             foreach my $item ('passback','roster','topmenu','inlinemenu') {
16553:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16554:                                 if ($confhash{$itemid}{$item}) {
16555:                                     $resulttext .= &mt('Yes');
16556:                                     if ($item eq 'passback') {
16557:                                         if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
16558:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
16559:                                         } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
16560:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
16561:                                         }
16562:                                     }
16563:                                 } else {
16564:                                     $resulttext .= &mt('No');
16565:                                 }
16566:                                 $resulttext .= '</li>';
16567:                             }
16568:                             if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16569:                                 if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16570:                                     $resulttext .= '<li>'.&mt('Menu items:').' '.
16571:                                                    join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
16572:                                 } else {
16573:                                     $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
16574:                                 }
16575:                             }
16576:                         }
16577:                     }
16578:                     $resulttext .= '</ul></li>';
16579:                 }
16580:             }
16581:         }
16582:         $resulttext .= '</ul>';
16583:     } else {
16584:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
16585:     }
16586:     if ($errors) {
16587:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
16588:                        $errors.'</ul>';
16589:     }
16590:     return $resulttext;
16591: }
16592: 
16593: sub get_lti_id {
16594:     my ($domain,$consumer) = @_;
16595:     # get lock on lti db
16596:     my $lockhash = {
16597:                       lock => $env{'user.name'}.
16598:                               ':'.$env{'user.domain'},
16599:                    };
16600:     my $tries = 0;
16601:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16602:     my ($id,$error);
16603: 
16604:     while (($gotlock ne 'ok') && ($tries<10)) {
16605:         $tries ++;
16606:         sleep (0.1);
16607:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16608:     }
16609:     if ($gotlock eq 'ok') {
16610:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
16611:         if ($currids{'lock'}) {
16612:             delete($currids{'lock'});
16613:             if (keys(%currids)) {
16614:                 my @curr = sort { $a <=> $b } keys(%currids);
16615:                 if ($curr[-1] =~ /^\d+$/) {
16616:                     $id = 1 + $curr[-1];
16617:                 }
16618:             } else {
16619:                 $id = 1;
16620:             }
16621:             if ($id) {
16622:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
16623:                     $error = 'nostore';
16624:                 }
16625:             } else {
16626:                 $error = 'nonumber';
16627:             }
16628:         }
16629:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
16630:     } else {
16631:         $error = 'nolock';
16632:     }
16633:     return ($id,$error);
16634: }
16635: 
16636: sub modify_autoenroll {
16637:     my ($dom,$lastactref,%domconfig) = @_;
16638:     my ($resulttext,%changes);
16639:     my %currautoenroll;
16640:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
16641:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
16642:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
16643:         }
16644:     }
16645:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
16646:     my %title = ( run => 'Auto-enrollment active',
16647:                   sender => 'Sender for notification messages',
16648:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
16649:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
16650:     my @offon = ('off','on');
16651:     my $sender_uname = $env{'form.sender_uname'};
16652:     my $sender_domain = $env{'form.sender_domain'};
16653:     if ($sender_domain eq '') {
16654:         $sender_uname = '';
16655:     } elsif ($sender_uname eq '') {
16656:         $sender_domain = '';
16657:     }
16658:     my $coowners = $env{'form.autoassign_coowners'};
16659:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
16660:     $autofailsafe =~ s{^\s+|\s+$}{}g;
16661:     if ($autofailsafe =~ /\D/) {
16662:         undef($autofailsafe);
16663:     }
16664:     my $failsafe = $env{'form.autoenroll_failsafe'};
16665:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
16666:         $failsafe = 'off';
16667:         undef($autofailsafe);
16668:     }
16669:     my %autoenrollhash =  (
16670:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
16671:                                        'sender_uname' => $sender_uname,
16672:                                        'sender_domain' => $sender_domain,
16673:                                        'co-owners' => $coowners,
16674:                                        'autofailsafe' => $autofailsafe,
16675:                                        'failsafe' => $failsafe,
16676:                                 }
16677:                      );
16678:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
16679:                                              $dom);
16680:     if ($putresult eq 'ok') {
16681:         if (exists($currautoenroll{'run'})) {
16682:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
16683:                  $changes{'run'} = 1;
16684:              }
16685:         } elsif ($autorun) {
16686:             if ($env{'form.autoenroll_run'} ne '1') {
16687:                  $changes{'run'} = 1;
16688:             }
16689:         }
16690:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
16691:             $changes{'sender'} = 1;
16692:         }
16693:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
16694:             $changes{'sender'} = 1;
16695:         }
16696:         if ($currautoenroll{'co-owners'} ne '') {
16697:             if ($currautoenroll{'co-owners'} ne $coowners) {
16698:                 $changes{'coowners'} = 1;
16699:             }
16700:         } elsif ($coowners) {
16701:             $changes{'coowners'} = 1;
16702:         }
16703:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
16704:             $changes{'autofailsafe'} = 1;
16705:         }
16706:         if ($currautoenroll{'failsafe'} ne $failsafe) {
16707:             $changes{'failsafe'} = 1;
16708:         }
16709:         if (keys(%changes) > 0) {
16710:             $resulttext = &mt('Changes made:').'<ul>';
16711:             if ($changes{'run'}) {
16712:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
16713:             }
16714:             if ($changes{'sender'}) {
16715:                 if ($sender_uname eq '' || $sender_domain eq '') {
16716:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
16717:                 } else {
16718:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
16719:                 }
16720:             }
16721:             if ($changes{'coowners'}) {
16722:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
16723:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16724:                 if (ref($lastactref) eq 'HASH') {
16725:                     $lastactref->{'domainconfig'} = 1;
16726:                 }
16727:             }
16728:             if ($changes{'autofailsafe'}) {
16729:                 if ($autofailsafe ne '') {
16730:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
16731:                 } else {
16732:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16733:                 }
16734:             }
16735:             if ($changes{'failsafe'}) {
16736:                 if ($failsafe eq 'off') {
16737:                     unless ($changes{'autofailsafe'}) {
16738:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16739:                     }
16740:                 } elsif ($failsafe eq 'zero') {
16741:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
16742:                 } else {
16743:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
16744:                 }
16745:             }
16746:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
16747:                 &Apache::lonnet::get_domain_defaults($dom,1);
16748:                 if (ref($lastactref) eq 'HASH') {
16749:                     $lastactref->{'domdefaults'} = 1;
16750:                 }
16751:             }
16752:             $resulttext .= '</ul>';
16753:         } else {
16754:             $resulttext = &mt('No changes made to auto-enrollment settings');
16755:         }
16756:     } else {
16757:         $resulttext = '<span class="LC_error">'.
16758: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16759:     }
16760:     return $resulttext;
16761: }
16762: 
16763: sub modify_autoupdate {
16764:     my ($dom,%domconfig) = @_;
16765:     my ($resulttext,%currautoupdate,%fields,%changes);
16766:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
16767:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
16768:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
16769:         }
16770:     }
16771:     my @offon = ('off','on');
16772:     my %title = &Apache::lonlocal::texthash (
16773:                     run        => 'Auto-update:',
16774:                     classlists => 'Updates to user information in classlists?',
16775:                     unexpired  => 'Skip updates for users without active or future roles?',
16776:                     lastactive => 'Skip updates for inactive users?',
16777:                 );
16778:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16779:     my %fieldtitles = &Apache::lonlocal::texthash (
16780:                         id => 'Student/Employee ID',
16781:                         permanentemail => 'E-mail address',
16782:                         lastname => 'Last Name',
16783:                         firstname => 'First Name',
16784:                         middlename => 'Middle Name',
16785:                         generation => 'Generation',
16786:                       );
16787:     $othertitle = &mt('All users');
16788:     if (keys(%{$usertypes}) >  0) {
16789:         $othertitle = &mt('Other users');
16790:     }
16791:     foreach my $key (keys(%env)) {
16792:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
16793:             my ($usertype,$item) = ($1,$2);
16794:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
16795:                 if ($usertype eq 'default') {   
16796:                     push(@{$fields{$1}},$2);
16797:                 } elsif (ref($types) eq 'ARRAY') {
16798:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
16799:                         push(@{$fields{$1}},$2);
16800:                     }
16801:                 }
16802:             }
16803:         }
16804:     }
16805:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
16806:     @lockablenames = sort(@lockablenames);
16807:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
16808:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16809:         if (@changed) {
16810:             $changes{'lockablenames'} = 1;
16811:         }
16812:     } else {
16813:         if (@lockablenames) {
16814:             $changes{'lockablenames'} = 1;
16815:         }
16816:     }
16817:     my %updatehash = (
16818:                       autoupdate => { run => $env{'form.autoupdate_run'},
16819:                                       classlists => $env{'form.classlists'},
16820:                                       unexpired  => $env{'form.unexpired'},
16821:                                       fields => {%fields},
16822:                                       lockablenames => \@lockablenames,
16823:                                     }
16824:                      );
16825:     my $lastactivedays;
16826:     if ($env{'form.lastactive'}) {
16827:         $lastactivedays = $env{'form.lastactivedays'};
16828:         $lastactivedays =~ s/^\s+|\s+$//g;
16829:         unless ($lastactivedays =~ /^\d+$/) {
16830:             undef($lastactivedays);
16831:             $env{'form.lastactive'} = 0;
16832:         }
16833:     }
16834:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
16835:     foreach my $key (keys(%currautoupdate)) {
16836:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
16837:             if (exists($updatehash{autoupdate}{$key})) {
16838:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
16839:                     $changes{$key} = 1;
16840:                 }
16841:             }
16842:         } elsif ($key eq 'fields') {
16843:             if (ref($currautoupdate{$key}) eq 'HASH') {
16844:                 foreach my $item (@{$types},'default') {
16845:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
16846:                         my $change = 0;
16847:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
16848:                             if (!exists($fields{$item})) {
16849:                                 $change = 1;
16850:                                 last;
16851:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
16852:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
16853:                                     $change = 1;
16854:                                     last;
16855:                                 }
16856:                             }
16857:                         }
16858:                         if ($change) {
16859:                             push(@{$changes{$key}},$item);
16860:                         }
16861:                     } 
16862:                 }
16863:             }
16864:         } elsif ($key eq 'lockablenames') {
16865:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
16866:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16867:                 if (@changed) {
16868:                     $changes{'lockablenames'} = 1;
16869:                 }
16870:             } else {
16871:                 if (@lockablenames) {
16872:                     $changes{'lockablenames'} = 1;
16873:                 }
16874:             }
16875:         }
16876:     }
16877:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
16878:         if (@lockablenames) {
16879:             $changes{'lockablenames'} = 1;
16880:         }
16881:     }
16882:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
16883:         if ($updatehash{'autoupdate'}{'unexpired'}) {
16884:             $changes{'unexpired'} = 1;
16885:         }
16886:     }
16887:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
16888:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
16889:             $changes{'lastactive'} = 1;
16890:         }
16891:     }
16892:     foreach my $item (@{$types},'default') {
16893:         if (defined($fields{$item})) {
16894:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
16895:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
16896:                     my $change = 0;
16897:                     if (ref($fields{$item}) eq 'ARRAY') {
16898:                         foreach my $type (@{$fields{$item}}) {
16899:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
16900:                                 $change = 1;
16901:                                 last;
16902:                             }
16903:                         }
16904:                     }
16905:                     if ($change) {
16906:                         push(@{$changes{'fields'}},$item);
16907:                     }
16908:                 } else {
16909:                     push(@{$changes{'fields'}},$item);
16910:                 }
16911:             } else {
16912:                 push(@{$changes{'fields'}},$item);
16913:             }
16914:         }
16915:     }
16916:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
16917:                                              $dom);
16918:     if ($putresult eq 'ok') {
16919:         if (keys(%changes) > 0) {
16920:             $resulttext = &mt('Changes made:').'<ul>';
16921:             foreach my $key (sort(keys(%changes))) {
16922:                 if ($key eq 'lockablenames') {
16923:                     $resulttext .= '<li>';
16924:                     if (@lockablenames) {
16925:                         $usertypes->{'default'} = $othertitle;
16926:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
16927:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
16928:                     } else {
16929:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
16930:                     }
16931:                     $resulttext .= '</li>';
16932:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
16933:                     foreach my $item (@{$changes{$key}}) {
16934:                         my @newvalues;
16935:                         foreach my $type (@{$fields{$item}}) {
16936:                             push(@newvalues,$fieldtitles{$type});
16937:                         }
16938:                         my $newvaluestr;
16939:                         if (@newvalues > 0) {
16940:                             $newvaluestr = join(', ',@newvalues);
16941:                         } else {
16942:                             $newvaluestr = &mt('none');
16943:                         }
16944:                         if ($item eq 'default') {
16945:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
16946:                         } else {
16947:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
16948:                         }
16949:                     }
16950:                 } else {
16951:                     my $newvalue;
16952:                     if ($key eq 'run') {
16953:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
16954:                     } elsif ($key eq 'lastactive') {
16955:                         $newvalue = $offon[$env{'form.lastactive'}];
16956:                         unless ($lastactivedays eq '') {
16957:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
16958:                         }
16959:                     } else {
16960:                         $newvalue = $offon[$env{'form.'.$key}];
16961:                     }
16962:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
16963:                 }
16964:             }
16965:             $resulttext .= '</ul>';
16966:         } else {
16967:             $resulttext = &mt('No changes made to autoupdates');
16968:         }
16969:     } else {
16970:         $resulttext = '<span class="LC_error">'.
16971: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16972:     }
16973:     return $resulttext;
16974: }
16975: 
16976: sub modify_autocreate {
16977:     my ($dom,%domconfig) = @_;
16978:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
16979:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
16980:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
16981:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
16982:         }
16983:     }
16984:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
16985:                  req => 'Auto-creation of validated requests for official courses',
16986:                  xmldc => 'Identity of course creator of courses from XML files',
16987:                );
16988:     my @types = ('xml','req');
16989:     foreach my $item (@types) {
16990:         $newvals{$item} = $env{'form.autocreate_'.$item};
16991:         $newvals{$item} =~ s/\D//g;
16992:         $newvals{$item} = 0 if ($newvals{$item} eq '');
16993:     }
16994:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
16995:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
16996:     unless (exists($domcoords{$newvals{'xmldc'}})) {
16997:         $newvals{'xmldc'} = '';
16998:     } 
16999:     %autocreatehash =  (
17000:                         autocreate => { xml => $newvals{'xml'},
17001:                                         req => $newvals{'req'},
17002:                                       }
17003:                        );
17004:     if ($newvals{'xmldc'} ne '') {
17005:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
17006:     }
17007:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
17008:                                              $dom);
17009:     if ($putresult eq 'ok') {
17010:         my @items = @types;
17011:         if ($newvals{'xml'}) {
17012:             push(@items,'xmldc');
17013:         }
17014:         foreach my $item (@items) {
17015:             if (exists($currautocreate{$item})) {
17016:                 if ($currautocreate{$item} ne $newvals{$item}) {
17017:                     $changes{$item} = 1;
17018:                 }
17019:             } elsif ($newvals{$item}) {
17020:                 $changes{$item} = 1;
17021:             }
17022:         }
17023:         if (keys(%changes) > 0) {
17024:             my @offon = ('off','on'); 
17025:             $resulttext = &mt('Changes made:').'<ul>';
17026:             foreach my $item (@types) {
17027:                 if ($changes{$item}) {
17028:                     my $newtxt = $offon[$newvals{$item}];
17029:                     $resulttext .= '<li>'.
17030:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
17031:                                        '<b>','</b>').
17032:                                    '</li>';
17033:                 }
17034:             }
17035:             if ($changes{'xmldc'}) {
17036:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
17037:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
17038:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
17039:             }
17040:             $resulttext .= '</ul>';
17041:         } else {
17042:             $resulttext = &mt('No changes made to auto-creation settings');
17043:         }
17044:     } else {
17045:         $resulttext = '<span class="LC_error">'.
17046:             &mt('An error occurred: [_1]',$putresult).'</span>';
17047:     }
17048:     return $resulttext;
17049: }
17050: 
17051: sub modify_directorysrch {
17052:     my ($dom,$lastactref,%domconfig) = @_;
17053:     my ($resulttext,%changes);
17054:     my %currdirsrch;
17055:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
17056:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
17057:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
17058:         }
17059:     }
17060:     my %title = ( available => 'Institutional directory search available',
17061:                   localonly => 'Other domains can search institution',
17062:                   lcavailable => 'LON-CAPA directory search available',
17063:                   lclocalonly => 'Other domains can search LON-CAPA domain',
17064:                   searchby => 'Search types',
17065:                   searchtypes => 'Search latitude');
17066:     my @offon = ('off','on');
17067:     my @otherdoms = ('Yes','No');
17068: 
17069:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
17070:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
17071:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
17072: 
17073:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17074:     if (keys(%{$usertypes}) == 0) {
17075:         @cansearch = ('default');
17076:     } else {
17077:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
17078:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
17079:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
17080:                     push(@{$changes{'cansearch'}},$type);
17081:                 }
17082:             }
17083:             foreach my $type (@cansearch) {
17084:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
17085:                     push(@{$changes{'cansearch'}},$type);
17086:                 }
17087:             }
17088:         } else {
17089:             push(@{$changes{'cansearch'}},@cansearch);
17090:         }
17091:     }
17092: 
17093:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
17094:         foreach my $by (@{$currdirsrch{'searchby'}}) {
17095:             if (!grep(/^\Q$by\E$/,@searchby)) {
17096:                 push(@{$changes{'searchby'}},$by);
17097:             }
17098:         }
17099:         foreach my $by (@searchby) {
17100:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
17101:                 push(@{$changes{'searchby'}},$by);
17102:             }
17103:         }
17104:     } else {
17105:         push(@{$changes{'searchby'}},@searchby);
17106:     }
17107: 
17108:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
17109:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
17110:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
17111:                 push(@{$changes{'searchtypes'}},$type);
17112:             }
17113:         }
17114:         foreach my $type (@searchtypes) {
17115:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
17116:                 push(@{$changes{'searchtypes'}},$type);
17117:             }
17118:         }
17119:     } else {
17120:         if (exists($currdirsrch{'searchtypes'})) {
17121:             foreach my $type (@searchtypes) {  
17122:                 if ($type ne $currdirsrch{'searchtypes'}) { 
17123:                     push(@{$changes{'searchtypes'}},$type);
17124:                 }
17125:             }
17126:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
17127:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
17128:             }   
17129:         } else {
17130:             push(@{$changes{'searchtypes'}},@searchtypes); 
17131:         }
17132:     }
17133: 
17134:     my %dirsrch_hash =  (
17135:             directorysrch => { available => $env{'form.dirsrch_available'},
17136:                                cansearch => \@cansearch,
17137:                                localonly => $env{'form.dirsrch_instlocalonly'},
17138:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
17139:                                lcavailable => $env{'form.dirsrch_domavailable'},
17140:                                searchby => \@searchby,
17141:                                searchtypes => \@searchtypes,
17142:                              }
17143:             );
17144:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
17145:                                              $dom);
17146:     if ($putresult eq 'ok') {
17147:         if (exists($currdirsrch{'available'})) {
17148:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
17149:                  $changes{'available'} = 1;
17150:              }
17151:         } else {
17152:             if ($env{'form.dirsrch_available'} eq '1') {
17153:                 $changes{'available'} = 1;
17154:             }
17155:         }
17156:         if (exists($currdirsrch{'lcavailable'})) {
17157:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
17158:                 $changes{'lcavailable'} = 1;
17159:             }
17160:         } else {
17161:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
17162:                 $changes{'lcavailable'} = 1;
17163:             }
17164:         }
17165:         if (exists($currdirsrch{'localonly'})) {
17166:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
17167:                 $changes{'localonly'} = 1;
17168:             }
17169:         } else {
17170:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
17171:                 $changes{'localonly'} = 1;
17172:             }
17173:         }
17174:         if (exists($currdirsrch{'lclocalonly'})) {
17175:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
17176:                 $changes{'lclocalonly'} = 1;
17177:             }
17178:         } else {
17179:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
17180:                 $changes{'lclocalonly'} = 1;
17181:             }
17182:         }
17183:         if (keys(%changes) > 0) {
17184:             $resulttext = &mt('Changes made:').'<ul>';
17185:             if ($changes{'available'}) {
17186:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
17187:             }
17188:             if ($changes{'lcavailable'}) {
17189:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
17190:             }
17191:             if ($changes{'localonly'}) {
17192:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
17193:             }
17194:             if ($changes{'lclocalonly'}) {
17195:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
17196:             }
17197:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
17198:                 my $chgtext;
17199:                 if (ref($usertypes) eq 'HASH') {
17200:                     if (keys(%{$usertypes}) > 0) {
17201:                         foreach my $type (@{$types}) {
17202:                             if (grep(/^\Q$type\E$/,@cansearch)) {
17203:                                 $chgtext .= $usertypes->{$type}.'; ';
17204:                             }
17205:                         }
17206:                         if (grep(/^default$/,@cansearch)) {
17207:                             $chgtext .= $othertitle;
17208:                         } else {
17209:                             $chgtext =~ s/\; $//;
17210:                         }
17211:                         $resulttext .=
17212:                             '<li>'.
17213:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
17214:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
17215:                             '</li>';
17216:                     }
17217:                 }
17218:             }
17219:             if (ref($changes{'searchby'}) eq 'ARRAY') {
17220:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
17221:                 my $chgtext;
17222:                 foreach my $type (@{$titleorder}) {
17223:                     if (grep(/^\Q$type\E$/,@searchby)) {
17224:                         if (defined($searchtitles->{$type})) {
17225:                             $chgtext .= $searchtitles->{$type}.'; ';
17226:                         }
17227:                     }
17228:                 }
17229:                 $chgtext =~ s/\; $//;
17230:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
17231:             }
17232:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
17233:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
17234:                 my $chgtext;
17235:                 foreach my $type (@{$srchtypeorder}) {
17236:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
17237:                         if (defined($srchtypes_desc->{$type})) {
17238:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
17239:                         }
17240:                     }
17241:                 }
17242:                 $chgtext =~ s/\; $//;
17243:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
17244:             }
17245:             $resulttext .= '</ul>';
17246:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
17247:             if (ref($lastactref) eq 'HASH') {
17248:                 $lastactref->{'directorysrch'} = 1;
17249:             }
17250:         } else {
17251:             $resulttext = &mt('No changes made to directory search settings');
17252:         }
17253:     } else {
17254:         $resulttext = '<span class="LC_error">'.
17255:                       &mt('An error occurred: [_1]',$putresult).'</span>';
17256:     }
17257:     return $resulttext;
17258: }
17259: 
17260: sub modify_contacts {
17261:     my ($dom,$lastactref,%domconfig) = @_;
17262:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
17263:     if (ref($domconfig{'contacts'}) eq 'HASH') {
17264:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
17265:             $currsetting{$key} = $domconfig{'contacts'}{$key};
17266:         }
17267:     }
17268:     my (%others,%to,%bcc,%includestr,%includeloc);
17269:     my @contacts = ('supportemail','adminemail');
17270:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
17271:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
17272:     my @toggles = ('reporterrors','reportupdates','reportstatus');
17273:     my @lonstatus = ('threshold','sysmail','weights','excluded');
17274:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
17275:     foreach my $type (@mailings) {
17276:         @{$newsetting{$type}} = 
17277:             &Apache::loncommon::get_env_multiple('form.'.$type);
17278:         foreach my $item (@contacts) {
17279:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
17280:                 $contacts_hash{contacts}{$type}{$item} = 1;
17281:             } else {
17282:                 $contacts_hash{contacts}{$type}{$item} = 0;
17283:             }
17284:         }
17285:         $others{$type} = $env{'form.'.$type.'_others'};
17286:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
17287:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17288:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
17289:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
17290:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
17291:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
17292:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
17293:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17294:             }
17295:         }
17296:     }
17297:     foreach my $item (@contacts) {
17298:         $to{$item} = $env{'form.'.$item};
17299:         $contacts_hash{'contacts'}{$item} = $to{$item};
17300:     }
17301:     foreach my $item (@toggles) {
17302:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
17303:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
17304:         }
17305:     }
17306:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
17307:     foreach my $item (@lonstatus) {
17308:         if ($item eq 'excluded') {
17309:             my (%serverhomes,@excluded);
17310:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
17311:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
17312:             if (@possexcluded) {
17313:                 foreach my $id (sort(@possexcluded)) {
17314:                     if ($serverhomes{$id}) {
17315:                         push(@excluded,$id);
17316:                     }
17317:                 }
17318:             }
17319:             if (@excluded) {
17320:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
17321:             }
17322:         } elsif ($item eq 'weights') {
17323:             foreach my $type ('E','W','N','U') {
17324:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
17325:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
17326:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
17327:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
17328:                             $env{'form.error'.$item.'_'.$type};
17329:                     }
17330:                 }
17331:             }
17332:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
17333:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
17334:             if ($env{'form.error'.$item} =~ /^\d+$/) {
17335:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
17336:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
17337:                 }
17338:             }
17339:         }
17340:     }
17341:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
17342:         foreach my $field (@{$fields}) {
17343:             if (ref($possoptions->{$field}) eq 'ARRAY') {
17344:                 my $value = $env{'form.helpform_'.$field};
17345:                 $value =~ s/^\s+|\s+$//g;
17346:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
17347:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
17348:                     if ($field eq 'screenshot') {
17349:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
17350:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
17351:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
17352:                         }
17353:                     }
17354:                 }
17355:             }
17356:         }
17357:     }
17358:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17359:     my (@statuses,%usertypeshash,@overrides);
17360:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
17361:         @statuses = @{$types};
17362:         if (ref($usertypes) eq 'HASH') {
17363:             %usertypeshash = %{$usertypes};
17364:         }
17365:     }
17366:     if (@statuses) {
17367:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
17368:         foreach my $type (@possoverrides) {
17369:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
17370:                 push(@overrides,$type);
17371:             }
17372:         }
17373:         if (@overrides) {
17374:             foreach my $type (@overrides) {
17375:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
17376:                 foreach my $item (@contacts) {
17377:                     if (grep(/^\Q$item\E$/,@standard)) {
17378:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
17379:                         $newsetting{'override_'.$type}{$item} = 1;
17380:                     } else {
17381:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
17382:                         $newsetting{'override_'.$type}{$item} = 0;
17383:                     }
17384:                 }
17385:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
17386:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17387:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
17388:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17389:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
17390:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
17391:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
17392:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17393:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
17394:                 }
17395:             }     
17396:         }
17397:     }
17398:     if (keys(%currsetting) > 0) {
17399:         foreach my $item (@contacts) {
17400:             if ($to{$item} ne $currsetting{$item}) {
17401:                 $changes{$item} = 1;
17402:             }
17403:         }
17404:         foreach my $type (@mailings) {
17405:             foreach my $item (@contacts) {
17406:                 if (ref($currsetting{$type}) eq 'HASH') {
17407:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
17408:                         push(@{$changes{$type}},$item);
17409:                     }
17410:                 } else {
17411:                     push(@{$changes{$type}},@{$newsetting{$type}});
17412:                 }
17413:             }
17414:             if ($others{$type} ne $currsetting{$type}{'others'}) {
17415:                 push(@{$changes{$type}},'others');
17416:             }
17417:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17418:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
17419:                     push(@{$changes{$type}},'bcc'); 
17420:                 }
17421:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
17422:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
17423:                     push(@{$changes{$type}},'include');
17424:                 }
17425:             }
17426:         }
17427:         if (ref($fields) eq 'ARRAY') {
17428:             if (ref($currsetting{'helpform'}) eq 'HASH') {
17429:                 foreach my $field (@{$fields}) {
17430:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
17431:                         push(@{$changes{'helpform'}},$field);
17432:                     }
17433:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17434:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
17435:                             push(@{$changes{'helpform'}},'maxsize');
17436:                         }
17437:                     }
17438:                 }
17439:             } else {
17440:                 foreach my $field (@{$fields}) {
17441:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17442:                         push(@{$changes{'helpform'}},$field);
17443:                     }
17444:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17445:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17446:                             push(@{$changes{'helpform'}},'maxsize');
17447:                         }
17448:                     }
17449:                 }
17450:             }
17451:         }
17452:         if (@statuses) {
17453:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
17454:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
17455:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
17456:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
17457:                             foreach my $item (@contacts,'bcc','others','include') {
17458:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
17459:                                     push(@{$changes{'overrides'}},$key);
17460:                                     last;
17461:                                 }
17462:                             }
17463:                         } else {
17464:                             push(@{$changes{'overrides'}},$key);
17465:                         }
17466:                     }
17467:                 }
17468:                 foreach my $key (@overrides) {
17469:                     unless (exists($currsetting{'overrides'}{$key})) {
17470:                         push(@{$changes{'overrides'}},$key);
17471:                     }
17472:                 }
17473:             } else {
17474:                 foreach my $key (@overrides) {
17475:                     push(@{$changes{'overrides'}},$key); 
17476:                 }
17477:             }
17478:         }
17479:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
17480:             foreach my $key ('excluded','weights','threshold','sysmail') {
17481:                 if ($key eq 'excluded') {
17482:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17483:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
17484:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17485:                             (@{$currsetting{'lonstatus'}{$key}})) {
17486:                             my @diffs =
17487:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
17488:                                                                    $currsetting{'lonstatus'}{$key});
17489:                             if (@diffs) {
17490:                                 push(@{$changes{'lonstatus'}},$key);
17491:                             }
17492:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
17493:                             push(@{$changes{'lonstatus'}},$key);
17494:                         }
17495:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17496:                              (@{$currsetting{'lonstatus'}{$key}})) {
17497:                         push(@{$changes{'lonstatus'}},$key);
17498:                     }
17499:                 } elsif ($key eq 'weights') {
17500:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17501:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
17502:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17503:                             foreach my $type ('E','W','N','U') {
17504:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
17505:                                         $currsetting{'lonstatus'}{$key}{$type}) {
17506:                                     push(@{$changes{'lonstatus'}},$key);
17507:                                     last;
17508:                                 }
17509:                             }
17510:                         } else {
17511:                             foreach my $type ('E','W','N','U') {
17512:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
17513:                                     push(@{$changes{'lonstatus'}},$key);
17514:                                     last;
17515:                                 }
17516:                             }
17517:                         }
17518:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17519:                         foreach my $type ('E','W','N','U') {
17520:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
17521:                                 push(@{$changes{'lonstatus'}},$key);
17522:                                 last;
17523:                             }
17524:                         }
17525:                     }
17526:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
17527:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17528:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17529:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
17530:                                 push(@{$changes{'lonstatus'}},$key);
17531:                             }
17532:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
17533:                             push(@{$changes{'lonstatus'}},$key);
17534:                         }
17535:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17536:                         push(@{$changes{'lonstatus'}},$key);
17537:                     }
17538:                 }
17539:             }
17540:         } else {
17541:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17542:                 foreach my $key ('excluded','weights','threshold','sysmail') {
17543:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17544:                         push(@{$changes{'lonstatus'}},$key);
17545:                     }
17546:                 }
17547:             }
17548:         }
17549:     } else {
17550:         my %default;
17551:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
17552:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
17553:         $default{'errormail'} = 'adminemail';
17554:         $default{'packagesmail'} = 'adminemail';
17555:         $default{'helpdeskmail'} = 'supportemail';
17556:         $default{'otherdomsmail'} = 'supportemail';
17557:         $default{'lonstatusmail'} = 'adminemail';
17558:         $default{'requestsmail'} = 'adminemail';
17559:         $default{'updatesmail'} = 'adminemail';
17560:         $default{'hostipmail'} = 'adminemail';
17561:         foreach my $item (@contacts) {
17562:            if ($to{$item} ne $default{$item}) {
17563:                $changes{$item} = 1;
17564:            }
17565:         }
17566:         foreach my $type (@mailings) {
17567:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
17568:                 push(@{$changes{$type}},@{$newsetting{$type}});
17569:             }
17570:             if ($others{$type} ne '') {
17571:                 push(@{$changes{$type}},'others');
17572:             }
17573:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17574:                 if ($bcc{$type} ne '') {
17575:                     push(@{$changes{$type}},'bcc');
17576:                 }
17577:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
17578:                     push(@{$changes{$type}},'include');
17579:                 }
17580:             }
17581:         }
17582:         if (ref($fields) eq 'ARRAY') {
17583:             foreach my $field (@{$fields}) {
17584:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17585:                     push(@{$changes{'helpform'}},$field);
17586:                 }
17587:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17588:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17589:                         push(@{$changes{'helpform'}},'maxsize');
17590:                     }
17591:                 }
17592:             }
17593:         }
17594:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17595:             foreach my $key ('excluded','weights','threshold','sysmail') {
17596:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17597:                     push(@{$changes{'lonstatus'}},$key);
17598:                 }
17599:             }
17600:         }
17601:     }
17602:     foreach my $item (@toggles) {
17603:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
17604:             $changes{$item} = 1;
17605:         } elsif ((!$env{'form.'.$item}) &&
17606:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
17607:             $changes{$item} = 1;
17608:         }
17609:     }
17610:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
17611:                                              $dom);
17612:     if ($putresult eq 'ok') {
17613:         if (keys(%changes) > 0) {
17614:             &Apache::loncommon::devalidate_domconfig_cache($dom);
17615:             if (ref($lastactref) eq 'HASH') {
17616:                 $lastactref->{'domainconfig'} = 1;
17617:             }
17618:             my ($titles,$short_titles)  = &contact_titles();
17619:             $resulttext = &mt('Changes made:').'<ul>';
17620:             foreach my $item (@contacts) {
17621:                 if ($changes{$item}) {
17622:                     $resulttext .= '<li>'.$titles->{$item}.
17623:                                     &mt(' set to: ').
17624:                                     '<span class="LC_cusr_emph">'.
17625:                                     $to{$item}.'</span></li>';
17626:                 }
17627:             }
17628:             foreach my $type (@mailings) {
17629:                 if (ref($changes{$type}) eq 'ARRAY') {
17630:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17631:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
17632:                     } else {
17633:                         $resulttext .= '<li>'.$titles->{$type}.': ';
17634:                     }
17635:                     my @text;
17636:                     foreach my $item (@{$newsetting{$type}}) {
17637:                         push(@text,$short_titles->{$item});
17638:                     }
17639:                     if ($others{$type} ne '') {
17640:                         push(@text,$others{$type});
17641:                     }
17642:                     if (@text) {
17643:                         $resulttext .= '<span class="LC_cusr_emph">'.
17644:                                        join(', ',@text).'</span>';
17645:                     }
17646:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17647:                         if ($bcc{$type} ne '') {
17648:                             my $bcctext;
17649:                             if (@text) {
17650:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
17651:                             } else {
17652:                                 $bcctext = '(Bcc)';
17653:                             }
17654:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
17655:                         } elsif (!@text) {
17656:                             $resulttext .= &mt('No one');
17657:                         }   
17658:                         if ($includestr{$type} ne '') {
17659:                             if ($includeloc{$type} eq 'b') {
17660:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
17661:                             } elsif ($includeloc{$type} eq 's') {
17662:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
17663:                             }
17664:                         }
17665:                     } elsif (!@text) {
17666:                         $resulttext .= &mt('No recipients');
17667:                     }
17668:                     $resulttext .= '</li>';
17669:                 }
17670:             }
17671:             if (ref($changes{'overrides'}) eq 'ARRAY') {
17672:                 my @deletions;
17673:                 foreach my $type (@{$changes{'overrides'}}) {
17674:                     if ($usertypeshash{$type}) {
17675:                         if (grep(/^\Q$type\E/,@overrides)) {
17676:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
17677:                                                       $usertypeshash{$type}).'<ul><li>';
17678:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
17679:                                 my @text;
17680:                                 foreach my $item (@contacts) {
17681:                                     if ($newsetting{'override_'.$type}{$item}) { 
17682:                                         push(@text,$short_titles->{$item});
17683:                                     }
17684:                                 }
17685:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
17686:                                     push(@text,$newsetting{'override_'.$type}{'others'});
17687:                                 }
17688:   
17689:                                 if (@text) {
17690:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
17691:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
17692:                                 }
17693:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
17694:                                     my $bcctext;
17695:                                     if (@text) {
17696:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
17697:                                     } else {
17698:                                         $bcctext = '(Bcc)';
17699:                                     }
17700:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
17701:                                 } elsif (!@text) {
17702:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
17703:                                 }
17704:                                 $resulttext .= '</li>';
17705:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
17706:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
17707:                                     if ($loc eq 'b') {
17708:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
17709:                                     } elsif ($loc eq 's') {
17710:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
17711:                                     }
17712:                                 }
17713:                             }
17714:                             $resulttext .= '</li></ul></li>';
17715:                         } else {
17716:                             push(@deletions,$usertypeshash{$type});
17717:                         }
17718:                     }
17719:                 }
17720:                 if (@deletions) {
17721:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
17722:                                               join(', ',@deletions)).'</li>';
17723:                 }
17724:             }
17725:             my @offon = ('off','on');
17726:             my $corelink = &core_link_msu();
17727:             if ($changes{'reporterrors'}) {
17728:                 $resulttext .= '<li>'.
17729:                                &mt('E-mail error reports to [_1] set to "'.
17730:                                    $offon[$env{'form.reporterrors'}].'".',
17731:                                    $corelink).
17732:                                '</li>';
17733:             }
17734:             if ($changes{'reportupdates'}) {
17735:                 $resulttext .= '<li>'.
17736:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
17737:                                     $offon[$env{'form.reportupdates'}].'".',
17738:                                     $corelink).
17739:                                 '</li>';
17740:             }
17741:             if ($changes{'reportstatus'}) {
17742:                 $resulttext .= '<li>'.
17743:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
17744:                                     $offon[$env{'form.reportstatus'}].'".',
17745:                                     $corelink).
17746:                                 '</li>';
17747:             }
17748:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
17749:                 $resulttext .= '<li>'.
17750:                                &mt('Nightly status check e-mail settings').':<ul>';
17751:                 my (%defval,%use_def,%shown);
17752:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
17753:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
17754:                 $defval{'weights'} =
17755:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
17756:                 $defval{'excluded'} = &mt('None');
17757:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
17758:                     foreach my $item ('threshold','sysmail','weights','excluded') {
17759:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
17760:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
17761:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
17762:                             } elsif ($item eq 'weights') {
17763:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
17764:                                     foreach my $type ('E','W','N','U') {
17765:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
17766:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
17767:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
17768:                                         } else {
17769:                                             $shown{$item} .= $lonstatus_defs->{$type};
17770:                                         }
17771:                                         $shown{$item} .= ', ';
17772:                                     }
17773:                                     $shown{$item} =~ s/, $//;
17774:                                 } else {
17775:                                     $shown{$item} = $defval{$item};
17776:                                 }
17777:                             } elsif ($item eq 'excluded') {
17778:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
17779:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
17780:                                 } else {
17781:                                     $shown{$item} = $defval{$item};
17782:                                 }
17783:                             }
17784:                         } else {
17785:                             $shown{$item} = $defval{$item};
17786:                         }
17787:                     }
17788:                 } else {
17789:                     foreach my $item ('threshold','weights','excluded','sysmail') {
17790:                         $shown{$item} = $defval{$item};
17791:                     }
17792:                 }
17793:                 foreach my $item ('threshold','weights','excluded','sysmail') {
17794:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
17795:                                           $shown{$item}).'</li>';
17796:                 }
17797:                 $resulttext .= '</ul></li>';
17798:             }
17799:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
17800:                 my (@optional,@required,@unused,$maxsizechg);
17801:                 foreach my $field (@{$changes{'helpform'}}) {
17802:                     if ($field eq 'maxsize') {
17803:                         $maxsizechg = 1;
17804:                         next;
17805:                     }
17806:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
17807:                         push(@optional,$field);
17808:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
17809:                         push(@unused,$field);
17810:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
17811:                         push(@required,$field);
17812:                     }
17813:                 }
17814:                 if (@optional) {
17815:                     $resulttext .= '<li>'.
17816:                                    &mt('Help form fields changed to "Optional": [_1].',
17817:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
17818:                                    '</li>';
17819:                 }
17820:                 if (@required) {
17821:                     $resulttext .= '<li>'.
17822:                                    &mt('Help form fields changed to "Required": [_1].',
17823:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
17824:                                    '</li>';
17825:                 }
17826:                 if (@unused) {
17827:                     $resulttext .= '<li>'.
17828:                                    &mt('Help form fields changed to "Not shown": [_1].',
17829:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
17830:                                    '</li>';
17831:                 }
17832:                 if ($maxsizechg) {
17833:                     $resulttext .= '<li>'.
17834:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
17835:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
17836:                                    '</li>';
17837:                 }
17838:             }
17839:             $resulttext .= '</ul>';
17840:         } else {
17841:             $resulttext = &mt('No changes made to contacts and form settings');
17842:         }
17843:     } else {
17844:         $resulttext = '<span class="LC_error">'.
17845:             &mt('An error occurred: [_1].',$putresult).'</span>';
17846:     }
17847:     return $resulttext;
17848: }
17849: 
17850: sub modify_privacy {
17851:     my ($dom,%domconfig) = @_;
17852:     my ($resulttext,%current,%changes);
17853:     if (ref($domconfig{'privacy'}) eq 'HASH') {
17854:         %current = %{$domconfig{'privacy'}};
17855:     }
17856:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
17857:     my @items = ('domain','author','course','community');
17858:     my %names = &Apache::lonlocal::texthash (
17859:                    domain => 'Assigned domain role(s)',
17860:                    author => 'Assigned co-author role(s)',
17861:                    course => 'Assigned course role(s)',
17862:                    community => 'Assigned community role',
17863:                 );
17864:     my %roles = &Apache::lonlocal::texthash (
17865:                    domain => 'Domain role',
17866:                    author => 'Co-author role',
17867:                    course => 'Course role',
17868:                    community => 'Community role',
17869:                 );
17870:     my %titles = &Apache::lonlocal::texthash (
17871:                   approval => 'Approval for role in different domain',
17872:                   othdom   => 'User information available in other domain',
17873:                   priv     => 'Information viewable by privileged user in same domain',
17874:                   unpriv   => 'Information viewable by unprivileged user in same domain',
17875:                   instdom  => 'Other domain shares institution/provider',
17876:                   extdom   => 'Other domain has different institution/provider',
17877:                   none     => 'Not allowed',
17878:                   user     => 'User authorizes',
17879:                   domain   => 'Domain Coordinator authorizes',
17880:                   auto     => 'Unrestricted',
17881:     );
17882:     my %fieldnames = &Apache::lonlocal::texthash (
17883:                         id => 'Student/Employee ID',
17884:                         permanentemail => 'E-mail address',
17885:                         lastname => 'Last Name',
17886:                         firstname => 'First Name',
17887:                         middlename => 'Middle Name',
17888:                         generation => 'Generation',
17889:     );
17890:     my ($othertitle,$usertypes,$types) =
17891:         &Apache::loncommon::sorted_inst_types($dom);
17892:     my (%by_ip,%by_location,@intdoms,@instdoms);
17893:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
17894: 
17895:     my %privacyhash = (
17896:                        'approval' => {
17897:                                        instdom => {},
17898:                                        extdom  => {},
17899:                                      },
17900:                        'othdom'   => {},
17901:                        'priv'     => {},
17902:                        'unpriv'   => {},
17903:                       );
17904:     foreach my $item (@items) {
17905:         if (@instdoms > 1) {
17906:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
17907:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
17908:             }
17909:             if (ref($current{'approval'}) eq 'HASH') {
17910:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
17911:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
17912:                         $changes{'approval'} = 1;
17913:                     }
17914:                 }
17915:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
17916:                 $changes{'approval'} = 1;
17917:             }
17918:         }
17919:         if (keys(%by_location) > 0) {
17920:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
17921:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
17922:             }
17923:             if (ref($current{'approval'}) eq 'HASH') {
17924:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
17925:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
17926:                         $changes{'approval'} = 1;
17927:                     }
17928:                 }
17929:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
17930:                 $changes{'approval'} = 1;
17931:             }
17932:         }
17933:         foreach my $status ('priv','unpriv') {
17934:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
17935:             my @newvalues;
17936:             foreach my $field (@possibles) {
17937:                 if (grep(/^\Q$field\E$/,@fields)) {
17938:                     $privacyhash{$status}{$item}{$field} = 1;
17939:                     push(@newvalues,$field);
17940:                 }
17941:             }
17942:             @newvalues = sort(@newvalues);
17943:             if (ref($current{$status}) eq 'HASH') {
17944:                 if (ref($current{$status}{$item}) eq 'HASH') {
17945:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
17946:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17947:                     if (@diffs > 0) {
17948:                         $changes{$status} = 1;
17949:                     }
17950:                 }
17951:             } else {
17952:                 my @stdfields;
17953:                 foreach my $field (@fields) {
17954:                     if ($field eq 'id') {
17955:                         next if ($status eq 'unpriv');
17956:                         next if (($status eq 'priv') && ($item eq 'community'));
17957:                     }
17958:                     push(@stdfields,$field);
17959:                 }
17960:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
17961:                 if (@diffs > 0) {
17962:                     $changes{$status} = 1;
17963:                 }
17964:             }
17965:         }
17966:     }
17967:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
17968:         my @statuses;
17969:         if (ref($types) eq 'ARRAY') {
17970:             @statuses = @{$types};
17971:         }
17972:         foreach my $type (@statuses,'default') {
17973:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
17974:             my @newvalues;
17975:             foreach my $field (sort(@possfields)) {
17976:                 if (grep(/^\Q$field\E$/,@fields)) {
17977:                     $privacyhash{'othdom'}{$type}{$field} = 1;
17978:                     push(@newvalues,$field);
17979:                 }
17980:             }
17981:             @newvalues = sort(@newvalues);
17982:             if (ref($current{'othdom'}) eq 'HASH') {
17983:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
17984:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
17985:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17986:                     if (@diffs > 0) {
17987:                         $changes{'othdom'} = 1;
17988:                     }
17989:                 }
17990:             } else {
17991:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
17992:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
17993:                 if (@diffs > 0) {
17994:                     $changes{'othdom'} = 1;
17995:                 }
17996:             }
17997:         }
17998:     }
17999:     my %confighash = (
18000:                         privacy => \%privacyhash,
18001:                      );
18002:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18003:     if ($putresult eq 'ok') {
18004:         if (keys(%changes) > 0) {
18005:             $resulttext = &mt('Changes made: ').'<ul>';
18006:             foreach my $key ('approval','othdom','priv','unpriv') {
18007:                 if ($changes{$key}) {
18008:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18009:                     if ($key eq 'approval') {
18010:                         if (keys(%{$privacyhash{$key}{instdom}})) {
18011:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
18012:                             foreach my $item (@items) {
18013:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
18014:                             }
18015:                             $resulttext .= '</ul></li>';
18016:                         }
18017:                         if (keys(%{$privacyhash{$key}{extdom}})) {
18018:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
18019:                             foreach my $item (@items) {
18020:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
18021:                             }
18022:                             $resulttext .= '</ul></li>';
18023:                         }
18024:                     } elsif ($key eq 'othdom') {
18025:                         my @statuses;
18026:                         if (ref($types) eq 'ARRAY') {
18027:                             @statuses = @{$types};
18028:                         }
18029:                         if (ref($privacyhash{$key}) eq 'HASH') {
18030:                             foreach my $status (@statuses,'default') {
18031:                                 if ($status eq 'default') {
18032:                                     $resulttext .= '<li>'.$othertitle.': ';
18033:                                 } elsif (ref($usertypes) eq 'HASH') {
18034:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
18035:                                 } else {
18036:                                     next;
18037:                                 }
18038:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
18039:                                     if (keys(%{$privacyhash{$key}{$status}})) {
18040:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
18041:                                     } else {
18042:                                         $resulttext .= &mt('none');
18043:                                     }
18044:                                 }
18045:                                 $resulttext .= '</li>';
18046:                             }
18047:                         }
18048:                     } else {
18049:                         foreach my $item (@items) {
18050:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
18051:                                 $resulttext .= '<li>'.$names{$item}.': ';
18052:                                 if (keys(%{$privacyhash{$key}{$item}})) {
18053:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
18054:                                 } else {
18055:                                     $resulttext .= &mt('none');
18056:                                 }
18057:                                 $resulttext .= '</li>';
18058:                             }
18059:                         }
18060:                     }
18061:                     $resulttext .= '</ul></li>';
18062:                 }
18063:             }
18064:         } else {
18065:             $resulttext = &mt('No changes made to user information settings');
18066:         }
18067:     } else {
18068:         $resulttext = '<span class="LC_error">'.
18069:             &mt('An error occurred: [_1]',$putresult).'</span>';
18070:     }
18071:     return $resulttext;
18072: }
18073: 
18074: sub modify_passwords {
18075:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18076:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
18077:         $updatedefaults,$updateconf);
18078:     my $customfn = 'resetpw.html';
18079:     if (ref($domconfig{'passwords'}) eq 'HASH') {
18080:         %current = %{$domconfig{'passwords'}};
18081:     }
18082:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18083:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18084:     if (ref($types) eq 'ARRAY') {
18085:         @oktypes = @{$types};
18086:     }
18087:     push(@oktypes,'default');
18088: 
18089:     my %titles = &Apache::lonlocal::texthash (
18090:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
18091:         intauth_check  => 'Check bcrypt cost if authenticated',
18092:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
18093:         permanent      => 'Permanent e-mail address',
18094:         critical       => 'Critical notification address',
18095:         notify         => 'Notification address',
18096:         min            => 'Minimum password length',
18097:         max            => 'Maximum password length',
18098:         chars          => 'Required characters',
18099:         expire         => 'Password expiration (days)',
18100:         numsaved       => 'Number of previous passwords to save',
18101:         reset          => 'Resetting Forgotten Password',
18102:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
18103:         rules          => 'Rules for LON-CAPA Passwords',
18104:         crsownerchg    => 'Course Owner Changing Student Passwords',
18105:         username       => 'Username',
18106:         email          => 'E-mail address',
18107:     );
18108: 
18109: #
18110: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
18111: #
18112:     my (%curr_defaults,%save_defaults);
18113:     if (ref($domconfig{'defaults'}) eq 'HASH') {
18114:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
18115:             if ($key =~ /^intauth_(cost|check|switch)$/) {
18116:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
18117:             } else {
18118:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
18119:             }
18120:         }
18121:     }
18122:     my %staticdefaults = (
18123:         'resetlink'      => 2,
18124:         'resetcase'      => \@oktypes,
18125:         'resetprelink'   => 'both',
18126:         'resetemail'     => ['critical','notify','permanent'],
18127:         'intauth_cost'   => 10,
18128:         'intauth_check'  => 0,
18129:         'intauth_switch' => 0,
18130:     );
18131:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18132:     foreach my $type (@oktypes) {
18133:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
18134:     }
18135:     my $linklife = $env{'form.passwords_link'};
18136:     $linklife =~ s/^\s+|\s+$//g;
18137:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
18138:         $newvalues{'resetlink'} = $linklife;
18139:         if ($current{'resetlink'}) {
18140:             if ($current{'resetlink'} ne $linklife) {
18141:                 $changes{'reset'} = 1;
18142:             }
18143:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18144:             if ($staticdefaults{'resetlink'} ne $linklife) {
18145:                 $changes{'reset'} = 1;
18146:             }
18147:         }
18148:     } elsif ($current{'resetlink'}) {
18149:         $changes{'reset'} = 1;
18150:     }
18151:     my @casesens;
18152:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
18153:     foreach my $case (sort(@posscase)) {
18154:         if (grep(/^\Q$case\E$/,@oktypes)) {
18155:             push(@casesens,$case);
18156:         }
18157:     }
18158:     $newvalues{'resetcase'} = \@casesens;
18159:     if (ref($current{'resetcase'}) eq 'ARRAY') {
18160:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
18161:         if (@diffs > 0) {
18162:             $changes{'reset'} = 1;
18163:         }
18164:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18165:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
18166:         if (@diffs > 0) {
18167:             $changes{'reset'} = 1;
18168:         }
18169:     }
18170:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
18171:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
18172:         if (exists($current{'resetprelink'})) {
18173:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
18174:                 $changes{'reset'} = 1;
18175:             }
18176:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18177:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
18178:                 $changes{'reset'} = 1;
18179:             }
18180:         }
18181:     } elsif ($current{'resetprelink'}) {
18182:         $changes{'reset'} = 1;
18183:     }
18184:     foreach my $type (@oktypes) {
18185:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
18186:         my @postlink;
18187:         foreach my $item (sort(@possplink)) {
18188:             if ($item =~ /^(email|username)$/) {
18189:                 push(@postlink,$item);
18190:             }
18191:         }
18192:         $newvalues{'resetpostlink'}{$type} = \@postlink;
18193:         unless ($changes{'reset'}) {
18194:             if (ref($current{'resetpostlink'}) eq 'HASH') {
18195:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
18196:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
18197:                     if (@diffs > 0) {
18198:                         $changes{'reset'} = 1;
18199:                     }
18200:                 } else {
18201:                     $changes{'reset'} = 1;
18202:                 }
18203:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18204:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
18205:                 if (@diffs > 0) {
18206:                     $changes{'reset'} = 1;
18207:                 }
18208:             }
18209:         }
18210:     }
18211:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
18212:     my @resetemail;
18213:     foreach my $item (sort(@possemailsrc)) {
18214:         if ($item =~ /^(permanent|critical|notify)$/) {
18215:             push(@resetemail,$item);
18216:         }
18217:     }
18218:     $newvalues{'resetemail'} = \@resetemail;
18219:     unless ($changes{'reset'}) {
18220:         if (ref($current{'resetemail'}) eq 'ARRAY') {
18221:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
18222:             if (@diffs > 0) {
18223:                 $changes{'reset'} = 1;
18224:             }
18225:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18226:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
18227:             if (@diffs > 0) {
18228:                 $changes{'reset'} = 1;
18229:             }
18230:         }
18231:     }
18232:     if ($env{'form.passwords_stdtext'} == 0) {
18233:         $newvalues{'resetremove'} = 1;
18234:         unless ($current{'resetremove'}) {
18235:             $changes{'reset'} = 1;
18236:         }
18237:     } elsif ($current{'resetremove'}) {
18238:         $changes{'reset'} = 1;
18239:     }
18240:     if ($env{'form.passwords_customfile.filename'} ne '') {
18241:         my $servadm = $r->dir_config('lonAdmEMail');
18242:         my ($configuserok,$author_ok,$switchserver) =
18243:             &config_check($dom,$confname,$servadm);
18244:         my $error;
18245:         if ($configuserok eq 'ok') {
18246:             if ($switchserver) {
18247:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
18248:             } else {
18249:                 if ($author_ok eq 'ok') {
18250:                     my ($result,$customurl) =
18251:                         &publishlogo($r,'upload','passwords_customfile',$dom,
18252:                                      $confname,'customtext/resetpw','','',$customfn);
18253:                     if ($result eq 'ok') {
18254:                         $newvalues{'resetcustom'} = $customurl;
18255:                         $changes{'reset'} = 1;
18256:                     } else {
18257:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
18258:                     }
18259:                 } else {
18260:                     $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);
18261:                 }
18262:             }
18263:         } else {
18264:             $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);
18265:         }
18266:         if ($error) {
18267:             &Apache::lonnet::logthis($error);
18268:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18269:         }
18270:     } elsif ($current{'resetcustom'}) {
18271:         if ($env{'form.passwords_custom_del'}) {
18272:             $changes{'reset'} = 1;
18273:         } else {
18274:             $newvalues{'resetcustom'} = $current{'resetcustom'};
18275:         }
18276:     }
18277:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
18278:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
18279:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
18280:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
18281:             $changes{'intauth'} = 1;
18282:         }
18283:     } else {
18284:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
18285:     }
18286:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
18287:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
18288:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
18289:             $changes{'intauth'} = 1;
18290:         }
18291:     } else {
18292:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18293:     }
18294:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
18295:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
18296:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
18297:             $changes{'intauth'} = 1;
18298:         }
18299:     } else {
18300:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18301:     }
18302:     foreach my $item ('cost','check','switch') {
18303:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
18304:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
18305:             $updatedefaults = 1;
18306:         }
18307:     }
18308:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
18309:     my %crsownerchg = (
18310:                         by => [],
18311:                         for => [],
18312:                       );
18313:     foreach my $item ('by','for') {
18314:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
18315:         foreach my $type (sort(@posstypes)) {
18316:             if (grep(/^\Q$type\E$/,@oktypes)) {
18317:                 push(@{$crsownerchg{$item}},$type);
18318:             }
18319:         }
18320:     }
18321:     $newvalues{'crsownerchg'} = \%crsownerchg;
18322:     if (ref($current{'crsownerchg'}) eq 'HASH') {
18323:         foreach my $item ('by','for') {
18324:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
18325:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
18326:                 if (@diffs > 0) {
18327:                     $changes{'crsownerchg'} = 1;
18328:                     last;
18329:                 }
18330:             }
18331:         }
18332:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
18333:         foreach my $item ('by','for') {
18334:             if (@{$crsownerchg{$item}} > 0) {
18335:                 $changes{'crsownerchg'} = 1;
18336:                 last;
18337:             }
18338:         }
18339:     }
18340: 
18341:     my %confighash = (
18342:                         defaults  => \%save_defaults,
18343:                         passwords => \%newvalues,
18344:                      );
18345:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
18346: 
18347:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18348:     if ($putresult eq 'ok') {
18349:         if (keys(%changes) > 0) {
18350:             $resulttext = &mt('Changes made: ').'<ul>';
18351:             foreach my $key ('reset','intauth','rules','crsownerchg') {
18352:                 if ($changes{$key}) {
18353:                     unless ($key eq 'intauth') {
18354:                         $updateconf = 1;
18355:                     }
18356:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18357:                     if ($key eq 'reset') {
18358:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
18359:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
18360:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
18361:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
18362:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
18363:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
18364:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
18365:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
18366:                             }
18367:                         } else {
18368:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
18369:                         }
18370:                         if ($confighash{'passwords'}{'resetlink'}) {
18371:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
18372:                         } else {
18373:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
18374:                                                   &mt('Will default to 2 hours').'</li>';
18375:                         }
18376:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
18377:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
18378:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
18379:                             } else {
18380:                                 my $casesens;
18381:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
18382:                                     if ($type eq 'default') {
18383:                                         $casesens .= $othertitle.', ';
18384:                                     } elsif ($usertypes->{$type} ne '') {
18385:                                         $casesens .= $usertypes->{$type}.', ';
18386:                                     }
18387:                                 }
18388:                                 $casesens =~ s/\Q, \E$//;
18389:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
18390:                             }
18391:                         } else {
18392:                             $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>';
18393:                         }
18394:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
18395:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
18396:                         } else {
18397:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
18398:                         }
18399:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
18400:                             my $output;
18401:                             if (ref($types) eq 'ARRAY') {
18402:                                 foreach my $type (@{$types}) {
18403:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
18404:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
18405:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
18406:                                         } else {
18407:                                             $output .= $usertypes->{$type}.' -- '.
18408:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
18409:                                         }
18410:                                     }
18411:                                 }
18412:                             }
18413:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
18414:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
18415:                                     $output .= $othertitle.' -- '.&mt('none');
18416:                                 } else {
18417:                                     $output .= $othertitle.' -- '.
18418:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
18419:                                 }
18420:                             }
18421:                             if ($output) {
18422:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
18423:                             } else {
18424:                                 $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>';
18425:                             }
18426:                         } else {
18427:                             $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>';
18428:                         }
18429:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
18430:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
18431:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
18432:                             } else {
18433:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18434:                             }
18435:                         } else {
18436:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18437:                         }
18438:                         if ($confighash{'passwords'}{'resetremove'}) {
18439:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
18440:                         } else {
18441:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
18442:                         }
18443:                         if ($confighash{'passwords'}{'resetcustom'}) {
18444:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
18445:                                                                             &mt('custom text'),600,500,undef,undef,
18446:                                                                             undef,undef,'background-color:#ffffff');
18447:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
18448:                         } else {
18449:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
18450:                         }
18451:                     } elsif ($key eq 'intauth') {
18452:                         foreach my $item ('cost','switch','check') {
18453:                             my $value = $save_defaults{$key.'_'.$item};
18454:                             if ($item eq 'switch') {
18455:                                 my %optiondesc = &Apache::lonlocal::texthash (
18456:                                                      0 => 'No',
18457:                                                      1 => 'Yes',
18458:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
18459:                                                  );
18460:                                 if ($value =~ /^(0|1|2)$/) {
18461:                                     $value = $optiondesc{$value};
18462:                                 } else {
18463:                                     $value = &mt('none -- defaults to No');
18464:                                 }
18465:                             } elsif ($item eq 'check') {
18466:                                 my %optiondesc = &Apache::lonlocal::texthash (
18467:                                                      0 => 'No',
18468:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
18469:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
18470:                                                  );
18471:                                 if ($value =~ /^(0|1|2)$/) {
18472:                                     $value = $optiondesc{$value};
18473:                                 } else {
18474:                                     $value = &mt('none -- defaults to No');
18475:                                 }
18476:                             }
18477:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
18478:                         }
18479:                     } elsif ($key eq 'rules') {
18480:                         foreach my $rule ('min','max','expire','numsaved') {
18481:                             if ($confighash{'passwords'}{$rule} eq '') {
18482:                                 if ($rule eq 'min') {
18483:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
18484:                                                    ' '.&mt('Default of [_1] will be used',
18485:                                                            $Apache::lonnet::passwdmin).'</li>';
18486:                                 } else {
18487:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
18488:                                 }
18489:                             } else {
18490:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
18491:                             }
18492:                         }
18493:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
18494:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
18495:                                 my %rulenames = &Apache::lonlocal::texthash(
18496:                                                      uc => 'At least one upper case letter',
18497:                                                      lc => 'At least one lower case letter',
18498:                                                      num => 'At least one number',
18499:                                                      spec => 'At least one non-alphanumeric',
18500:                                                    );
18501:                                 my $needed = '<ul><li>'.
18502:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
18503:                                              '</li></ul>'; 
18504:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
18505:                             } else {
18506:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18507:                             }
18508:                         } else {
18509:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18510:                         }
18511:                     } elsif ($key eq 'crsownerchg') {
18512:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
18513:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
18514:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
18515:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18516:                             } else {
18517:                                 my %crsownerstr;
18518:                                 foreach my $item ('by','for') {
18519:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
18520:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
18521:                                             if ($type eq 'default') {
18522:                                                 $crsownerstr{$item} .= $othertitle.', ';
18523:                                             } elsif ($usertypes->{$type} ne '') {
18524:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
18525:                                             }
18526:                                         }
18527:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
18528:                                     }
18529:                                 }
18530:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
18531:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
18532:                             }
18533:                         } else {
18534:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18535:                         }
18536:                     }
18537:                     $resulttext .= '</ul></li>';
18538:                 }
18539:             }
18540:             $resulttext .= '</ul>';
18541:         } else {
18542:             $resulttext = &mt('No changes made to password settings');
18543:         }
18544:         my $cachetime = 24*60*60;
18545:         if ($updatedefaults) {
18546:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18547:             if (ref($lastactref) eq 'HASH') {
18548:                 $lastactref->{'domdefaults'} = 1;
18549:             }
18550:         }
18551:         if ($updateconf) {
18552:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
18553:             if (ref($lastactref) eq 'HASH') {
18554:                 $lastactref->{'passwdconf'} = 1;
18555:             }
18556:         }
18557:     } else {
18558:         $resulttext = '<span class="LC_error">'.
18559:             &mt('An error occurred: [_1]',$putresult).'</span>';
18560:     }
18561:     if ($errors) {
18562:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18563:                        $errors.'</ul></p>';
18564:     }
18565:     return $resulttext;
18566: }
18567: 
18568: sub password_rule_changes {
18569:     my ($prefix,$newvalues,$current,$changes) = @_;
18570:     return unless ((ref($newvalues) eq 'HASH') &&
18571:                    (ref($current) eq 'HASH') &&
18572:                    (ref($changes) eq 'HASH'));
18573:     my (@rules,%staticdefaults);
18574:     if ($prefix eq 'passwords') {
18575:         @rules = ('min','max','expire','numsaved');
18576:     } elsif ($prefix eq 'secrets') {
18577:         @rules = ('min','max');
18578:     }
18579:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18580:     foreach my $rule (@rules) {
18581:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
18582:         my $ruleok;
18583:         if ($rule eq 'expire') {
18584:             if (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+(|\.\d*)$/) &&
18585:                 ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18586:                 $ruleok = 1;
18587:             }
18588:         } elsif ($rule eq 'min') {
18589:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
18590:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
18591:                     $ruleok = 1;
18592:                 }
18593:             }
18594:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
18595:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18596:             $ruleok = 1;
18597:         }
18598:         if ($ruleok) {
18599:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
18600:             if (exists($current->{$rule})) {
18601:                 if ($newvalues->{$rule} ne $current->{$rule}) {
18602:                     $changes->{'rules'} = 1;
18603:                 }
18604:             } elsif ($rule eq 'min') {
18605:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
18606:                     $changes->{'rules'} = 1;
18607:                 }
18608:             } else {
18609:                 $changes->{'rules'} = 1;
18610:             }
18611:         } elsif (exists($current->{$rule})) {
18612:             $changes->{'rules'} = 1;
18613:         }
18614:     }
18615:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
18616:     my @chars;
18617:     foreach my $item (sort(@posschars)) {
18618:         if ($item =~ /^(uc|lc|num|spec)$/) {
18619:             push(@chars,$item);
18620:         }
18621:     }
18622:     $newvalues->{'chars'} = \@chars;
18623:     unless ($changes->{'rules'}) {
18624:         if (ref($current->{'chars'}) eq 'ARRAY') {
18625:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
18626:             if (@diffs > 0) {
18627:                 $changes->{'rules'} = 1;
18628:             }
18629:         } else {
18630:             if (@chars > 0) {
18631:                 $changes->{'rules'} = 1;
18632:             }
18633:         }
18634:     }
18635:     return;
18636: }
18637: 
18638: sub modify_usercreation {
18639:     my ($dom,%domconfig) = @_;
18640:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
18641:     my $warningmsg;
18642:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18643:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18644:             if ($key eq 'cancreate') {
18645:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18646:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18647:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
18648:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18649:                         } else {
18650:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18651:                         }
18652:                     }
18653:                 }
18654:             } elsif ($key eq 'email_rule') {
18655:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18656:             } else {
18657:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18658:             }
18659:         }
18660:     }
18661:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
18662:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
18663:     my @contexts = ('author','course','requestcrs');
18664:     foreach my $item(@contexts) {
18665:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
18666:     }
18667:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
18668:         foreach my $item (@contexts) {
18669:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
18670:                 push(@{$changes{'cancreate'}},$item);
18671:             }
18672:         }
18673:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
18674:         foreach my $item (@contexts) {
18675:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
18676:                 if ($cancreate{$item} ne 'any') {
18677:                     push(@{$changes{'cancreate'}},$item);
18678:                 }
18679:             } else {
18680:                 if ($cancreate{$item} ne 'none') {
18681:                     push(@{$changes{'cancreate'}},$item);
18682:                 }
18683:             }
18684:         }
18685:     } else {
18686:         foreach my $item (@contexts)  {
18687:             push(@{$changes{'cancreate'}},$item);
18688:         }
18689:     }
18690: 
18691:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
18692:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
18693:             if (!grep(/^\Q$type\E$/,@username_rule)) {
18694:                 push(@{$changes{'username_rule'}},$type);
18695:             }
18696:         }
18697:         foreach my $type (@username_rule) {
18698:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
18699:                 push(@{$changes{'username_rule'}},$type);
18700:             }
18701:         }
18702:     } else {
18703:         push(@{$changes{'username_rule'}},@username_rule);
18704:     }
18705: 
18706:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
18707:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
18708:             if (!grep(/^\Q$type\E$/,@id_rule)) {
18709:                 push(@{$changes{'id_rule'}},$type);
18710:             }
18711:         }
18712:         foreach my $type (@id_rule) {
18713:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
18714:                 push(@{$changes{'id_rule'}},$type);
18715:             }
18716:         }
18717:     } else {
18718:         push(@{$changes{'id_rule'}},@id_rule);
18719:     }
18720: 
18721:     my @authen_contexts = ('author','course','domain');
18722:     my @authtypes = ('int','krb4','krb5','loc','lti');
18723:     my %authhash;
18724:     foreach my $item (@authen_contexts) {
18725:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
18726:         foreach my $auth (@authtypes) {
18727:             if (grep(/^\Q$auth\E$/,@authallowed)) {
18728:                 $authhash{$item}{$auth} = 1;
18729:             } else {
18730:                 $authhash{$item}{$auth} = 0;
18731:             }
18732:         }
18733:     }
18734:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
18735:         foreach my $item (@authen_contexts) {
18736:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
18737:                 foreach my $auth (@authtypes) {
18738:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
18739:                         push(@{$changes{'authtypes'}},$item);
18740:                         last;
18741:                     }
18742:                 }
18743:             }
18744:         }
18745:     } else {
18746:         foreach my $item (@authen_contexts) {
18747:             push(@{$changes{'authtypes'}},$item);
18748:         }
18749:     }
18750: 
18751:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
18752:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
18753:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
18754:     $save_usercreate{'id_rule'} = \@id_rule;
18755:     $save_usercreate{'username_rule'} = \@username_rule,
18756:     $save_usercreate{'authtypes'} = \%authhash;
18757: 
18758:     my %usercreation_hash =  (
18759:         usercreation     => \%save_usercreate,
18760:     );
18761: 
18762:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
18763:                                              $dom);
18764: 
18765:     if ($putresult eq 'ok') {
18766:         if (keys(%changes) > 0) {
18767:             $resulttext = &mt('Changes made:').'<ul>';
18768:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
18769:                 my %lt = &usercreation_types();
18770:                 foreach my $type (@{$changes{'cancreate'}}) {
18771:                     my $chgtext = $lt{$type}.', ';
18772:                     if ($cancreate{$type} eq 'none') {
18773:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
18774:                     } elsif ($cancreate{$type} eq 'any') {
18775:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
18776:                     } elsif ($cancreate{$type} eq 'official') {
18777:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
18778:                     } elsif ($cancreate{$type} eq 'unofficial') {
18779:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
18780:                     }
18781:                     $resulttext .= '<li>'.$chgtext.'</li>';
18782:                 }
18783:             }
18784:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
18785:                 my ($rules,$ruleorder) = 
18786:                     &Apache::lonnet::inst_userrules($dom,'username');
18787:                 my $chgtext = '<ul>';
18788:                 foreach my $type (@username_rule) {
18789:                     if (ref($rules->{$type}) eq 'HASH') {
18790:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
18791:                     }
18792:                 }
18793:                 $chgtext .= '</ul>';
18794:                 if (@username_rule > 0) {
18795:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
18796:                 } else {
18797:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
18798:                 }
18799:             }
18800:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
18801:                 my ($idrules,$idruleorder) = 
18802:                     &Apache::lonnet::inst_userrules($dom,'id');
18803:                 my $chgtext = '<ul>';
18804:                 foreach my $type (@id_rule) {
18805:                     if (ref($idrules->{$type}) eq 'HASH') {
18806:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
18807:                     }
18808:                 }
18809:                 $chgtext .= '</ul>';
18810:                 if (@id_rule > 0) {
18811:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
18812:                 } else {
18813:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
18814:                 }
18815:             }
18816:             my %authname = &authtype_names();
18817:             my %context_title = &context_names();
18818:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
18819:                 my $chgtext = '<ul>';
18820:                 foreach my $type (@{$changes{'authtypes'}}) {
18821:                     my @allowed;
18822:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
18823:                     foreach my $auth (@authtypes) {
18824:                         if ($authhash{$type}{$auth}) {
18825:                             push(@allowed,$authname{$auth});
18826:                         }
18827:                     }
18828:                     if (@allowed > 0) {
18829:                         $chgtext .= join(', ',@allowed).'</li>';
18830:                     } else {
18831:                         $chgtext .= &mt('none').'</li>';
18832:                     }
18833:                 }
18834:                 $chgtext .= '</ul>';
18835:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
18836:                 $resulttext .= '</li>';
18837:             }
18838:             $resulttext .= '</ul>';
18839:         } else {
18840:             $resulttext = &mt('No changes made to user creation settings');
18841:         }
18842:     } else {
18843:         $resulttext = '<span class="LC_error">'.
18844:             &mt('An error occurred: [_1]',$putresult).'</span>';
18845:     }
18846:     if ($warningmsg ne '') {
18847:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18848:     }
18849:     return $resulttext;
18850: }
18851: 
18852: sub modify_selfcreation {
18853:     my ($dom,$lastactref,%domconfig) = @_;
18854:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
18855:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
18856:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18857:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
18858:     if (ref($typesref) eq 'ARRAY') {
18859:         @types = @{$typesref};
18860:     }
18861:     if (ref($usertypesref) eq 'HASH') {
18862:         %usertypes = %{$usertypesref};
18863:     }
18864:     $usertypes{'default'} = $othertitle;
18865: #
18866: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
18867: #
18868:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18869:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18870:             if ($key eq 'cancreate') {
18871:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18872:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18873:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
18874:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
18875:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
18876:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
18877:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
18878:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
18879:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18880:                         } else {
18881:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18882:                         }
18883:                     }
18884:                 }
18885:             } elsif ($key eq 'email_rule') {
18886:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18887:             } else {
18888:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18889:             }
18890:         }
18891:     }
18892: #
18893: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
18894: #
18895:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
18896:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
18897:             if ($key eq 'selfcreate') {
18898:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
18899:             } else {
18900:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
18901:             }
18902:         }
18903:     }
18904: #
18905: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
18906: #
18907:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18908:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
18909:             if ($key eq 'inststatusguest') {
18910:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
18911:             } else {
18912:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
18913:             }
18914:         }
18915:     }
18916: 
18917:     my @contexts = ('selfcreate');
18918:     @{$cancreate{'selfcreate'}} = ();
18919:     %{$cancreate{'emailusername'}} = ();
18920:     if (@types) {
18921:         @{$cancreate{'statustocreate'}} = ();
18922:     }
18923:     %{$cancreate{'selfcreateprocessing'}} = ();
18924:     %{$cancreate{'shibenv'}} = ();
18925:     %{$cancreate{'emailverified'}} = ();
18926:     %{$cancreate{'emailoptions'}} = ();
18927:     %{$cancreate{'emaildomain'}} = ();
18928:     my %selfcreatetypes = (
18929:                              sso   => 'users authenticated by institutional single sign on',
18930:                              login => 'users authenticated by institutional log-in',
18931:                              email => 'users verified by e-mail',
18932:                           );
18933: #
18934: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
18935: # is permitted.
18936: #
18937:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
18938: 
18939:     my (@statuses,%email_rule);
18940:     foreach my $item ('login','sso','email') {
18941:         if ($item eq 'email') {
18942:             if ($env{'form.cancreate_email'}) {
18943:                 if (@types) {
18944:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
18945:                     foreach my $status (@poss_statuses) {
18946:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
18947:                             push(@statuses,$status);
18948:                         }
18949:                     }
18950:                     $save_inststatus{'inststatusguest'} = \@statuses;
18951:                 } else {
18952:                     push(@statuses,'default');
18953:                 }
18954:                 if (@statuses) {
18955:                     my %curr_rule;
18956:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
18957:                         foreach my $type (@statuses) {
18958:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
18959:                         }
18960:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
18961:                         foreach my $type (@statuses) {
18962:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
18963:                         }
18964:                     }
18965:                     push(@{$cancreate{'selfcreate'}},'email');
18966:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
18967:                     my %curremaildom;
18968:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
18969:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
18970:                     }
18971:                     foreach my $type (@statuses) {
18972:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
18973:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
18974:                         }
18975:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
18976:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
18977:                         }
18978:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
18979: #
18980: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
18981: #
18982:                             my $chosen = $1;
18983:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
18984:                                 my $emaildom;
18985:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
18986:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
18987:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
18988:                                     if (ref($curremaildom{$type}) eq 'HASH') {
18989:                                         if (exists($curremaildom{$type}{$chosen})) {
18990:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
18991:                                                 push(@{$changes{'cancreate'}},'emaildomain');
18992:                                             }
18993:                                         } elsif ($emaildom ne '') {
18994:                                             push(@{$changes{'cancreate'}},'emaildomain');
18995:                                         }
18996:                                     } elsif ($emaildom ne '') {
18997:                                         push(@{$changes{'cancreate'}},'emaildomain');
18998:                                     } 
18999:                                 }
19000:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19001:                             } elsif ($chosen eq 'custom') {
19002:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
19003:                                 $email_rule{$type} = [];
19004:                                 if (ref($emailrules) eq 'HASH') {
19005:                                     foreach my $rule (@possemail_rules) {
19006:                                         if (exists($emailrules->{$rule})) {
19007:                                             push(@{$email_rule{$type}},$rule);
19008:                                         }
19009:                                     }
19010:                                 }
19011:                                 if (@{$email_rule{$type}}) {
19012:                                     $cancreate{'emailoptions'}{$type} = 'custom';
19013:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
19014:                                         if (@{$curr_rule{$type}} > 0) {
19015:                                             foreach my $rule (@{$curr_rule{$type}}) {
19016:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
19017:                                                     push(@{$changes{'email_rule'}},$type);
19018:                                                 }
19019:                                             }
19020:                                         }
19021:                                         foreach my $type (@{$email_rule{$type}}) {
19022:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
19023:                                                 push(@{$changes{'email_rule'}},$type);
19024:                                             }
19025:                                         }
19026:                                     } else {
19027:                                         push(@{$changes{'email_rule'}},$type);
19028:                                     }
19029:                                 }
19030:                             } else {
19031:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19032:                             }
19033:                         }
19034:                     }
19035:                     if (@types) {
19036:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19037:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
19038:                             if (@changed) {
19039:                                 push(@{$changes{'inststatus'}},'inststatusguest');
19040:                             }
19041:                         } else {
19042:                             push(@{$changes{'inststatus'}},'inststatusguest');
19043:                         }
19044:                     }
19045:                 } else {
19046:                     delete($env{'form.cancreate_email'});
19047:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19048:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19049:                             push(@{$changes{'inststatus'}},'inststatusguest');
19050:                         }
19051:                     }
19052:                 }
19053:             } else {
19054:                 $save_inststatus{'inststatusguest'} = [];
19055:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19056:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19057:                         push(@{$changes{'inststatus'}},'inststatusguest');
19058:                     }
19059:                 }
19060:             }
19061:         } else {
19062:             if ($env{'form.cancreate_'.$item}) {
19063:                 push(@{$cancreate{'selfcreate'}},$item);
19064:             }
19065:         }
19066:     }
19067:     my (%userinfo,%savecaptcha);
19068:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
19069: #
19070: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
19071: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
19072: #
19073: 
19074:     if ($env{'form.cancreate_email'}) {
19075:         push(@contexts,'emailusername');
19076:         if (@statuses) {
19077:             foreach my $type (@statuses) {
19078:                 if (ref($infofields) eq 'ARRAY') {
19079:                     foreach my $field (@{$infofields}) {
19080:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
19081:                             $cancreate{'emailusername'}{$type}{$field} = $1;
19082:                         }
19083:                     }
19084:                 }
19085:             }
19086:         }
19087: #
19088: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
19089: # queued requests for self-creation of account verified by e-mail.
19090: #
19091: 
19092:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
19093:         @approvalnotify = sort(@approvalnotify);
19094:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
19095:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19096:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
19097:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
19098:                     push(@{$changes{'cancreate'}},'notify');
19099:                 }
19100:             } else {
19101:                 if ($cancreate{'notify'}{'approval'}) {
19102:                     push(@{$changes{'cancreate'}},'notify');
19103:                 }
19104:             }
19105:         } elsif ($cancreate{'notify'}{'approval'}) {
19106:             push(@{$changes{'cancreate'}},'notify');
19107:         }
19108: 
19109:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
19110:     }
19111: #  
19112: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
19113: # institutional log-in.
19114: #
19115:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
19116:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
19117:                ($domdefaults{'auth_def'} eq 'localauth'))) {
19118:             $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.').' '.
19119:                           &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.');
19120:         }
19121:     }
19122:     my @fields = ('lastname','firstname','middlename','generation',
19123:                   'permanentemail','id');
19124:     my @shibfields = (@fields,'inststatus');
19125:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19126: #
19127: # Where usernames may created for institutional log-in and/or institutional single sign on:
19128: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
19129: # may self-create accounts 
19130: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
19131: # which the user may supply, if institutional data is unavailable.
19132: #
19133:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
19134:         if (@types) {
19135:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
19136:             push(@contexts,'statustocreate');
19137:             foreach my $type (@types) {
19138:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
19139:                 foreach my $field (@fields) {
19140:                     if (grep(/^\Q$field\E$/,@modifiable)) {
19141:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
19142:                     } else {
19143:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
19144:                     }
19145:                 }
19146:             }
19147:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
19148:                 foreach my $type (@types) {
19149:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
19150:                         foreach my $field (@fields) {
19151:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
19152:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
19153:                                 push(@{$changes{'selfcreate'}},$type);
19154:                                 last;
19155:                             }
19156:                         }
19157:                     }
19158:                 }
19159:             } else {
19160:                 foreach my $type (@types) {
19161:                     push(@{$changes{'selfcreate'}},$type);
19162:                 }
19163:             }
19164:         }
19165:         foreach my $field (@shibfields) {
19166:             if ($env{'form.shibenv_'.$field} ne '') {
19167:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
19168:             }
19169:         }
19170:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19171:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
19172:                 foreach my $field (@shibfields) {
19173:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
19174:                         push(@{$changes{'cancreate'}},'shibenv');
19175:                     }
19176:                 }
19177:             } else {
19178:                 foreach my $field (@shibfields) {
19179:                     if ($env{'form.shibenv_'.$field}) {
19180:                         push(@{$changes{'cancreate'}},'shibenv');
19181:                         last;
19182:                     }
19183:                 }
19184:             }
19185:         }
19186:     }
19187:     foreach my $item (@contexts) {
19188:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
19189:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
19190:                 if (ref($cancreate{$item}) eq 'ARRAY') {
19191:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
19192:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19193:                             push(@{$changes{'cancreate'}},$item);
19194:                         }
19195:                     }
19196:                 }
19197:             }
19198:             if (ref($cancreate{$item}) eq 'ARRAY') {
19199:                 foreach my $type (@{$cancreate{$item}}) {
19200:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
19201:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19202:                             push(@{$changes{'cancreate'}},$item);
19203:                         }
19204:                     }
19205:                 }
19206:             }
19207:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
19208:             if (ref($cancreate{$item}) eq 'HASH') {
19209:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
19210:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19211:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
19212:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19213:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19214:                                     push(@{$changes{'cancreate'}},$item);
19215:                                 }
19216:                             }
19217:                         }
19218:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19219:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19220:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19221:                                 push(@{$changes{'cancreate'}},$item);
19222:                             }
19223:                         }
19224:                     }
19225:                 }
19226:                 foreach my $type (keys(%{$cancreate{$item}})) {
19227:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19228:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19229:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19230:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19231:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19232:                                         push(@{$changes{'cancreate'}},$item);
19233:                                     }
19234:                                 }
19235:                             } else {
19236:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19237:                                     push(@{$changes{'cancreate'}},$item);
19238:                                 }
19239:                             }
19240:                         }
19241:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19242:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19243:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19244:                                 push(@{$changes{'cancreate'}},$item);
19245:                             }
19246:                         }
19247:                     }
19248:                 }
19249:             }
19250:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
19251:             if (ref($cancreate{$item}) eq 'ARRAY') {
19252:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
19253:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19254:                         push(@{$changes{'cancreate'}},$item);
19255:                     }
19256:                 }
19257:             }
19258:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19259:             if (ref($cancreate{$item}) eq 'HASH') {
19260:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19261:                     push(@{$changes{'cancreate'}},$item);
19262:                 }
19263:             }
19264:         } elsif ($item eq 'emailusername') {
19265:             if (ref($cancreate{$item}) eq 'HASH') {
19266:                 foreach my $type (keys(%{$cancreate{$item}})) {
19267:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19268:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19269:                             if ($cancreate{$item}{$type}{$field}) {
19270:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19271:                                     push(@{$changes{'cancreate'}},$item);
19272:                                 }
19273:                                 last;
19274:                             }
19275:                         }
19276:                     }
19277:                 }
19278:             }
19279:         }
19280:     }
19281: #
19282: # Populate %save_usercreate hash with updates to self-creation configuration.
19283: #
19284:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
19285:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
19286:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
19287:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
19288:     if (ref($cancreate{'notify'}) eq 'HASH') {
19289:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
19290:     }
19291:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
19292:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
19293:     }
19294:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
19295:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
19296:     }
19297:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
19298:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
19299:     }
19300:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
19301:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
19302:     }
19303:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19304:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
19305:     }
19306:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
19307:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
19308:     }
19309:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
19310:     $save_usercreate{'email_rule'} = \%email_rule;
19311: 
19312:     my %userconfig_hash = (
19313:             usercreation     => \%save_usercreate,
19314:             usermodification => \%save_usermodify,
19315:             inststatus       => \%save_inststatus,
19316:     );
19317: 
19318:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
19319:                                              $dom);
19320: #
19321: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
19322: #
19323:     if ($putresult eq 'ok') {
19324:         if (keys(%changes) > 0) {
19325:             $resulttext = &mt('Changes made:').'<ul>';
19326:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
19327:                 my %lt = &selfcreation_types();
19328:                 foreach my $type (@{$changes{'cancreate'}}) {
19329:                     my $chgtext = '';
19330:                     if ($type eq 'selfcreate') {
19331:                         if (@{$cancreate{$type}} == 0) {
19332:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
19333:                         } else {
19334:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
19335:                                         '<ul>';
19336:                             foreach my $case (@{$cancreate{$type}}) {
19337:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
19338:                             }
19339:                             $chgtext .= '</ul>';
19340:                             if (ref($cancreate{$type}) eq 'ARRAY') {
19341:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
19342:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19343:                                         if (@{$cancreate{'statustocreate'}} == 0) {
19344:                                             $chgtext .= '<span class="LC_warning">'.
19345:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
19346:                                                         '</span><br />';
19347:                                         }
19348:                                     }
19349:                                 }
19350:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
19351:                                     if (!@statuses) {
19352:                                         $chgtext .= '<span class="LC_warning">'.
19353:                                                     &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.").
19354:                                                     '</span><br />';
19355: 
19356:                                     }
19357:                                 }
19358:                             }
19359:                         }
19360:                     } elsif ($type eq 'shibenv') {
19361:                         if (keys(%{$cancreate{$type}}) == 0) {
19362:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
19363:                         } else {
19364:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
19365:                                         '<ul>';
19366:                             foreach my $field (@shibfields) {
19367:                                 next if ($cancreate{$type}{$field} eq '');
19368:                                 if ($field eq 'inststatus') {
19369:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
19370:                                 } else {
19371:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
19372:                                 }
19373:                             }
19374:                             $chgtext .= '</ul>';
19375:                         }
19376:                     } elsif ($type eq 'statustocreate') {
19377:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
19378:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
19379:                             if (@{$cancreate{'selfcreate'}} > 0) {
19380:                                 if (@{$cancreate{'statustocreate'}} == 0) {
19381:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
19382:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
19383:                                         $chgtext .= '<br />'.
19384:                                                     '<span class="LC_warning">'.
19385:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
19386:                                                     '</span>';
19387:                                     }
19388:                                 } elsif (keys(%usertypes) > 0) {
19389:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19390:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
19391:                                     } else {
19392:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
19393:                                     }
19394:                                     $chgtext .= '<ul>';
19395:                                     foreach my $case (@{$cancreate{$type}}) {
19396:                                         if ($case eq 'default') {
19397:                                             $chgtext .= '<li>'.$othertitle.'</li>';
19398:                                         } else {
19399:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
19400:                                         }
19401:                                     }
19402:                                     $chgtext .= '</ul>';
19403:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19404:                                         $chgtext .= '<span class="LC_warning">'.
19405:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
19406:                                                     '</span>';
19407:                                     }
19408:                                 }
19409:                             } else {
19410:                                 if (@{$cancreate{$type}} == 0) {
19411:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
19412:                                 } else {
19413:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
19414:                                 }
19415:                             }
19416:                             $chgtext .= '<br />';
19417:                         }
19418:                     } elsif ($type eq 'selfcreateprocessing') {
19419:                         my %choices = &Apache::lonlocal::texthash (
19420:                                                                     automatic => 'Automatic approval',
19421:                                                                     approval  => 'Queued for approval',
19422:                                                                   );
19423:                         if (@types) {
19424:                             if (@statuses) {
19425:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
19426:                                             '<ul>';
19427:                                 foreach my $status (@statuses) {
19428:                                     if ($status eq 'default') {
19429:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19430:                                     } else {
19431:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19432:                                     }
19433:                                 }
19434:                                 $chgtext .= '</ul>';
19435:                             }
19436:                         } else {
19437:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
19438:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
19439:                         }
19440:                     } elsif ($type eq 'emailverified') {
19441:                         my %options = &Apache::lonlocal::texthash (
19442:                                                                     all   => 'Same as e-mail',
19443:                                                                     first => 'Omit @domain',
19444:                                                                     free  => 'Free to choose',
19445:                                                                   );
19446:                         if (@types) {
19447:                             if (@statuses) {
19448:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
19449:                                             '<ul>';
19450:                                 foreach my $status (@statuses) {
19451:                                     if ($status eq 'default') {
19452:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19453:                                     } else {
19454:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19455:                                     }
19456:                                 }
19457:                                 $chgtext .= '</ul>';
19458:                             }
19459:                         } else {
19460:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
19461:                                             $options{$cancreate{'emailverified'}{'default'}});
19462:                         }
19463:                     } elsif ($type eq 'emailoptions') {
19464:                         my %options = &Apache::lonlocal::texthash (
19465:                                                                     any     => 'Any e-mail',
19466:                                                                     inst    => 'Institutional only',
19467:                                                                     noninst => 'Non-institutional only',
19468:                                                                     custom  => 'Custom restrictions',
19469:                                                                   );
19470:                         if (@types) {
19471:                             if (@statuses) {
19472:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
19473:                                             '<ul>';
19474:                                 foreach my $status (@statuses) {
19475:                                     if ($type eq 'default') {
19476:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19477:                                     } else {
19478:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19479:                                     }
19480:                                 }
19481:                                 $chgtext .= '</ul>';
19482:                             }
19483:                         } else {
19484:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
19485:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
19486:                             } else {
19487:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
19488:                                                 $options{$cancreate{'emailoptions'}{'default'}});
19489:                             }
19490:                         }
19491:                     } elsif ($type eq 'emaildomain') {
19492:                         my $output;
19493:                         if (@statuses) {
19494:                             foreach my $type (@statuses) {
19495:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
19496:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
19497:                                         if ($type eq 'default') {
19498:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19499:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19500:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19501:                                             } else {
19502:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
19503:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
19504:                                             }
19505:                                         } else {
19506:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19507:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19508:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19509:                                             } else {
19510:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
19511:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
19512:                                             }
19513:                                         }
19514:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
19515:                                         if ($type eq 'default') {
19516:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19517:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19518:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19519:                                             } else {
19520:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
19521:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
19522:                                             }
19523:                                         } else {
19524:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19525:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19526:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19527:                                             } else {
19528:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
19529:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
19530:                                             }
19531:                                         }
19532:                                     }
19533:                                 }
19534:                             }
19535:                         }
19536:                         if ($output ne '') {
19537:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
19538:                                         '<ul>'.$output.'</ul>';
19539:                         }
19540:                     } elsif ($type eq 'captcha') {
19541:                         if ($savecaptcha{$type} eq 'notused') {
19542:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
19543:                         } else {
19544:                             my %captchas = &captcha_phrases();
19545:                             if ($captchas{$savecaptcha{$type}}) {
19546:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
19547:                             } else {
19548:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
19549:                             }
19550:                         }
19551:                     } elsif ($type eq 'recaptchakeys') {
19552:                         my ($privkey,$pubkey);
19553:                         if (ref($savecaptcha{$type}) eq 'HASH') {
19554:                             $pubkey = $savecaptcha{$type}{'public'};
19555:                             $privkey = $savecaptcha{$type}{'private'};
19556:                         }
19557:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
19558:                         if (!$pubkey) {
19559:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
19560:                         } else {
19561:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
19562:                         }
19563:                         if (!$privkey) {
19564:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
19565:                         } else {
19566:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
19567:                         }
19568:                         $chgtext .= '</ul>';
19569:                     } elsif ($type eq 'recaptchaversion') {
19570:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
19571:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
19572:                         }
19573:                     } elsif ($type eq 'emailusername') {
19574:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
19575:                             if (@statuses) {
19576:                                 foreach my $type (@statuses) {
19577:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
19578:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
19579:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
19580:                                                     '<ul>';
19581:                                             foreach my $field (@{$infofields}) {
19582:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
19583:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
19584:                                                 }
19585:                                             }
19586:                                             $chgtext .= '</ul>';
19587:                                         } else {
19588:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19589:                                         }
19590:                                     } else {
19591:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19592:                                     }
19593:                                 }
19594:                             }
19595:                         }
19596:                     } elsif ($type eq 'notify') {
19597:                         my $numapprove = 0;
19598:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
19599:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
19600:                                 if ($cancreate{'notify'}{'approval'}) {
19601:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
19602:                                     $numapprove ++;
19603:                                 }
19604:                             }
19605:                         }
19606:                         unless ($numapprove) {
19607:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
19608:                         }
19609:                     }
19610:                     if ($chgtext) {
19611:                         $resulttext .= '<li>'.$chgtext.'</li>';
19612:                     }
19613:                 }
19614:             }
19615:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
19616:                 my ($emailrules,$emailruleorder) =
19617:                     &Apache::lonnet::inst_userrules($dom,'email');
19618:                 foreach my $type (@{$changes{'email_rule'}}) {
19619:                     if (ref($email_rule{$type}) eq 'ARRAY') {
19620:                         my $chgtext = '<ul>';
19621:                         foreach my $rule (@{$email_rule{$type}}) {
19622:                             if (ref($emailrules->{$rule}) eq 'HASH') {
19623:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
19624:                             }
19625:                         }
19626:                         $chgtext .= '</ul>';
19627:                         my $typename;
19628:                         if (@types) {
19629:                             if ($type eq 'default') {
19630:                                 $typename = $othertitle;
19631:                             } else {
19632:                                 $typename = $usertypes{$type};
19633:                             } 
19634:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
19635:                         }
19636:                         if (@{$email_rule{$type}} > 0) {
19637:                             $resulttext .= '<li>'.
19638:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
19639:                                                $usertypes{$type}).
19640:                                            $chgtext.
19641:                                            '</li>';
19642:                         } else {
19643:                             $resulttext .= '<li>'.
19644:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
19645:                                            '</li>'.
19646:                                            &mt('(Affiliation: [_1])',$typename);
19647:                         }
19648:                     }
19649:                 }
19650:             }
19651:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
19652:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
19653:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
19654:                         my $chgtext = '<ul>';
19655:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
19656:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
19657:                         }
19658:                         $chgtext .= '</ul>';
19659:                         $resulttext .= '<li>'.
19660:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
19661:                                           $chgtext.
19662:                                        '</li>';
19663:                     } else {
19664:                         $resulttext .= '<li>'.
19665:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
19666:                                        '</li>';
19667:                     }
19668:                 }
19669:             }
19670:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
19671:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
19672:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19673:                 foreach my $type (@{$changes{'selfcreate'}}) {
19674:                     my $typename = $type;
19675:                     if (keys(%usertypes) > 0) {
19676:                         if ($usertypes{$type} ne '') {
19677:                             $typename = $usertypes{$type};
19678:                         }
19679:                     }
19680:                     my @modifiable;
19681:                     $resulttext .= '<li>'.
19682:                                     &mt('Self-creation of account by users with status: [_1]',
19683:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
19684:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
19685:                     foreach my $field (@fields) {
19686:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
19687:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
19688:                         }
19689:                     }
19690:                     if (@modifiable > 0) {
19691:                         $resulttext .= join(', ',@modifiable);
19692:                     } else {
19693:                         $resulttext .= &mt('none');
19694:                     }
19695:                     $resulttext .= '</li>';
19696:                 }
19697:                 $resulttext .= '</ul></li>';
19698:             }
19699:             $resulttext .= '</ul>';
19700:             my $cachetime = 24*60*60;
19701:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
19702:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19703:             if (ref($lastactref) eq 'HASH') {
19704:                 $lastactref->{'domdefaults'} = 1;
19705:             }
19706:         } else {
19707:             $resulttext = &mt('No changes made to self-creation settings');
19708:         }
19709:     } else {
19710:         $resulttext = '<span class="LC_error">'.
19711:             &mt('An error occurred: [_1]',$putresult).'</span>';
19712:     }
19713:     if ($warningmsg ne '') {
19714:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
19715:     }
19716:     return $resulttext;
19717: }
19718: 
19719: sub process_captcha {
19720:     my ($container,$changes,$newsettings,$currsettings) = @_;
19721:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
19722:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
19723:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
19724:         $newsettings->{'captcha'} = 'original';
19725:     }
19726:     my %current;
19727:     if (ref($currsettings) eq 'HASH') {
19728:         %current = %{$currsettings};
19729:     }
19730:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
19731:         if ($container eq 'cancreate') {
19732:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19733:                 push(@{$changes->{'cancreate'}},'captcha');
19734:             } elsif (!defined($changes->{'cancreate'})) {
19735:                 $changes->{'cancreate'} = ['captcha'];
19736:             }
19737:         } elsif ($container eq 'passwords') {
19738:             $changes->{'reset'} = 1;
19739:         } else {
19740:             $changes->{'captcha'} = 1;
19741:         }
19742:     }
19743:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
19744:     if ($newsettings->{'captcha'} eq 'recaptcha') {
19745:         $newpub = $env{'form.'.$container.'_recaptchapub'};
19746:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
19747:         $newpub =~ s/[^\w\-]//g;
19748:         $newpriv =~ s/[^\w\-]//g;
19749:         $newsettings->{'recaptchakeys'} = {
19750:                                              public  => $newpub,
19751:                                              private => $newpriv,
19752:                                           };
19753:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
19754:         $newversion =~ s/\D//g;
19755:         if ($newversion ne '2') {
19756:             $newversion = 1;
19757:         }
19758:         $newsettings->{'recaptchaversion'} = $newversion;
19759:     }
19760:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
19761:         $currpub = $current{'recaptchakeys'}{'public'};
19762:         $currpriv = $current{'recaptchakeys'}{'private'};
19763:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
19764:             $newsettings->{'recaptchakeys'} = {
19765:                                                  public  => '',
19766:                                                  private => '',
19767:                                               }
19768:         }
19769:     }
19770:     if ($current{'captcha'} eq 'recaptcha') {
19771:         $currversion = $current{'recaptchaversion'};
19772:         if ($currversion ne '2') {
19773:             $currversion = 1;
19774:         }
19775:     }
19776:     if ($currversion ne $newversion) {
19777:         if ($container eq 'cancreate') {
19778:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19779:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
19780:             } elsif (!defined($changes->{'cancreate'})) {
19781:                 $changes->{'cancreate'} = ['recaptchaversion'];
19782:             }
19783:         } elsif ($container eq 'passwords') {
19784:             $changes->{'reset'} = 1;
19785:         } else {
19786:             $changes->{'recaptchaversion'} = 1;
19787:         }
19788:     }
19789:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
19790:         if ($container eq 'cancreate') {
19791:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19792:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
19793:             } elsif (!defined($changes->{'cancreate'})) {
19794:                 $changes->{'cancreate'} = ['recaptchakeys'];
19795:             }
19796:         } elsif ($container eq 'passwords') {
19797:             $changes->{'reset'} = 1;
19798:         } else {
19799:             $changes->{'recaptchakeys'} = 1;
19800:         }
19801:     }
19802:     return;
19803: }
19804: 
19805: sub modify_usermodification {
19806:     my ($dom,%domconfig) = @_;
19807:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
19808:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
19809:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
19810:             if ($key eq 'selfcreate') {
19811:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
19812:             } else {  
19813:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
19814:             }
19815:         }
19816:     }
19817:     my @contexts = ('author','course');
19818:     my %context_title = (
19819:                            author => 'In author context',
19820:                            course => 'In course context',
19821:                         );
19822:     my @fields = ('lastname','firstname','middlename','generation',
19823:                   'permanentemail','id');
19824:     my %roles = (
19825:                   author => ['ca','aa'],
19826:                   course => ['st','ep','ta','in','cr'],
19827:                 );
19828:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19829:     foreach my $context (@contexts) {
19830:         foreach my $role (@{$roles{$context}}) {
19831:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
19832:             foreach my $item (@fields) {
19833:                 if (grep(/^\Q$item\E$/,@modifiable)) {
19834:                     $modifyhash{$context}{$role}{$item} = 1;
19835:                 } else {
19836:                     $modifyhash{$context}{$role}{$item} = 0;
19837:                 }
19838:             }
19839:         }
19840:         if (ref($curr_usermodification{$context}) eq 'HASH') {
19841:             foreach my $role (@{$roles{$context}}) {
19842:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
19843:                     foreach my $field (@fields) {
19844:                         if ($modifyhash{$context}{$role}{$field} ne 
19845:                                 $curr_usermodification{$context}{$role}{$field}) {
19846:                             push(@{$changes{$context}},$role);
19847:                             last;
19848:                         }
19849:                     }
19850:                 }
19851:             }
19852:         } else {
19853:             foreach my $context (@contexts) {
19854:                 foreach my $role (@{$roles{$context}}) {
19855:                     push(@{$changes{$context}},$role);
19856:                 }
19857:             }
19858:         }
19859:     }
19860:     my %usermodification_hash =  (
19861:                                    usermodification => \%modifyhash,
19862:                                  );
19863:     my $putresult = &Apache::lonnet::put_dom('configuration',
19864:                                              \%usermodification_hash,$dom);
19865:     if ($putresult eq 'ok') {
19866:         if (keys(%changes) > 0) {
19867:             $resulttext = &mt('Changes made: ').'<ul>';
19868:             foreach my $context (@contexts) {
19869:                 if (ref($changes{$context}) eq 'ARRAY') {
19870:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
19871:                     if (ref($changes{$context}) eq 'ARRAY') {
19872:                         foreach my $role (@{$changes{$context}}) {
19873:                             my $rolename;
19874:                             if ($role eq 'cr') {
19875:                                 $rolename = &mt('Custom');
19876:                             } else {
19877:                                 $rolename = &Apache::lonnet::plaintext($role);
19878:                             }
19879:                             my @modifiable;
19880:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
19881:                             foreach my $field (@fields) {
19882:                                 if ($modifyhash{$context}{$role}{$field}) {
19883:                                     push(@modifiable,$fieldtitles{$field});
19884:                                 }
19885:                             }
19886:                             if (@modifiable > 0) {
19887:                                 $resulttext .= join(', ',@modifiable);
19888:                             } else {
19889:                                 $resulttext .= &mt('none'); 
19890:                             }
19891:                             $resulttext .= '</li>';
19892:                         }
19893:                         $resulttext .= '</ul></li>';
19894:                     }
19895:                 }
19896:             }
19897:             $resulttext .= '</ul>';
19898:         } else {
19899:             $resulttext = &mt('No changes made to user modification settings');
19900:         }
19901:     } else {
19902:         $resulttext = '<span class="LC_error">'.
19903:             &mt('An error occurred: [_1]',$putresult).'</span>';
19904:     }
19905:     return $resulttext;
19906: }
19907: 
19908: sub modify_defaults {
19909:     my ($dom,$lastactref,%domconfig) = @_;
19910:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
19911:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19912:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
19913:                  'portal_def');
19914:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
19915:     foreach my $item (@items) {
19916:         $newvalues{$item} = $env{'form.'.$item};
19917:         if ($item eq 'auth_def') {
19918:             if ($newvalues{$item} ne '') {
19919:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
19920:                     push(@errors,$item);
19921:                 }
19922:             }
19923:         } elsif ($item eq 'lang_def') {
19924:             if ($newvalues{$item} ne '') {
19925:                 if ($newvalues{$item} =~ /^(\w+)/) {
19926:                     my $langcode = $1;
19927:                     if ($langcode ne 'x_chef') {
19928:                         if (code2language($langcode) eq '') {
19929:                             push(@errors,$item);
19930:                         }
19931:                     }
19932:                 } else {
19933:                     push(@errors,$item);
19934:                 }
19935:             }
19936:         } elsif ($item eq 'timezone_def') {
19937:             if ($newvalues{$item} ne '') {
19938:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
19939:                     push(@errors,$item);   
19940:                 }
19941:             }
19942:         } elsif ($item eq 'datelocale_def') {
19943:             if ($newvalues{$item} ne '') {
19944:                 my @datelocale_ids = DateTime::Locale->ids();
19945:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
19946:                     push(@errors,$item);
19947:                 }
19948:             }
19949:         } elsif ($item eq 'portal_def') {
19950:             if ($newvalues{$item} ne '') {
19951:                 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])\/?$/) {
19952:                     push(@errors,$item);
19953:                 }
19954:             }
19955:         }
19956:         if (grep(/^\Q$item\E$/,@errors)) {
19957:             $newvalues{$item} = $domdefaults{$item};
19958:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
19959:             $changes{$item} = 1;
19960:         }
19961:         $domdefaults{$item} = $newvalues{$item};
19962:     }
19963:     my %staticdefaults = (
19964:                            'intauth_cost'   => 10,
19965:                            'intauth_check'  => 0,
19966:                            'intauth_switch' => 0,
19967:                          );
19968:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
19969:         if (exists($domdefaults{$item})) {
19970:             $newvalues{$item} = $domdefaults{$item};
19971:         } else {
19972:             $newvalues{$item} = $staticdefaults{$item};
19973:         }
19974:     }
19975:     my %defaults_hash = (
19976:                          defaults => \%newvalues,
19977:                         );
19978:     my $title = &defaults_titles();
19979: 
19980:     my $currinststatus;
19981:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
19982:         $currinststatus = $domconfig{'inststatus'};
19983:     } else {
19984:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
19985:         $currinststatus = {
19986:                              inststatustypes => $usertypes,
19987:                              inststatusorder => $types,
19988:                              inststatusguest => [],
19989:                           };
19990:     }
19991:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
19992:     my @allpos;
19993:     my %alltypes;
19994:     my @inststatusguest;
19995:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
19996:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
19997:             unless (grep(/^\Q$type\E$/,@todelete)) {
19998:                 push(@inststatusguest,$type);
19999:             }
20000:         }
20001:     }
20002:     my ($currtitles,$currorder);
20003:     if (ref($currinststatus) eq 'HASH') {
20004:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
20005:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
20006:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
20007:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
20008:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
20009:                     }
20010:                 }
20011:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
20012:                     my $position = $env{'form.inststatus_pos_'.$type};
20013:                     $position =~ s/\D+//g;
20014:                     $allpos[$position] = $type;
20015:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
20016:                     $alltypes{$type} =~ s/`//g;
20017:                 }
20018:             }
20019:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
20020:             $currtitles =~ s/,$//;
20021:         }
20022:     }
20023:     if ($env{'form.addinststatus'}) {
20024:         my $newtype = $env{'form.addinststatus'};
20025:         $newtype =~ s/\W//g;
20026:         unless (exists($alltypes{$newtype})) {
20027:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
20028:             $alltypes{$newtype} =~ s/`//g; 
20029:             my $position = $env{'form.addinststatus_pos'};
20030:             $position =~ s/\D+//g;
20031:             if ($position ne '') {
20032:                 $allpos[$position] = $newtype;
20033:             }
20034:         }
20035:     }
20036:     my @orderedstatus;
20037:     foreach my $type (@allpos) {
20038:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
20039:             push(@orderedstatus,$type);
20040:         }
20041:     }
20042:     foreach my $type (keys(%alltypes)) {
20043:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
20044:             delete($alltypes{$type});
20045:         }
20046:     }
20047:     $defaults_hash{'inststatus'} = {
20048:                                      inststatustypes => \%alltypes,
20049:                                      inststatusorder => \@orderedstatus,
20050:                                      inststatusguest => \@inststatusguest,
20051:                                    };
20052:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
20053:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
20054:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
20055:         }
20056:     }
20057:     if ($currorder ne join(',',@orderedstatus)) {
20058:         $changes{'inststatus'}{'inststatusorder'} = 1;
20059:     }
20060:     my $newtitles;
20061:     foreach my $item (@orderedstatus) {
20062:         $newtitles .= $alltypes{$item}.',';
20063:     }
20064:     $newtitles =~ s/,$//;
20065:     if ($currtitles ne $newtitles) {
20066:         $changes{'inststatus'}{'inststatustypes'} = 1;
20067:     }
20068:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
20069:                                              $dom);
20070:     if ($putresult eq 'ok') {
20071:         if (keys(%changes) > 0) {
20072:             $resulttext = &mt('Changes made:').'<ul>';
20073:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
20074:             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";
20075:             foreach my $item (sort(keys(%changes))) {
20076:                 if ($item eq 'inststatus') {
20077:                     if (ref($changes{'inststatus'}) eq 'HASH') {
20078:                         if (@orderedstatus) {
20079:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
20080:                             foreach my $type (@orderedstatus) { 
20081:                                 $resulttext .= $alltypes{$type}.', ';
20082:                             }
20083:                             $resulttext =~ s/, $//;
20084:                             $resulttext .= '</li>';
20085:                         } else {
20086:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
20087:                         }
20088:                     }
20089:                 } else {
20090:                     my $value = $env{'form.'.$item};
20091:                     if ($value eq '') {
20092:                         $value = &mt('none');
20093:                     } elsif ($item eq 'auth_def') {
20094:                         my %authnames = &authtype_names();
20095:                         my %shortauth = (
20096:                                           internal   => 'int',
20097:                                           krb4       => 'krb4',
20098:                                           krb5       => 'krb5',
20099:                                           localauth  => 'loc',
20100:                                           lti        => 'lti',
20101:                         );
20102:                         $value = $authnames{$shortauth{$value}};
20103:                     }
20104:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
20105:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
20106:                 }
20107:             }
20108:             $resulttext .= '</ul>';
20109:             $mailmsgtext .= "\n";
20110:             my $cachetime = 24*60*60;
20111:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20112:             if (ref($lastactref) eq 'HASH') {
20113:                 $lastactref->{'domdefaults'} = 1;
20114:             }
20115:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
20116:                 my $notify = 1;
20117:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
20118:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
20119:                         $notify = 0;
20120:                     }
20121:                 }
20122:                 if ($notify) {
20123:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
20124:                                                "LON-CAPA Domain Settings Change - $dom",
20125:                                                $mailmsgtext);
20126:                 }
20127:             }
20128:         } else {
20129:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
20130:         }
20131:     } else {
20132:         $resulttext = '<span class="LC_error">'.
20133:             &mt('An error occurred: [_1]',$putresult).'</span>';
20134:     }
20135:     if (@errors > 0) {
20136:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
20137:         foreach my $item (@errors) {
20138:             $resulttext .= ' "'.$title->{$item}.'",';
20139:         }
20140:         $resulttext =~ s/,$//;
20141:     }
20142:     return $resulttext;
20143: }
20144: 
20145: sub modify_scantron {
20146:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20147:     my ($resulttext,%confhash,%changes,$errors);
20148:     my $custom = 'custom.tab';
20149:     my $default = 'default.tab';
20150:     my $servadm = $r->dir_config('lonAdmEMail');
20151:     my ($configuserok,$author_ok,$switchserver) =
20152:         &config_check($dom,$confname,$servadm);
20153:     if ($env{'form.scantronformat.filename'} ne '') {
20154:         my $error;
20155:         if ($configuserok eq 'ok') {
20156:             if ($switchserver) {
20157:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
20158:             } else {
20159:                 if ($author_ok eq 'ok') {
20160:                     my ($result,$scantronurl) =
20161:                         &publishlogo($r,'upload','scantronformat',$dom,
20162:                                      $confname,'scantron','','',$custom);
20163:                     if ($result eq 'ok') {
20164:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
20165:                         $changes{'scantronformat'} = 1;
20166:                     } else {
20167:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
20168:                     }
20169:                 } else {
20170:                     $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);
20171:                 }
20172:             }
20173:         } else {
20174:             $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);
20175:         }
20176:         if ($error) {
20177:             &Apache::lonnet::logthis($error);
20178:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
20179:         }
20180:     }
20181:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20182:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
20183:             if ($env{'form.scantronformat_del'}) {
20184:                 $confhash{'scantron'}{'scantronformat'} = '';
20185:                 $changes{'scantronformat'} = 1;
20186:             } else {
20187:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
20188:             }
20189:         }
20190:     }
20191:     my @options = ('hdr','pad','rem');
20192:     my @fields = &scantroncsv_fields();
20193:     my %titles = &scantronconfig_titles();
20194:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
20195:     my ($newdat,$currdat,%newcol,%currcol);
20196:     if (grep(/^dat$/,@formats)) {
20197:         $confhash{'scantron'}{config}{dat} = 1;
20198:         $newdat = 1;
20199:     } else {
20200:         $newdat = 0;
20201:     }
20202:     if (grep(/^csv$/,@formats)) {
20203:         my %bynum;
20204:         foreach my $field (@fields) {
20205:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
20206:                 my $posscol = $1;
20207:                 if (($posscol < 20) && (!$bynum{$posscol})) {
20208:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
20209:                     $bynum{$posscol} = $field;
20210:                     $newcol{$field} = $posscol;
20211:                 }
20212:             }
20213:         }
20214:         if (keys(%newcol)) {
20215:             foreach my $option (@options) {
20216:                 if ($env{'form.scantroncsv_'.$option}) {
20217:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
20218:                 }
20219:             }
20220:         }
20221:     }
20222:     $currdat = 1;
20223:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20224:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
20225:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
20226:                 $currdat = 0;
20227:             }
20228:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20229:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20230:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
20231:                 }
20232:             }
20233:         }
20234:     }
20235:     if ($currdat != $newdat) {
20236:         $changes{'config'} = 1;
20237:     } else {
20238:         foreach my $field (@fields) {
20239:             if ($currcol{$field} ne '') {
20240:                 if ($currcol{$field} ne $newcol{$field}) {
20241:                     $changes{'config'} = 1;
20242:                     last;
20243:                 }
20244:             } elsif ($newcol{$field} ne '') {
20245:                 $changes{'config'} = 1;
20246:                 last;
20247:             }
20248:         }
20249:     }
20250:     if (keys(%confhash) > 0) {
20251:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
20252:                                                  $dom);
20253:         if ($putresult eq 'ok') {
20254:             if (keys(%changes) > 0) {
20255:                 if (ref($confhash{'scantron'}) eq 'HASH') {
20256:                     $resulttext = &mt('Changes made:').'<ul>';
20257:                     if ($changes{'scantronformat'}) {
20258:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
20259:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
20260:                         } else {
20261:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
20262:                         }
20263:                     }
20264:                     if ($changes{'config'}) {
20265:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
20266:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
20267:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
20268:                             }
20269:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20270:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20271:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
20272:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
20273:                                         foreach my $field (@fields) {
20274:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
20275:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
20276:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
20277:                                             }
20278:                                         }
20279:                                         $resulttext .= '</ul></li>';
20280:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
20281:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
20282:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
20283:                                                 foreach my $option (@options) {
20284:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
20285:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
20286:                                                     }
20287:                                                 }
20288:                                                 $resulttext .= '</ul></li>';
20289:                                             }
20290:                                         }
20291:                                     }
20292:                                 }
20293:                             }
20294:                         } else {
20295:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
20296:                         }
20297:                     }
20298:                     $resulttext .= '</ul>';
20299:                 } else {
20300:                     $resulttext = &mt('Changes made to bubblesheet format file.');
20301:                 }
20302:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
20303:                 if (ref($lastactref) eq 'HASH') {
20304:                     $lastactref->{'domainconfig'} = 1;
20305:                 }
20306:             } else {
20307:                 $resulttext = &mt('No changes made to bubblesheet format settings');
20308:             }
20309:         } else {
20310:             $resulttext = '<span class="LC_error">'.
20311:                 &mt('An error occurred: [_1]',$putresult).'</span>';
20312:         }
20313:     } else {
20314:         $resulttext = &mt('No changes made to bubblesheet format file'); 
20315:     }
20316:     if ($errors) {
20317:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
20318:                        $errors.'</ul></p>';
20319:     }
20320:     return $resulttext;
20321: }
20322: 
20323: sub modify_coursecategories {
20324:     my ($dom,$lastactref,%domconfig) = @_;
20325:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
20326:         $cathash);
20327:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
20328:     my @catitems = ('unauth','auth');
20329:     my @cattypes = ('std','domonly','codesrch','none');
20330:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20331:         $cathash = $domconfig{'coursecategories'}{'cats'};
20332:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
20333:             $changes{'togglecats'} = 1;
20334:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
20335:         }
20336:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
20337:             $changes{'categorize'} = 1;
20338:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
20339:         }
20340:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
20341:             $changes{'togglecatscomm'} = 1;
20342:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
20343:         }
20344:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
20345:             $changes{'categorizecomm'} = 1;
20346:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
20347: 
20348:         }
20349:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
20350:             $changes{'togglecatsplace'} = 1;
20351:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
20352:         }
20353:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
20354:             $changes{'categorizeplace'} = 1;
20355:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
20356:         }
20357:         foreach my $item (@catitems) {
20358:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20359:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
20360:                     $changes{$item} = 1;
20361:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20362:                 }
20363:             }
20364:         }
20365:     } else {
20366:         $changes{'togglecats'} = 1;
20367:         $changes{'categorize'} = 1;
20368:         $changes{'togglecatscomm'} = 1;
20369:         $changes{'categorizecomm'} = 1;
20370:         $changes{'togglecatsplace'} = 1;
20371:         $changes{'categorizeplace'} = 1;
20372:         $domconfig{'coursecategories'} = {
20373:                                              togglecats => $env{'form.togglecats'},
20374:                                              categorize => $env{'form.categorize'},
20375:                                              togglecatscomm => $env{'form.togglecatscomm'},
20376:                                              categorizecomm => $env{'form.categorizecomm'},
20377:                                              togglecatsplace => $env{'form.togglecatsplace'},
20378:                                              categorizeplace => $env{'form.categorizeplace'},
20379:                                          };
20380:         foreach my $item (@catitems) {
20381:             if ($env{'form.coursecat_'.$item} ne 'std') {
20382:                 $changes{$item} = 1;
20383:             }
20384:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20385:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20386:             }
20387:         }
20388:     }
20389:     if (ref($cathash) eq 'HASH') {
20390:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
20391:             push (@deletecategory,'instcode::0');
20392:         }
20393:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
20394:             push(@deletecategory,'communities::0');
20395:         }
20396:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
20397:             push(@deletecategory,'placement::0');
20398:         }
20399:     }
20400:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
20401:     if (ref($cathash) eq 'HASH') {
20402:         if (@deletecategory > 0) {
20403:             #FIXME Need to remove category from all courses using a deleted category 
20404:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
20405:             foreach my $item (@deletecategory) {
20406:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
20407:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
20408:                     $deletions{$item} = 1;
20409:                     &recurse_cat_deletes($item,$cathash,\%deletions);
20410:                 }
20411:             }
20412:         }
20413:         foreach my $item (keys(%{$cathash})) {
20414:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
20415:             if ($cathash->{$item} ne $env{'form.'.$item}) {
20416:                 $reorderings{$item} = 1;
20417:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
20418:             }
20419:             if ($env{'form.addcategory_name_'.$item} ne '') {
20420:                 my $newcat = $env{'form.addcategory_name_'.$item};
20421:                 my $newdepth = $depth+1;
20422:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20423:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
20424:                 $adds{$newitem} = 1; 
20425:             }
20426:             if ($env{'form.subcat_'.$item} ne '') {
20427:                 my $newcat = $env{'form.subcat_'.$item};
20428:                 my $newdepth = $depth+1;
20429:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20430:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
20431:                 $adds{$newitem} = 1;
20432:             }
20433:         }
20434:     }
20435:     if ($env{'form.instcode'} eq '1') {
20436:         if (ref($cathash) eq 'HASH') {
20437:             my $newitem = 'instcode::0';
20438:             if ($cathash->{$newitem} eq '') {  
20439:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20440:                 $adds{$newitem} = 1;
20441:             }
20442:         } else {
20443:             my $newitem = 'instcode::0';
20444:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20445:             $adds{$newitem} = 1;
20446:         }
20447:     }
20448:     if ($env{'form.communities'} eq '1') {
20449:         if (ref($cathash) eq 'HASH') {
20450:             my $newitem = 'communities::0';
20451:             if ($cathash->{$newitem} eq '') {
20452:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20453:                 $adds{$newitem} = 1;
20454:             }
20455:         } else {
20456:             my $newitem = 'communities::0';
20457:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20458:             $adds{$newitem} = 1;
20459:         }
20460:     }
20461:     if ($env{'form.placement'} eq '1') {
20462:         if (ref($cathash) eq 'HASH') {
20463:             my $newitem = 'placement::0';
20464:             if ($cathash->{$newitem} eq '') {
20465:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20466:                 $adds{$newitem} = 1;
20467:             }
20468:         } else {
20469:             my $newitem = 'placement::0';
20470:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20471:             $adds{$newitem} = 1;
20472:         }
20473:     }
20474:     if ($env{'form.addcategory_name'} ne '') {
20475:         if (($env{'form.addcategory_name'} ne 'instcode') &&
20476:             ($env{'form.addcategory_name'} ne 'communities') &&
20477:             ($env{'form.addcategory_name'} ne 'placement')) {
20478:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
20479:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
20480:             $adds{$newitem} = 1;
20481:         }
20482:     }
20483:     my $putresult;
20484:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20485:         if (keys(%deletions) > 0) {
20486:             foreach my $key (keys(%deletions)) {
20487:                 if ($predelallitems{$key} ne '') {
20488:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
20489:                 }
20490:             }
20491:         }
20492:         my (@chkcats,@chktrails,%chkallitems);
20493:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
20494:         if (ref($chkcats[0]) eq 'ARRAY') {
20495:             my $depth = 0;
20496:             my $chg = 0;
20497:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
20498:                 my $name = $chkcats[0][$i];
20499:                 my $item;
20500:                 if ($name eq '') {
20501:                     $chg ++;
20502:                 } else {
20503:                     $item = &escape($name).'::0';
20504:                     if ($chg) {
20505:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
20506:                     }
20507:                     $depth ++; 
20508:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
20509:                     $depth --;
20510:                 }
20511:             }
20512:         }
20513:     }
20514:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20515:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
20516:         if ($putresult eq 'ok') {
20517:             my %title = (
20518:                          togglecats     => 'Show/Hide a course in catalog',
20519:                          categorize     => 'Assign a category to a course',
20520:                          togglecatscomm => 'Show/Hide a community in catalog',
20521:                          categorizecomm => 'Assign a category to a community',
20522:                         );
20523:             my %level = (
20524:                          dom  => 'set in Domain ("Modify Course/Community")',
20525:                          crs  => 'set in Course ("Course Configuration")',
20526:                          comm => 'set in Community ("Community Configuration")',
20527:                          none     => 'No catalog',
20528:                          std      => 'Standard catalog',
20529:                          domonly  => 'Domain-only catalog',
20530:                          codesrch => 'Code search form',
20531:                         );
20532:             $resulttext = &mt('Changes made:').'<ul>';
20533:             if ($changes{'togglecats'}) {
20534:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
20535:             }
20536:             if ($changes{'categorize'}) {
20537:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
20538:             }
20539:             if ($changes{'togglecatscomm'}) {
20540:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
20541:             }
20542:             if ($changes{'categorizecomm'}) {
20543:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
20544:             }
20545:             if ($changes{'unauth'}) {
20546:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
20547:             }
20548:             if ($changes{'auth'}) {
20549:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
20550:             }
20551:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20552:                 my $cathash;
20553:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20554:                     $cathash = $domconfig{'coursecategories'}{'cats'};
20555:                 } else {
20556:                     $cathash = {};
20557:                 } 
20558:                 my (@cats,@trails,%allitems);
20559:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
20560:                 if (keys(%deletions) > 0) {
20561:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
20562:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
20563:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
20564:                     }
20565:                     $resulttext .= '</ul></li>';
20566:                 }
20567:                 if (keys(%reorderings) > 0) {
20568:                     my %sort_by_trail;
20569:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
20570:                     foreach my $key (keys(%reorderings)) {
20571:                         if ($allitems{$key} ne '') {
20572:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20573:                         }
20574:                     }
20575:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20576:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20577:                     }
20578:                     $resulttext .= '</ul></li>';
20579:                 }
20580:                 if (keys(%adds) > 0) {
20581:                     my %sort_by_trail;
20582:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
20583:                     foreach my $key (keys(%adds)) {
20584:                         if ($allitems{$key} ne '') {
20585:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20586:                         }
20587:                     }
20588:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20589:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20590:                     }
20591:                     $resulttext .= '</ul></li>';
20592:                 }
20593:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
20594:                 if (ref($lastactref) eq 'HASH') {
20595:                     $lastactref->{'cats'} = 1;
20596:                 }
20597:             }
20598:             $resulttext .= '</ul>';
20599:             if ($changes{'unauth'} || $changes{'auth'}) {
20600:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20601:                 if ($changes{'auth'}) {
20602:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
20603:                 }
20604:                 if ($changes{'unauth'}) {
20605:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
20606:                 }
20607:                 my $cachetime = 24*60*60;
20608:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20609:                 if (ref($lastactref) eq 'HASH') {
20610:                     $lastactref->{'domdefaults'} = 1;
20611:                 }
20612:             }
20613:         } else {
20614:             $resulttext = '<span class="LC_error">'.
20615:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20616:         }
20617:     } else {
20618:         $resulttext = &mt('No changes made to course and community categories');
20619:     }
20620:     return $resulttext;
20621: }
20622: 
20623: sub modify_serverstatuses {
20624:     my ($dom,%domconfig) = @_;
20625:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
20626:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
20627:         %currserverstatus = %{$domconfig{'serverstatuses'}};
20628:     }
20629:     my @pages = &serverstatus_pages();
20630:     foreach my $type (@pages) {
20631:         $newserverstatus{$type}{'namedusers'} = '';
20632:         $newserverstatus{$type}{'machines'} = '';
20633:         if (defined($env{'form.'.$type.'_namedusers'})) {
20634:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
20635:             my @okusers;
20636:             foreach my $user (@users) {
20637:                 my ($uname,$udom) = split(/:/,$user);
20638:                 if (($udom =~ /^$match_domain$/) &&   
20639:                     (&Apache::lonnet::domain($udom)) &&
20640:                     ($uname =~ /^$match_username$/)) {
20641:                     if (!grep(/^\Q$user\E/,@okusers)) {
20642:                         push(@okusers,$user);
20643:                     }
20644:                 }
20645:             }
20646:             if (@okusers > 0) {
20647:                  @okusers = sort(@okusers);
20648:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
20649:             }
20650:         }
20651:         if (defined($env{'form.'.$type.'_machines'})) {
20652:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
20653:             my @okmachines;
20654:             foreach my $ip (@machines) {
20655:                 my @parts = split(/\./,$ip);
20656:                 next if (@parts < 4);
20657:                 my $badip = 0;
20658:                 for (my $i=0; $i<4; $i++) {
20659:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
20660:                         $badip = 1;
20661:                         last;
20662:                     }
20663:                 }
20664:                 if (!$badip) {
20665:                     push(@okmachines,$ip);     
20666:                 }
20667:             }
20668:             @okmachines = sort(@okmachines);
20669:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
20670:         }
20671:     }
20672:     my %serverstatushash =  (
20673:                                 serverstatuses => \%newserverstatus,
20674:                             );
20675:     foreach my $type (@pages) {
20676:         foreach my $setting ('namedusers','machines') {
20677:             my (@current,@new);
20678:             if (ref($currserverstatus{$type}) eq 'HASH') {
20679:                 if ($currserverstatus{$type}{$setting} ne '') { 
20680:                     @current = split(/,/,$currserverstatus{$type}{$setting});
20681:                 }
20682:             }
20683:             if ($newserverstatus{$type}{$setting} ne '') {
20684:                 @new = split(/,/,$newserverstatus{$type}{$setting});
20685:             }
20686:             if (@current > 0) {
20687:                 if (@new > 0) {
20688:                     foreach my $item (@current) {
20689:                         if (!grep(/^\Q$item\E$/,@new)) {
20690:                             $changes{$type}{$setting} = 1;
20691:                             last;
20692:                         }
20693:                     }
20694:                     foreach my $item (@new) {
20695:                         if (!grep(/^\Q$item\E$/,@current)) {
20696:                             $changes{$type}{$setting} = 1;
20697:                             last;
20698:                         }
20699:                     }
20700:                 } else {
20701:                     $changes{$type}{$setting} = 1;
20702:                 }
20703:             } elsif (@new > 0) {
20704:                 $changes{$type}{$setting} = 1;
20705:             }
20706:         }
20707:     }
20708:     if (keys(%changes) > 0) {
20709:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
20710:         my $putresult = &Apache::lonnet::put_dom('configuration',
20711:                                                  \%serverstatushash,$dom);
20712:         if ($putresult eq 'ok') {
20713:             $resulttext .= &mt('Changes made:').'<ul>';
20714:             foreach my $type (@pages) {
20715:                 if (ref($changes{$type}) eq 'HASH') {
20716:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
20717:                     if ($changes{$type}{'namedusers'}) {
20718:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
20719:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
20720:                         } else {
20721:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
20722:                         }
20723:                     }
20724:                     if ($changes{$type}{'machines'}) {
20725:                         if ($newserverstatus{$type}{'machines'} eq '') {
20726:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
20727:                         } else {
20728:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
20729:                         }
20730: 
20731:                     }
20732:                     $resulttext .= '</ul></li>';
20733:                 }
20734:             }
20735:             $resulttext .= '</ul>';
20736:         } else {
20737:             $resulttext = '<span class="LC_error">'.
20738:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
20739: 
20740:         }
20741:     } else {
20742:         $resulttext = &mt('No changes made to access to server status pages');
20743:     }
20744:     return $resulttext;
20745: }
20746: 
20747: sub modify_helpsettings {
20748:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20749:     my ($resulttext,$errors,%changes,%helphash);
20750:     my %defaultchecked = ('submitbugs' => 'on');
20751:     my @offon = ('off','on');
20752:     my @toggles = ('submitbugs');
20753:     my %current = ('submitbugs' => '',
20754:                    'adhoc'      => {},
20755:                   );
20756:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
20757:         %current = %{$domconfig{'helpsettings'}};
20758:     }
20759:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20760:     foreach my $item (@toggles) {
20761:         if ($defaultchecked{$item} eq 'on') { 
20762:             if ($current{$item} eq '') {
20763:                 if ($env{'form.'.$item} eq '0') {
20764:                     $changes{$item} = 1;
20765:                 }
20766:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20767:                 $changes{$item} = 1;
20768:             }
20769:         } elsif ($defaultchecked{$item} eq 'off') {
20770:             if ($current{$item} eq '') {
20771:                 if ($env{'form.'.$item} eq '1') {
20772:                     $changes{$item} = 1;
20773:                 }
20774:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20775:                 $changes{$item} = 1;
20776:             }
20777:         }
20778:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
20779:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
20780:         }
20781:     }
20782:     my $maxnum = $env{'form.helproles_maxnum'};
20783:     my $confname = $dom.'-domainconfig';
20784:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
20785:     my (@allpos,%newsettings,%changedprivs,$newrole);
20786:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20787:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
20788:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
20789:     my %lt = &Apache::lonlocal::texthash(
20790:                     s      => 'system',
20791:                     d      => 'domain',
20792:                     order  => 'Display order',
20793:                     access => 'Role usage',
20794:                     all    => 'All with domain helpdesk or helpdesk assistant role',
20795:                     dh     => 'All with domain helpdesk role',
20796:                     da     => 'All with domain helpdesk assistant role',
20797:                     none   => 'None',
20798:                     status => 'Determined based on institutional status',
20799:                     inc    => 'Include all, but exclude specific personnel',
20800:                     exc    => 'Exclude all, but include specific personnel',
20801:     );
20802:     for (my $num=0; $num<=$maxnum; $num++) {
20803:         my ($prefix,$identifier,$rolename,%curr);
20804:         if ($num == $maxnum) {
20805:             next unless ($env{'form.newcusthelp'} == $maxnum);
20806:             $identifier = 'custhelp'.$num;
20807:             $prefix = 'helproles_'.$num;
20808:             $rolename = $env{'form.custhelpname'.$num};
20809:             $rolename=~s/[^A-Za-z0-9]//gs;
20810:             next if ($rolename eq '');
20811:             next if (exists($existing{'rolesdef_'.$rolename}));
20812:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20813:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20814:                                                      $newprivs{'c'},$confname,$dom);
20815:             if ($result ne 'ok') {
20816:                 $errors .= '<li><span class="LC_error">'.
20817:                            &mt('An error occurred storing the new custom role: [_1]',
20818:                            $result).'</span></li>';
20819:                 next;
20820:             } else {
20821:                 $changedprivs{$rolename} = \%newprivs;
20822:                 $newrole = $rolename;
20823:             }
20824:         } else {
20825:             $prefix = 'helproles_'.$num;
20826:             $rolename = $env{'form.'.$prefix};
20827:             next if ($rolename eq '');
20828:             next unless (exists($existing{'rolesdef_'.$rolename}));
20829:             $identifier = 'custhelp'.$num;
20830:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20831:             my %currprivs;
20832:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
20833:                 split(/\_/,$existing{'rolesdef_'.$rolename});
20834:             foreach my $level ('c','d','s') {
20835:                 if ($newprivs{$level} ne $currprivs{$level}) {
20836:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20837:                                                              $newprivs{'c'},$confname,$dom);
20838:                     if ($result ne 'ok') {
20839:                         $errors .= '<li><span class="LC_error">'.
20840:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
20841:                                        $rolename,$result).'</span></li>';
20842:                     } else {
20843:                         $changedprivs{$rolename} = \%newprivs;
20844:                     }
20845:                     last;
20846:                 }
20847:             }
20848:             if (ref($current{'adhoc'}) eq 'HASH') {
20849:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20850:                     %curr = %{$current{'adhoc'}{$rolename}};
20851:                 }
20852:             }
20853:         }
20854:         my $newpos = $env{'form.'.$prefix.'_pos'};
20855:         $newpos =~ s/\D+//g;
20856:         $allpos[$newpos] = $rolename;
20857:         my $newdesc = $env{'form.'.$prefix.'_desc'};
20858:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
20859:         if ($curr{'desc'}) {
20860:             if ($curr{'desc'} ne $newdesc) {
20861:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
20862:                 $newsettings{$rolename}{'desc'} = $newdesc;
20863:             }
20864:         } elsif ($newdesc ne '') {
20865:             $changes{'customrole'}{$rolename}{'desc'} = 1;
20866:             $newsettings{$rolename}{'desc'} = $newdesc;
20867:         }
20868:         my $access = $env{'form.'.$prefix.'_access'};
20869:         if (grep(/^\Q$access\E$/,@accesstypes)) {
20870:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
20871:             if ($access eq 'status') {
20872:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
20873:                 if (scalar(@statuses) == 0) {
20874:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
20875:                 } else {
20876:                     my (@shownstatus,$numtypes);
20877:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20878:                     if (ref($types) eq 'ARRAY') {
20879:                         $numtypes = scalar(@{$types});
20880:                         foreach my $type (sort(@statuses)) {
20881:                             if ($type eq 'default') {
20882:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20883:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
20884:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20885:                                 push(@shownstatus,$usertypes->{$type});
20886:                             }
20887:                         }
20888:                     }
20889:                     if (grep(/^default$/,@statuses)) {
20890:                         push(@shownstatus,$othertitle);
20891:                     }
20892:                     if (scalar(@shownstatus) == 1+$numtypes) {
20893:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
20894:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
20895:                     } else {
20896:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
20897:                         if (ref($curr{'status'}) eq 'ARRAY') {
20898:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20899:                             if (@diffs) {
20900:                                 $changes{'customrole'}{$rolename}{$access} = 1;
20901:                             }
20902:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20903:                             $changes{'customrole'}{$rolename}{$access} = 1;
20904:                         }
20905:                     }
20906:                 }
20907:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
20908:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
20909:                 my @newspecstaff;
20910:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20911:                 foreach my $person (sort(@personnel)) {
20912:                     if ($domhelpdesk{$person}) {
20913:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
20914:                     }
20915:                 }
20916:                 if (ref($curr{$access}) eq 'ARRAY') {
20917:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20918:                     if (@diffs) {
20919:                         $changes{'customrole'}{$rolename}{$access} = 1;
20920:                     }
20921:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20922:                     $changes{'customrole'}{$rolename}{$access} = 1;
20923:                 }
20924:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20925:                     my ($uname,$udom) = split(/:/,$person);
20926:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
20927:                 }
20928:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
20929:             }
20930:         } else {
20931:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
20932:         }
20933:         unless ($curr{'access'} eq $access) {
20934:             $changes{'customrole'}{$rolename}{'access'} = 1;
20935:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
20936:         }
20937:     }
20938:     if (@allpos > 0) {
20939:         my $idx = 0;
20940:         foreach my $rolename (@allpos) {
20941:             if ($rolename ne '') {
20942:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
20943:                 if (ref($current{'adhoc'}) eq 'HASH') {
20944:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20945:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
20946:                             $changes{'customrole'}{$rolename}{'order'} = 1;
20947:                             $newsettings{$rolename}{'order'} = $idx+1;
20948:                         }
20949:                     }
20950:                 }
20951:                 $idx ++;
20952:             }
20953:         }
20954:     }
20955:     my $putresult;
20956:     if (keys(%changes) > 0) {
20957:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
20958:         if ($putresult eq 'ok') {
20959:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
20960:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
20961:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
20962:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
20963:                 }
20964:             }
20965:             my $cachetime = 24*60*60;
20966:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20967:             if (ref($lastactref) eq 'HASH') {
20968:                 $lastactref->{'domdefaults'} = 1;
20969:             }
20970:         } else {
20971:             $errors .= '<li><span class="LC_error">'.
20972:                        &mt('An error occurred storing the settings: [_1]',
20973:                            $putresult).'</span></li>';
20974:         }
20975:     }
20976:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
20977:         $resulttext = &mt('Changes made:').'<ul>';
20978:         my (%shownprivs,@levelorder);
20979:         @levelorder = ('c','d','s');
20980:         if ((keys(%changes)) && ($putresult eq 'ok')) {
20981:             foreach my $item (sort(keys(%changes))) {
20982:                 if ($item eq 'submitbugs') {
20983:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
20984:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
20985:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
20986:                 } elsif ($item eq 'customrole') {
20987:                     if (ref($changes{'customrole'}) eq 'HASH') {
20988:                         my @keyorder = ('order','desc','access','status','exc','inc');
20989:                         my %keytext = &Apache::lonlocal::texthash(
20990:                                                                    order  => 'Order',
20991:                                                                    desc   => 'Role description',
20992:                                                                    access => 'Role usage',
20993:                                                                    status => 'Allowed institutional types',
20994:                                                                    exc    => 'Allowed personnel',
20995:                                                                    inc    => 'Disallowed personnel',
20996:                         );
20997:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
20998:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
20999:                                 if ($role eq $newrole) {
21000:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
21001:                                                               $role).'<ul>';
21002:                                 } else {
21003:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21004:                                                               $role).'<ul>';
21005:                                 }
21006:                                 foreach my $key (@keyorder) {
21007:                                     if ($changes{'customrole'}{$role}{$key}) {
21008:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
21009:                                                                   $keytext{$key},$newsettings{$role}{$key}).
21010:                                                        '</li>';
21011:                                     }
21012:                                 }
21013:                                 if (ref($changedprivs{$role}) eq 'HASH') {
21014:                                     $shownprivs{$role} = 1;
21015:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
21016:                                     foreach my $level (@levelorder) {
21017:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21018:                                             next if ($item eq '');
21019:                                             my ($priv) = split(/\&/,$item,2);
21020:                                             if (&Apache::lonnet::plaintext($priv)) {
21021:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21022:                                                 unless ($level eq 'c') {
21023:                                                     $resulttext .= ' ('.$lt{$level}.')';
21024:                                                 }
21025:                                                 $resulttext .= '</li>';
21026:                                             }
21027:                                         }
21028:                                     }
21029:                                     $resulttext .= '</ul>';
21030:                                 }
21031:                                 $resulttext .= '</ul></li>';
21032:                             }
21033:                         }
21034:                     }
21035:                 }
21036:             }
21037:         }
21038:         if (keys(%changedprivs)) {
21039:             foreach my $role (sort(keys(%changedprivs))) {
21040:                 unless ($shownprivs{$role}) {
21041:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21042:                                               $role).'<ul>'.
21043:                                    '<li>'.&mt('Privileges set to :').'<ul>';
21044:                     foreach my $level (@levelorder) {
21045:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21046:                             next if ($item eq '');
21047:                             my ($priv) = split(/\&/,$item,2);
21048:                             if (&Apache::lonnet::plaintext($priv)) {
21049:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21050:                                 unless ($level eq 'c') {
21051:                                     $resulttext .= ' ('.$lt{$level}.')';
21052:                                 }
21053:                                 $resulttext .= '</li>';
21054:                             }
21055:                         }
21056:                     }
21057:                     $resulttext .= '</ul></li></ul></li>';
21058:                 }
21059:             }
21060:         }
21061:         $resulttext .= '</ul>';
21062:     } else {
21063:         $resulttext = &mt('No changes made to help settings');
21064:     }
21065:     if ($errors) {
21066:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
21067:                                     $errors.'</ul>';
21068:     }
21069:     return $resulttext;
21070: }
21071: 
21072: sub modify_coursedefaults {
21073:     my ($dom,$lastactref,%domconfig) = @_;
21074:     my ($resulttext,$errors,%changes,%defaultshash);
21075:     my %defaultchecked = (
21076:                            'canuse_pdfforms' => 'off',
21077:                            'uselcmath'       => 'on',
21078:                            'usejsme'         => 'on',
21079:                            'inline_chem'     => 'on',
21080:                            'ltiauth'         => 'off',
21081:                          );
21082:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem','ltiauth');
21083:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
21084:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
21085:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
21086:                    'mysqltables_textbook','mysqltables_placement');
21087:     my @types = ('official','unofficial','community','textbook','placement');
21088:     my %staticdefaults = (
21089:                            anonsurvey_threshold => 10,
21090:                            uploadquota          => 500,
21091:                            postsubmit           => 60,
21092:                            mysqltables          => 172800,
21093:                          );
21094:     my %texoptions = (
21095:                         MathJax  => 'MathJax',
21096:                         mimetex  => &mt('Convert to Images'),
21097:                         tth      => &mt('TeX to HTML'),
21098:                      );
21099:     $defaultshash{'coursedefaults'} = {};
21100: 
21101:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
21102:         if ($domconfig{'coursedefaults'} eq '') {
21103:             $domconfig{'coursedefaults'} = {};
21104:         }
21105:     }
21106: 
21107:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
21108:         foreach my $item (@toggles) {
21109:             if ($defaultchecked{$item} eq 'on') {
21110:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21111:                     ($env{'form.'.$item} eq '0')) {
21112:                     $changes{$item} = 1;
21113:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21114:                     $changes{$item} = 1;
21115:                 }
21116:             } elsif ($defaultchecked{$item} eq 'off') {
21117:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21118:                     ($env{'form.'.$item} eq '1')) {
21119:                     $changes{$item} = 1;
21120:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21121:                     $changes{$item} = 1;
21122:                 }
21123:             }
21124:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
21125:         }
21126:         foreach my $item (@numbers) {
21127:             my ($currdef,$newdef);
21128:             $newdef = $env{'form.'.$item};
21129:             if ($item eq 'anonsurvey_threshold') {
21130:                 $currdef = $domconfig{'coursedefaults'}{$item};
21131:                 $newdef =~ s/\D//g;
21132:                 if ($newdef eq '' || $newdef < 1) {
21133:                     $newdef = 1;
21134:                 }
21135:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
21136:             } else {
21137:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
21138:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
21139:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
21140:                 }
21141:                 $newdef =~ s/[^\w.\-]//g;
21142:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
21143:             }
21144:             if ($currdef ne $newdef) {
21145:                 if ($item eq 'anonsurvey_threshold') {
21146:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
21147:                         $changes{$item} = 1;
21148:                     }
21149:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
21150:                     my $setting = $1;
21151:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
21152:                         $changes{$setting} = 1;
21153:                     }
21154:                 }
21155:             }
21156:         }
21157:         my $texengine;
21158:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
21159:             $texengine = $env{'form.texengine'};
21160:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
21161:             if ($currdef eq '') {
21162:                 unless ($texengine eq $Apache::lonnet::deftex) {
21163:                     $changes{'texengine'} = 1;
21164:                 }
21165:             } elsif ($currdef ne $texengine) {
21166:                 $changes{'texengine'} = 1;
21167:             }
21168:         }
21169:         if ($texengine ne '') {
21170:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
21171:         }
21172:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
21173:         my @currclonecode;
21174:         if (ref($currclone) eq 'HASH') {
21175:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
21176:                 @currclonecode = @{$currclone->{'instcode'}};
21177:             }
21178:         }
21179:         my $newclone;
21180:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
21181:             $newclone = $env{'form.canclone'};
21182:         }
21183:         if ($newclone eq 'instcode') {
21184:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
21185:             my (%codedefaults,@code_order,@clonecode);
21186:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
21187:                                                     \@code_order);
21188:             foreach my $item (@code_order) {
21189:                 if (grep(/^\Q$item\E$/,@newcodes)) {
21190:                     push(@clonecode,$item);
21191:                 }
21192:             }
21193:             if (@clonecode) {
21194:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
21195:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
21196:                 if (@diffs) {
21197:                     $changes{'canclone'} = 1;
21198:                 }
21199:             } else {
21200:                 $newclone eq '';
21201:             }
21202:         } elsif ($newclone ne '') {
21203:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
21204:         }
21205:         if ($newclone ne $currclone) {
21206:             $changes{'canclone'} = 1;
21207:         }
21208:         my %credits;
21209:         foreach my $type (@types) {
21210:             unless ($type eq 'community') {
21211:                 $credits{$type} = $env{'form.'.$type.'_credits'};
21212:                 $credits{$type} =~ s/[^\d.]+//g;
21213:             }
21214:         }
21215:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
21216:             ($env{'form.coursecredits'} eq '1')) {
21217:             $changes{'coursecredits'} = 1;
21218:             foreach my $type (keys(%credits)) {
21219:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21220:             }
21221:         } else {
21222:             if ($env{'form.coursecredits'} eq '1') {
21223:                 foreach my $type (@types) {
21224:                     unless ($type eq 'community') {
21225:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
21226:                             $changes{'coursecredits'} = 1;
21227:                         }
21228:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21229:                     }
21230:                 }
21231:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21232:                 foreach my $type (@types) {
21233:                     unless ($type eq 'community') {
21234:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
21235:                             $changes{'coursecredits'} = 1;
21236:                             last;
21237:                         }
21238:                     }
21239:                 }
21240:             }
21241:         }
21242:         if ($env{'form.postsubmit'} eq '1') {
21243:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
21244:             my %currtimeout;
21245:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21246:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
21247:                     $changes{'postsubmit'} = 1;
21248:                 }
21249:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21250:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
21251:                 }
21252:             } else {
21253:                 $changes{'postsubmit'} = 1;
21254:             }
21255:             foreach my $type (@types) {
21256:                 my $timeout = $env{'form.'.$type.'_timeout'};
21257:                 $timeout =~ s/\D//g;
21258:                 if ($timeout == $staticdefaults{'postsubmit'}) {
21259:                     $timeout = '';
21260:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
21261:                     $timeout = '0';
21262:                 }
21263:                 unless ($timeout eq '') {
21264:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
21265:                 }
21266:                 if (exists($currtimeout{$type})) {
21267:                     if ($timeout ne $currtimeout{$type}) {
21268:                         $changes{'postsubmit'} = 1;
21269:                     }
21270:                 } elsif ($timeout ne '') {
21271:                     $changes{'postsubmit'} = 1;
21272:                 }
21273:             }
21274:         } else {
21275:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
21276:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21277:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
21278:                     $changes{'postsubmit'} = 1;
21279:                 }
21280:             } else {
21281:                 $changes{'postsubmit'} = 1;
21282:             }
21283:         }
21284:     }
21285:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21286:                                              $dom);
21287:     if ($putresult eq 'ok') {
21288:         if (keys(%changes) > 0) {
21289:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21290:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
21291:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
21292:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
21293:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'})) {
21294:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','inline_chem','texengine','ltiauth') {
21295:                     if ($changes{$item}) {
21296:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
21297:                     }
21298:                 }
21299:                 if ($changes{'coursecredits'}) {
21300:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21301:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
21302:                             $domdefaults{$type.'credits'} =
21303:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
21304:                         }
21305:                     }
21306:                 }
21307:                 if ($changes{'postsubmit'}) {
21308:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21309:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
21310:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21311:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
21312:                                 $domdefaults{$type.'postsubtimeout'} =
21313:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21314:                             }
21315:                         }
21316:                     }
21317:                 }
21318:                 if ($changes{'uploadquota'}) {
21319:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21320:                         foreach my $type (@types) {
21321:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
21322:                         }
21323:                     }
21324:                 }
21325:                 if ($changes{'canclone'}) {
21326:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21327:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21328:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
21329:                             if (@clonecodes) {
21330:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
21331:                             }
21332:                         }
21333:                     } else {
21334:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
21335:                     }
21336:                 }
21337:                 my $cachetime = 24*60*60;
21338:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21339:                 if (ref($lastactref) eq 'HASH') {
21340:                     $lastactref->{'domdefaults'} = 1;
21341:                 }
21342:             }
21343:             $resulttext = &mt('Changes made:').'<ul>';
21344:             foreach my $item (sort(keys(%changes))) {
21345:                 if ($item eq 'canuse_pdfforms') {
21346:                     if ($env{'form.'.$item} eq '1') {
21347:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
21348:                     } else {
21349:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
21350:                     }
21351:                 } elsif ($item eq 'uselcmath') {
21352:                     if ($env{'form.'.$item} eq '1') {
21353:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
21354:                     } else {
21355:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
21356:                     }
21357:                 } elsif ($item eq 'usejsme') {
21358:                     if ($env{'form.'.$item} eq '1') {
21359:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
21360:                     } else {
21361:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
21362:                     }
21363:                 } elsif ($item eq 'inline_chem') {
21364:                     if ($env{'form.'.$item} eq '1') {
21365:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
21366:                     } else {
21367:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
21368:                     }
21369:                 } elsif ($item eq 'texengine') {
21370:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
21371:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
21372:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
21373:                     }
21374:                 } elsif ($item eq 'anonsurvey_threshold') {
21375:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
21376:                 } elsif ($item eq 'uploadquota') {
21377:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21378:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
21379:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
21380:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
21381:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
21382:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
21383:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
21384:                                        '</ul>'.
21385:                                        '</li>';
21386:                     } else {
21387:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
21388:                     }
21389:                 } elsif ($item eq 'mysqltables') {
21390:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
21391:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
21392:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
21393:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
21394:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
21395:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
21396:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
21397:                                        '</ul>'.
21398:                                        '</li>';
21399:                     } else {
21400:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
21401:                     }
21402:                 } elsif ($item eq 'postsubmit') {
21403:                     if ($domdefaults{'postsubmit'} eq 'off') {
21404:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
21405:                     } else {
21406:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
21407:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21408:                             $resulttext .= &mt('durations:').'<ul>';
21409:                             foreach my $type (@types) {
21410:                                 $resulttext .= '<li>';
21411:                                 my $timeout;
21412:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21413:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21414:                                 }
21415:                                 my $display;
21416:                                 if ($timeout eq '0') {
21417:                                     $display = &mt('unlimited');
21418:                                 } elsif ($timeout eq '') {
21419:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
21420:                                 } else {
21421:                                     $display = &mt('[quant,_1,second]',$timeout);
21422:                                 }
21423:                                 if ($type eq 'community') {
21424:                                     $resulttext .= &mt('Communities');
21425:                                 } elsif ($type eq 'official') {
21426:                                     $resulttext .= &mt('Official courses');
21427:                                 } elsif ($type eq 'unofficial') {
21428:                                     $resulttext .= &mt('Unofficial courses');
21429:                                 } elsif ($type eq 'textbook') {
21430:                                     $resulttext .= &mt('Textbook courses');
21431:                                 } elsif ($type eq 'placement') {
21432:                                     $resulttext .= &mt('Placement tests');
21433:                                 }
21434:                                 $resulttext .= ' -- '.$display.'</li>';
21435:                             }
21436:                             $resulttext .= '</ul>';
21437:                         }
21438:                         $resulttext .= '</li>';
21439:                     }
21440:                 } elsif ($item eq 'coursecredits') {
21441:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21442:                         if (($domdefaults{'officialcredits'} eq '') &&
21443:                             ($domdefaults{'unofficialcredits'} eq '') &&
21444:                             ($domdefaults{'textbookcredits'} eq '')) {
21445:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21446:                         } else {
21447:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
21448:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
21449:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
21450:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
21451:                                            '</ul>'.
21452:                                            '</li>';
21453:                         }
21454:                     } else {
21455:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21456:                     }
21457:                 } elsif ($item eq 'canclone') {
21458:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21459:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21460:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
21461:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
21462:                         }
21463:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
21464:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
21465:                     } else {
21466:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
21467:                     }
21468:                 } elsif ($item eq 'ltiauth') {
21469:                     if ($env{'form.'.$item} eq '1') {
21470:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
21471:                     } else {
21472:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
21473:                     }
21474:                 }
21475:             }
21476:             $resulttext .= '</ul>';
21477:         } else {
21478:             $resulttext = &mt('No changes made to course defaults');
21479:         }
21480:     } else {
21481:         $resulttext = '<span class="LC_error">'.
21482:             &mt('An error occurred: [_1]',$putresult).'</span>';
21483:     }
21484:     return $resulttext;
21485: }
21486: 
21487: sub modify_selfenrollment {
21488:     my ($dom,$lastactref,%domconfig) = @_;
21489:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
21490:     my @types = ('official','unofficial','community','textbook','placement');
21491:     my %titles = &tool_titles();
21492:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
21493:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
21494:     $ordered{'default'} = ['types','registered','approval','limit'];
21495: 
21496:     my (%roles,%shown,%toplevel);
21497:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
21498: 
21499:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
21500:         if ($domconfig{'selfenrollment'} eq '') {
21501:             $domconfig{'selfenrollment'} = {};
21502:         }
21503:     }
21504:     %toplevel = (
21505:                   admin      => 'Configuration Rights',
21506:                   default    => 'Default settings',
21507:                   validation => 'Validation of self-enrollment requests',
21508:                 );
21509:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
21510: 
21511:     if (ref($ordered{'admin'}) eq 'ARRAY') {
21512:         foreach my $item (@{$ordered{'admin'}}) {
21513:             foreach my $type (@types) {
21514:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
21515:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
21516:                 } else {
21517:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
21518:                 }
21519:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
21520:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
21521:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
21522:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
21523:                             push(@{$changes{'admin'}{$type}},$item);
21524:                         }
21525:                     } else {
21526:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
21527:                             push(@{$changes{'admin'}{$type}},$item);
21528:                         }
21529:                     }
21530:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
21531:                     push(@{$changes{'admin'}{$type}},$item);
21532:                 }
21533:             }
21534:         }
21535:     }
21536: 
21537:     foreach my $item (@{$ordered{'default'}}) {
21538:         foreach my $type (@types) {
21539:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
21540:             if ($item eq 'types') {
21541:                 unless (($value eq 'all') || ($value eq 'dom')) {
21542:                     $value = '';
21543:                 }
21544:             } elsif ($item eq 'registered') {
21545:                 unless ($value eq '1') {
21546:                     $value = 0;
21547:                 }
21548:             } elsif ($item eq 'approval') {
21549:                 unless ($value =~ /^[012]$/) {
21550:                     $value = 0;
21551:                 }
21552:             } else {
21553:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21554:                     $value = 'none';
21555:                 }
21556:             }
21557:             $selfenrollhash{'default'}{$type}{$item} = $value;
21558:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
21559:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21560:                     if ($selfenrollhash{'default'}{$type}{$item} ne
21561:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
21562:                          push(@{$changes{'default'}{$type}},$item);
21563:                     }
21564:                 } else {
21565:                     push(@{$changes{'default'}{$type}},$item);
21566:                 }
21567:             } else {
21568:                 push(@{$changes{'default'}{$type}},$item);
21569:             }
21570:             if ($item eq 'limit') {
21571:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21572:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
21573:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
21574:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
21575:                     }
21576:                 } else {
21577:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
21578:                 }
21579:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21580:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
21581:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
21582:                          push(@{$changes{'default'}{$type}},'cap');
21583:                     }
21584:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
21585:                     push(@{$changes{'default'}{$type}},'cap');
21586:                 }
21587:             }
21588:         }
21589:     }
21590: 
21591:     foreach my $item (@{$itemsref}) {
21592:         if ($item eq 'fields') {
21593:             my @changed;
21594:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
21595:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
21596:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
21597:             }
21598:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21599:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
21600:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
21601:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
21602:                 } else {
21603:                     @changed = @{$selfenrollhash{'validation'}{$item}};
21604:                 }
21605:             } else {
21606:                 @changed = @{$selfenrollhash{'validation'}{$item}};
21607:             }
21608:             if (@changed) {
21609:                 if ($selfenrollhash{'validation'}{$item}) { 
21610:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
21611:                 } else {
21612:                     $changes{'validation'}{$item} = &mt('None');
21613:                 }
21614:             }
21615:         } else {
21616:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
21617:             if ($item eq 'markup') {
21618:                if ($env{'form.selfenroll_validation_'.$item}) {
21619:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
21620:                }
21621:             }
21622:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21623:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
21624:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
21625:                 }
21626:             }
21627:         }
21628:     }
21629: 
21630:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
21631:                                              $dom);
21632:     if ($putresult eq 'ok') {
21633:         if (keys(%changes) > 0) {
21634:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21635:             $resulttext = &mt('Changes made:').'<ul>';
21636:             foreach my $key ('admin','default','validation') {
21637:                 if (ref($changes{$key}) eq 'HASH') {
21638:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
21639:                     if ($key eq 'validation') {
21640:                         foreach my $item (@{$itemsref}) {
21641:                             if (exists($changes{$key}{$item})) {
21642:                                 if ($item eq 'markup') {
21643:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21644:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
21645:                                 } else {  
21646:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21647:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
21648:                                 }
21649:                             }
21650:                         }
21651:                     } else {
21652:                         foreach my $type (@types) {
21653:                             if ($type eq 'community') {
21654:                                 $roles{'1'} = &mt('Community personnel');
21655:                             } else {
21656:                                 $roles{'1'} = &mt('Course personnel');
21657:                             }
21658:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
21659:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
21660:                                     if ($key eq 'admin') {
21661:                                         my @mgrdc = ();
21662:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21663:                                             foreach my $item (@{$ordered{'admin'}}) {
21664:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
21665:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
21666:                                                         push(@mgrdc,$item);
21667:                                                     }
21668:                                                 }
21669:                                             }
21670:                                             if (@mgrdc) {
21671:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
21672:                                             } else {
21673:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
21674:                                             }
21675:                                         }
21676:                                     } else {
21677:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21678:                                             foreach my $item (@{$ordered{$key}}) {
21679:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21680:                                                     $domdefaults{$type.'selfenroll'.$item} =
21681:                                                         $selfenrollhash{$key}{$type}{$item};
21682:                                                 }
21683:                                             }
21684:                                         }
21685:                                     }
21686:                                 }
21687:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
21688:                                 foreach my $item (@{$ordered{$key}}) {
21689:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21690:                                         $resulttext .= '<li>';
21691:                                         if ($key eq 'admin') {
21692:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
21693:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
21694:                                         } else {
21695:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
21696:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
21697:                                         }
21698:                                         $resulttext .= '</li>';
21699:                                     }
21700:                                 }
21701:                                 $resulttext .= '</ul></li>';
21702:                             }
21703:                         }
21704:                         $resulttext .= '</ul></li>'; 
21705:                     }
21706:                 }
21707:             }
21708:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
21709:                 my $cachetime = 24*60*60;
21710:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21711:                 if (ref($lastactref) eq 'HASH') {
21712:                     $lastactref->{'domdefaults'} = 1;
21713:                 }
21714:             }
21715:             $resulttext .= '</ul>';
21716:         } else {
21717:             $resulttext = &mt('No changes made to self-enrollment settings');
21718:         }
21719:     } else {
21720:         $resulttext = '<span class="LC_error">'.
21721:             &mt('An error occurred: [_1]',$putresult).'</span>';
21722:     }
21723:     return $resulttext;
21724: }
21725: 
21726: sub modify_wafproxy {
21727:     my ($dom,$action,$lastactref,%domconfig) = @_;
21728:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21729:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
21730:         %wafproxy,%changes,%expirecache,%expiresaml);
21731:     foreach my $server (sort(keys(%servers))) {
21732:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21733:         if ($serverhome eq $server) {
21734:             my $serverdom = &Apache::lonnet::host_domain($server);
21735:             if ($serverdom eq $dom) {
21736:                 $canset{$server} = 1;
21737:             }
21738:         }
21739:     }
21740:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
21741:         %{$values{$dom}} = ();
21742:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
21743:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
21744:         }
21745:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
21746:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
21747:         }
21748:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21749:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
21750:         }
21751:     }
21752:     my $output;
21753:     if (keys(%canset)) {
21754:         %{$wafproxy{'alias'}} = ();
21755:         %{$wafproxy{'saml'}} = ();
21756:         foreach my $key (sort(keys(%canset))) {
21757:             if ($env{'form.wafproxy_'.$dom}) {
21758:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
21759:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
21760:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
21761:                     $changes{'alias'} = 1;
21762:                 }
21763:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
21764:                     $wafproxy{'saml'}{$key} = 1;
21765:                 }
21766:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
21767:                     $changes{'saml'} = 1;
21768:                 }
21769:             } else {
21770:                 $wafproxy{'alias'}{$key} = '';
21771:                 $wafproxy{'saml'}{$key} = '';
21772:                 if ($curralias{$key}) {
21773:                     $changes{'alias'} = 1;
21774:                 }
21775:                 if ($currsaml{$key}) {
21776:                     $changes{'saml'} = 1;
21777:                 }
21778:             }
21779:             if ($wafproxy{'alias'}{$key} eq '') {
21780:                 if ($curralias{$key}) {
21781:                     $expirecache{$key} = 1;
21782:                 }
21783:                 delete($wafproxy{'alias'}{$key});
21784:             }
21785:             if ($wafproxy{'saml'}{$key} eq '') {
21786:                 if ($currsaml{$key}) {
21787:                     $expiresaml{$key} = 1;
21788:                 }
21789:                 delete($wafproxy{'saml'}{$key});
21790:             }
21791:         }
21792:         unless (keys(%{$wafproxy{'alias'}})) {
21793:             delete($wafproxy{'alias'});
21794:         }
21795:         unless (keys(%{$wafproxy{'saml'}})) {
21796:             delete($wafproxy{'saml'});
21797:         }
21798:         # Localization for values in %warn occurs in &mt() calls separately.
21799:         my %warn = (
21800:                      trusted => 'trusted IP range(s)',
21801:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
21802:                      vpnext => 'IP range(s) for backend WAF connections',
21803:                    );
21804:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21805:             my $possible = $env{'form.wafproxy_'.$item};
21806:             $possible =~ s/^\s+|\s+$//g;
21807:             if ($possible ne '') {
21808:                 if ($item eq 'remoteip') {
21809:                     if ($possible =~ /^[mhn]$/) {
21810:                         $wafproxy{$item} = $possible;
21811:                     }
21812:                 } elsif ($item eq 'ipheader') {
21813:                     if ($wafproxy{'remoteip'} eq 'h') {
21814:                         $wafproxy{$item} = $possible;
21815:                     }
21816:                 } elsif ($item eq 'sslopt') {
21817:                     if ($possible =~ /^0|1$/) {
21818:                         $wafproxy{$item} = $possible;
21819:                     }
21820:                 } else {
21821:                     my (@ok,$count);
21822:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
21823:                         unless ($env{'form.wafproxy_vpnaccess'}) {
21824:                             $possible = '';
21825:                         }
21826:                     } elsif ($item eq 'trusted') {
21827:                         unless ($wafproxy{'remoteip'} eq 'h') {
21828:                             $possible = '';
21829:                         }
21830:                     }
21831:                     unless ($possible eq '') {
21832:                         $possible =~ s/[\r\n]+/\s/g;
21833:                         $possible =~ s/\s*-\s*/-/g;
21834:                         $possible =~ s/\s+/,/g;
21835:                         $possible =~ s/,+/,/g;
21836:                     }
21837:                     $count = 0;
21838:                     if ($possible ne '') {
21839:                         foreach my $poss (split(/\,/,$possible)) {
21840:                             $count ++;
21841:                             $poss = &validate_ip_pattern($poss);
21842:                             if ($poss ne '') {
21843:                                 push(@ok,$poss);
21844:                             }
21845:                         }
21846:                         my $diff = $count - scalar(@ok);
21847:                         if ($diff) {
21848:                             push(@warnings,'<li>'.
21849:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
21850:                                      $diff,$warn{$item}).
21851:                                  '</li>');
21852:                         }
21853:                         if (@ok) {
21854:                             my @cidr_list;
21855:                             foreach my $item (@ok) {
21856:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
21857:                             }
21858:                             $wafproxy{$item} = join(',',@cidr_list);
21859:                         }
21860:                     }
21861:                 }
21862:                 if ($wafproxy{$item} ne $currvalue{$item}) {
21863:                     $changes{$item} = 1;
21864:                 }
21865:             } elsif ($currvalue{$item}) {
21866:                 $changes{$item} = 1;
21867:             } 
21868:         }
21869:     } else {
21870:         if (keys(%curralias)) {
21871:             $changes{'alias'} = 1;
21872:         }
21873:         if (keys(%currsaml)) {
21874:             $changes{'saml'} = 1;
21875:         } 
21876:         if (keys(%currvalue)) {
21877:             foreach my $key (keys(%currvalue)) {
21878:                 $changes{$key} = 1;
21879:             }
21880:         }
21881:     }
21882:     if (keys(%changes)) {
21883:         my %defaultshash = (
21884:                               wafproxy => \%wafproxy,
21885:                            ); 
21886:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21887:                                                  $dom);
21888:         if ($putresult eq 'ok') {
21889:             my $cachetime = 24*60*60;
21890:             my (%domdefaults,$updatedomdefs);
21891:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
21892:                 if ($changes{$item}) {
21893:                     unless ($updatedomdefs) {
21894:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
21895:                         $updatedomdefs = 1;
21896:                     }
21897:                     if ($wafproxy{$item}) {
21898:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
21899:                     } elsif (exists($domdefaults{'waf_'.$item})) {
21900:                         delete($domdefaults{'waf_'.$item});
21901:                     } 
21902:                 }
21903:             }
21904:             if ($updatedomdefs) {
21905:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21906:                 if (ref($lastactref) eq 'HASH') {
21907:                     $lastactref->{'domdefaults'} = 1;
21908:                 }
21909:             }
21910:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
21911:                 my %updates = %expirecache;
21912:                 foreach my $key (keys(%expirecache)) {
21913:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
21914:                 }
21915:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
21916:                     my $cachetime = 24*60*60;
21917:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
21918:                         $updates{$key} = 1;
21919:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
21920:                                                       $cachetime);
21921:                     }
21922:                 }
21923:                 if (ref($lastactref) eq 'HASH') {
21924:                     $lastactref->{'proxyalias'} = \%updates;
21925:                 }
21926:             }
21927:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
21928:                 my %samlupdates = %expiresaml;
21929:                 foreach my $key (keys(%expiresaml)) {
21930:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
21931:                 }
21932:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
21933:                     my $cachetime = 24*60*60;
21934:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
21935:                         $samlupdates{$key} = 1;
21936:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
21937:                                                       $cachetime);
21938:                     }
21939:                 }
21940:                 if (ref($lastactref) eq 'HASH') {
21941:                     $lastactref->{'proxysaml'} = \%samlupdates;
21942:                 }
21943:             }
21944:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
21945:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21946:                 if ($changes{$item}) {
21947:                     if ($item eq 'alias') {
21948:                         my $numaliased = 0;
21949:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
21950:                             my $shown;
21951:                             if (keys(%{$wafproxy{'alias'}})) {
21952:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
21953:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
21954:                                                          &Apache::lonnet::hostname($server),
21955:                                                          $wafproxy{'alias'}{$server}).'</li>';
21956:                                     $numaliased ++;
21957:                                 }
21958:                                 if ($numaliased) {
21959:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
21960:                                                           '<ul>'.$shown.'</ul>').'</li>';
21961:                                 }
21962:                             }
21963:                         }
21964:                         unless ($numaliased) {
21965:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
21966:                         }
21967:                     } elsif ($item eq 'saml') {
21968:                         my $shown; 
21969:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
21970:                             if (keys(%{$wafproxy{'saml'}})) {
21971:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
21972:                             }
21973:                         }
21974:                         if ($shown) {
21975:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
21976:                                                   $shown).'</li>';
21977:                         } else {
21978:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
21979:                         }
21980:                     } else {
21981:                         if ($item eq 'remoteip') {
21982:                             my %ip_methods = &remoteip_methods();
21983:                             if ($wafproxy{$item} =~ /^[mh]$/) {
21984:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
21985:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
21986:                             } else {
21987:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
21988:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
21989:                                                '</li>';
21990:                                 } else {
21991:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
21992:                                 }
21993:                             }
21994:                         } elsif ($item eq 'ipheader') {
21995:                             if ($wafproxy{$item}) {
21996:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
21997:                                                       $wafproxy{$item}).'</li>';
21998:                             } else {
21999:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
22000:                             }
22001:                         } elsif ($item eq 'trusted') {
22002:                             if ($wafproxy{$item}) {
22003:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
22004:                                                       $wafproxy{$item}).'</li>';
22005:                             } else {
22006:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
22007:                             }
22008:                         } elsif ($item eq 'vpnint') {
22009:                             if ($wafproxy{$item}) {
22010:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
22011:                                                        $wafproxy{$item}).'</li>';
22012:                             } else {
22013:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
22014:                             }
22015:                         } elsif ($item eq 'vpnext') {
22016:                             if ($wafproxy{$item}) {
22017:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
22018:                                                        $wafproxy{$item}).'</li>';
22019:                             } else {
22020:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
22021:                             }
22022:                         } elsif ($item eq 'sslopt') {
22023:                             if ($wafproxy{$item}) {
22024:                                 $output .= '<li>'.&mt('WAF/Reverse Proxy expected to forward requests to https on LON-CAPA node, regardless of original protocol in web browser (http or https).').'</li>';
22025:                             } else {
22026:                                 $output .= '<li>'.&mt('WAF/Reverse Proxy expected to preserve original protocol in web browser (either http or https) when forwarding to LON-CAPA node.').'</li>';
22027:                             }
22028:                         }
22029:                     }
22030:                 }
22031:             }
22032:         } else {
22033:             $output = '<span class="LC_error">'.
22034:                       &mt('An error occurred: [_1]',$putresult).'</span>';
22035:         }
22036:     } elsif (keys(%canset)) {
22037:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
22038:     }
22039:     if (@warnings) {
22040:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
22041:                        join("\n",@warnings).'</ul>';
22042:     }
22043:     return $output;
22044: }
22045: 
22046: sub validate_ip_pattern {
22047:     my ($pattern) = @_;
22048:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
22049:         my ($start,$end) = ($1,$2);
22050:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
22051:             if (($start !~ m{/}) && ($end !~ m{/})) {
22052:                 return $start.'-'.$end;
22053:             }
22054:         }
22055:     } elsif ($pattern ne '') {
22056:         $pattern = &Net::CIDR::cidrvalidate($pattern);
22057:         if ($pattern ne '') {
22058:             return $pattern;
22059:         }
22060:     }
22061:     return;
22062: }
22063: 
22064: sub modify_usersessions {
22065:     my ($dom,$lastactref,%domconfig) = @_;
22066:     my @hostingtypes = ('version','excludedomain','includedomain');
22067:     my @offloadtypes = ('primary','default');
22068:     my %types = (
22069:                   remote => \@hostingtypes,
22070:                   hosted => \@hostingtypes,
22071:                   spares => \@offloadtypes,
22072:                 );
22073:     my @prefixes = ('remote','hosted','spares');
22074:     my @lcversions = &Apache::lonnet::all_loncaparevs();
22075:     my (%by_ip,%by_location,@intdoms,@instdoms);
22076:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22077:     my @locations = sort(keys(%by_location));
22078:     my (%defaultshash,%changes);
22079:     foreach my $prefix (@prefixes) {
22080:         $defaultshash{'usersessions'}{$prefix} = {};
22081:     }
22082:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22083:     my $resulttext;
22084:     my %iphost = &Apache::lonnet::get_iphost();
22085:     foreach my $prefix (@prefixes) {
22086:         next if ($prefix eq 'spares');
22087:         foreach my $type (@{$types{$prefix}}) {
22088:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22089:             if ($type eq 'version') {
22090:                 my $value = $env{'form.'.$prefix.'_'.$type};
22091:                 my $okvalue;
22092:                 if ($value ne '') {
22093:                     if (grep(/^\Q$value\E$/,@lcversions)) {
22094:                         $okvalue = $value;
22095:                     }
22096:                 }
22097:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22098:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22099:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
22100:                             if ($inuse == 0) {
22101:                                 $changes{$prefix}{$type} = 1;
22102:                             } else {
22103:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
22104:                                     $changes{$prefix}{$type} = 1;
22105:                                 }
22106:                                 if ($okvalue ne '') {
22107:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22108:                                 } 
22109:                             }
22110:                         } else {
22111:                             if (($inuse == 1) && ($okvalue ne '')) {
22112:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22113:                                 $changes{$prefix}{$type} = 1;
22114:                             }
22115:                         }
22116:                     } else {
22117:                         if (($inuse == 1) && ($okvalue ne '')) {
22118:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22119:                             $changes{$prefix}{$type} = 1;
22120:                         }
22121:                     }
22122:                 } else {
22123:                     if (($inuse == 1) && ($okvalue ne '')) {
22124:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22125:                         $changes{$prefix}{$type} = 1;
22126:                     }
22127:                 }
22128:             } else {
22129:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22130:                 my @okvals;
22131:                 foreach my $val (@vals) {
22132:                     if ($val =~ /:/) {
22133:                         my @items = split(/:/,$val);
22134:                         foreach my $item (@items) {
22135:                             if (ref($by_location{$item}) eq 'ARRAY') {
22136:                                 push(@okvals,$item);
22137:                             }
22138:                         }
22139:                     } else {
22140:                         if (ref($by_location{$val}) eq 'ARRAY') {
22141:                             push(@okvals,$val);
22142:                         }
22143:                     }
22144:                 }
22145:                 @okvals = sort(@okvals);
22146:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22147:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22148:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22149:                             if ($inuse == 0) {
22150:                                 $changes{$prefix}{$type} = 1; 
22151:                             } else {
22152:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22153:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
22154:                                 if (@changed > 0) {
22155:                                     $changes{$prefix}{$type} = 1;
22156:                                 }
22157:                             }
22158:                         } else {
22159:                             if ($inuse == 1) {
22160:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22161:                                 $changes{$prefix}{$type} = 1;
22162:                             }
22163:                         } 
22164:                     } else {
22165:                         if ($inuse == 1) {
22166:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22167:                             $changes{$prefix}{$type} = 1;
22168:                         }
22169:                     }
22170:                 } else {
22171:                     if ($inuse == 1) {
22172:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22173:                         $changes{$prefix}{$type} = 1;
22174:                     }
22175:                 }
22176:             }
22177:         }
22178:     }
22179: 
22180:     my @alldoms = &Apache::lonnet::all_domains();
22181:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22182:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
22183:     my $savespares;
22184: 
22185:     foreach my $lonhost (sort(keys(%servers))) {
22186:         my $serverhomeID =
22187:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
22188:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
22189:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
22190:         my %spareschg;
22191:         foreach my $type (@{$types{'spares'}}) {
22192:             my @okspares;
22193:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
22194:             foreach my $server (@checked) {
22195:                 if (&Apache::lonnet::hostname($server) ne '') {
22196:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
22197:                         unless (grep(/^\Q$server\E$/,@okspares)) {
22198:                             push(@okspares,$server);
22199:                         }
22200:                     }
22201:                 }
22202:             }
22203:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
22204:             my $newspare;
22205:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
22206:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
22207:                     $newspare = $new;
22208:                 }
22209:             }
22210:             my @spares;
22211:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
22212:                 @spares = sort(@okspares,$newspare);
22213:             } else {
22214:                 @spares = sort(@okspares);
22215:             }
22216:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
22217:             if (ref($spareid{$lonhost}) eq 'HASH') {
22218:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
22219:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
22220:                     if (@diffs > 0) {
22221:                         $spareschg{$type} = 1;
22222:                     }
22223:                 }
22224:             }
22225:         }
22226:         if (keys(%spareschg) > 0) {
22227:             $changes{'spares'}{$lonhost} = \%spareschg;
22228:         }
22229:     }
22230:     $defaultshash{'usersessions'}{'offloadnow'} = {};
22231:     $defaultshash{'usersessions'}{'offloadoth'} = {};
22232:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
22233:     my @okoffload;
22234:     if (@offloadnow) {
22235:         foreach my $server (@offloadnow) {
22236:             if (&Apache::lonnet::hostname($server) ne '') {
22237:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
22238:                     push(@okoffload,$server);
22239:                 }
22240:             }
22241:         }
22242:         if (@okoffload) {
22243:             foreach my $lonhost (@okoffload) {
22244:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
22245:             }
22246:         }
22247:     }
22248:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
22249:     my @okoffloadoth;
22250:     if (@offloadoth) {
22251:         foreach my $server (@offloadoth) {
22252:             if (&Apache::lonnet::hostname($server) ne '') {
22253:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
22254:                     push(@okoffloadoth,$server);
22255:                 }
22256:             }
22257:         }
22258:         if (@okoffloadoth) {
22259:             foreach my $lonhost (@okoffloadoth) {
22260:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
22261:             }
22262:         }
22263:     }
22264:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
22265:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
22266:             if (ref($changes{'spares'}) eq 'HASH') {
22267:                 if (keys(%{$changes{'spares'}}) > 0) {
22268:                     $savespares = 1;
22269:                 }
22270:             }
22271:         } else {
22272:             $savespares = 1;
22273:         }
22274:         foreach my $offload ('offloadnow','offloadoth') {
22275:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
22276:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
22277:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
22278:                         $changes{$offload} = 1;
22279:                         last;
22280:                     }
22281:                 }
22282:                 unless ($changes{$offload}) {
22283:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
22284:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
22285:                             $changes{$offload} = 1;
22286:                             last;
22287:                         }
22288:                     }
22289:                 }
22290:             } else {
22291:                 if (($offload eq 'offloadnow') && (@okoffload)) {
22292:                      $changes{'offloadnow'} = 1;
22293:                 }
22294:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
22295:                     $changes{'offloadoth'} = 1;
22296:                 }
22297:             } 
22298:         }
22299:     } else {
22300:         if (@okoffload) {
22301:             $changes{'offloadnow'} = 1;
22302:         }
22303:         if (@okoffloadoth) {
22304:             $changes{'offloadoth'} = 1;
22305:         }
22306:     }
22307:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
22308:     if ((keys(%changes) > 0) || ($savespares)) {
22309:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22310:                                                  $dom);
22311:         if ($putresult eq 'ok') {
22312:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22313:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
22314:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
22315:                 }
22316:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
22317:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
22318:                 }
22319:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22320:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
22321:                 }
22322:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22323:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
22324:                 }
22325:             }
22326:             my $cachetime = 24*60*60;
22327:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22328:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
22329:             if (ref($lastactref) eq 'HASH') {
22330:                 $lastactref->{'domdefaults'} = 1;
22331:                 $lastactref->{'usersessions'} = 1;
22332:             }
22333:             if (keys(%changes) > 0) {
22334:                 my %lt = &usersession_titles();
22335:                 $resulttext = &mt('Changes made:').'<ul>';
22336:                 foreach my $prefix (@prefixes) {
22337:                     if (ref($changes{$prefix}) eq 'HASH') {
22338:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22339:                         if ($prefix eq 'spares') {
22340:                             if (ref($changes{$prefix}) eq 'HASH') {
22341:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
22342:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
22343:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
22344:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
22345:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
22346:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
22347:                                         foreach my $type (@{$types{$prefix}}) {
22348:                                             if ($changes{$prefix}{$lonhost}{$type}) {
22349:                                                 my $offloadto = &mt('None');
22350:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
22351:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
22352:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
22353:                                                     }
22354:                                                 }
22355:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
22356:                                             }
22357:                                         }
22358:                                     }
22359:                                     $resulttext .= '</li>';
22360:                                 }
22361:                             }
22362:                         } else {
22363:                             foreach my $type (@{$types{$prefix}}) {
22364:                                 if (defined($changes{$prefix}{$type})) {
22365:                                     my ($newvalue,$notinuse);
22366:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22367:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
22368:                                             if ($type eq 'version') {
22369:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
22370:                                             } else {
22371:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22372:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
22373:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
22374:                                                     }
22375:                                                 } else {
22376:                                                     $notinuse = 1;
22377:                                                 }
22378:                                             }
22379:                                         }
22380:                                     }
22381:                                     if ($newvalue eq '') {
22382:                                         if ($type eq 'version') {
22383:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
22384:                                         } elsif ($notinuse) {
22385:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22386:                                         } else {
22387:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22388:                                         }
22389:                                     } else {
22390:                                         if ($type eq 'version') {
22391:                                             $newvalue .= ' '.&mt('(or later)');
22392:                                         }
22393:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22394:                                     }
22395:                                 }
22396:                             }
22397:                         }
22398:                         $resulttext .= '</ul>';
22399:                     }
22400:                 }
22401:                 if ($changes{'offloadnow'}) {
22402:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22403:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
22404:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
22405:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
22406:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22407:                             }
22408:                             $resulttext .= '</ul>';
22409:                         } else {
22410:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
22411:                         }
22412:                     } else {
22413:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
22414:                     }
22415:                 }
22416:                 if ($changes{'offloadoth'}) {
22417:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22418:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
22419:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
22420:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
22421:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22422:                             }
22423:                             $resulttext .= '</ul>';
22424:                         } else {
22425:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
22426:                         }
22427:                     } else {
22428:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
22429:                     }
22430:                 }
22431:                 $resulttext .= '</ul>';
22432:             } else {
22433:                 $resulttext = $nochgmsg;
22434:             }
22435:         } else {
22436:             $resulttext = '<span class="LC_error">'.
22437:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22438:         }
22439:     } else {
22440:         $resulttext = $nochgmsg;
22441:     }
22442:     return $resulttext;
22443: }
22444: 
22445: sub modify_ssl {
22446:     my ($dom,$lastactref,%domconfig) = @_;
22447:     my (%by_ip,%by_location,@intdoms,@instdoms);
22448:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22449:     my @locations = sort(keys(%by_location));
22450:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22451:     my (%defaultshash,%changes);
22452:     my $action = 'ssl';
22453:     my @prefixes = ('connto','connfrom','replication');
22454:     foreach my $prefix (@prefixes) {
22455:         $defaultshash{$action}{$prefix} = {};
22456:     }
22457:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22458:     my $resulttext;
22459:     my %iphost = &Apache::lonnet::get_iphost();
22460:     my @reptypes = ('certreq','nocertreq');
22461:     my @connecttypes = ('dom','intdom','other');
22462:     my %types = (
22463:                   connto      => \@connecttypes,
22464:                   connfrom    => \@connecttypes,
22465:                   replication => \@reptypes,
22466:                 );
22467:     foreach my $prefix (sort(keys(%types))) {
22468:         foreach my $type (@{$types{$prefix}}) {
22469:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22470:                 my $value = 'yes';
22471:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
22472:                     $value = $env{'form.'.$prefix.'_'.$type};
22473:                 }
22474:                 if (ref($domconfig{$action}) eq 'HASH') {
22475:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22476:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
22477:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
22478:                                 $changes{$prefix}{$type} = 1;
22479:                             }
22480:                             $defaultshash{$action}{$prefix}{$type} = $value;
22481:                         } else {
22482:                             $defaultshash{$action}{$prefix}{$type} = $value;
22483:                             $changes{$prefix}{$type} = 1;
22484:                         }
22485:                     } else {
22486:                         $defaultshash{$action}{$prefix}{$type} = $value;
22487:                         $changes{$prefix}{$type} = 1;
22488:                     }
22489:                 } else {
22490:                     $defaultshash{$action}{$prefix}{$type} = $value;
22491:                     $changes{$prefix}{$type} = 1;
22492:                 }
22493:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
22494:                     delete($changes{$prefix}{$type});
22495:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
22496:                     delete($changes{$prefix}{$type});
22497:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
22498:                     delete($changes{$prefix}{$type});
22499:                 }
22500:             } elsif ($prefix eq 'replication') {
22501:                 if (@locations > 0) {
22502:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22503:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22504:                     my @okvals;
22505:                     foreach my $val (@vals) {
22506:                         if ($val =~ /:/) {
22507:                             my @items = split(/:/,$val);
22508:                             foreach my $item (@items) {
22509:                                 if (ref($by_location{$item}) eq 'ARRAY') {
22510:                                     push(@okvals,$item);
22511:                                 }
22512:                             }
22513:                         } else {
22514:                             if (ref($by_location{$val}) eq 'ARRAY') {
22515:                                 push(@okvals,$val);
22516:                             }
22517:                         }
22518:                     }
22519:                     @okvals = sort(@okvals);
22520:                     if (ref($domconfig{$action}) eq 'HASH') {
22521:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22522:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
22523:                                 if ($inuse == 0) {
22524:                                     $changes{$prefix}{$type} = 1;
22525:                                 } else {
22526:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22527:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
22528:                                     if (@changed > 0) {
22529:                                         $changes{$prefix}{$type} = 1;
22530:                                     }
22531:                                 }
22532:                             } else {
22533:                                 if ($inuse == 1) {
22534:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22535:                                     $changes{$prefix}{$type} = 1;
22536:                                 }
22537:                             }
22538:                         } else {
22539:                             if ($inuse == 1) {
22540:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
22541:                                 $changes{$prefix}{$type} = 1;
22542:                             }
22543:                         }
22544:                     } else {
22545:                         if ($inuse == 1) {
22546:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
22547:                             $changes{$prefix}{$type} = 1;
22548:                         }
22549:                     }
22550:                 }
22551:             }
22552:         }
22553:     }
22554:     if (keys(%changes)) {
22555:         foreach my $prefix (keys(%changes)) {
22556:             if (ref($changes{$prefix}) eq 'HASH') {
22557:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
22558:                     delete($changes{$prefix});
22559:                 }
22560:             } else {
22561:                 delete($changes{$prefix});
22562:             }
22563:         }
22564:     }
22565:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
22566:     if (keys(%changes) > 0) {
22567:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22568:                                                  $dom);
22569:         if ($putresult eq 'ok') {
22570:             if (ref($defaultshash{$action}) eq 'HASH') {
22571:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
22572:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
22573:                 }
22574:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
22575:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
22576:                 }
22577:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
22578:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
22579:                 }
22580:             }
22581:             my $cachetime = 24*60*60;
22582:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22583:             if (ref($lastactref) eq 'HASH') {
22584:                 $lastactref->{'domdefaults'} = 1;
22585:             }
22586:             if (keys(%changes) > 0) {
22587:                 my %titles = &ssl_titles();
22588:                 $resulttext = &mt('Changes made:').'<ul>';
22589:                 foreach my $prefix (@prefixes) {
22590:                     if (ref($changes{$prefix}) eq 'HASH') {
22591:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
22592:                         foreach my $type (@{$types{$prefix}}) {
22593:                             if (defined($changes{$prefix}{$type})) {
22594:                                 my ($newvalue,$notinuse);
22595:                                 if (ref($defaultshash{$action}) eq 'HASH') {
22596:                                     if (ref($defaultshash{$action}{$prefix})) {
22597:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22598:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
22599:                                         } else {
22600:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
22601:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
22602:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
22603:                                                 }
22604:                                             } else {
22605:                                                 $notinuse = 1;
22606:                                             }
22607:                                         }
22608:                                     }
22609:                                     if ($notinuse) {
22610:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
22611:                                     } elsif ($newvalue eq '') {
22612:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
22613:                                     } else {
22614:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
22615:                                     }
22616:                                 }
22617:                             }
22618:                         }
22619:                         $resulttext .= '</ul>';
22620:                     }
22621:                 }
22622:             } else {
22623:                 $resulttext = $nochgmsg;
22624:             }
22625:         } else {
22626:             $resulttext = '<span class="LC_error">'.
22627:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22628:         }
22629:     } else {
22630:         $resulttext = $nochgmsg;
22631:     }
22632:     return $resulttext;
22633: }
22634: 
22635: sub modify_trust {
22636:     my ($dom,$lastactref,%domconfig) = @_;
22637:     my (%by_ip,%by_location,@intdoms,@instdoms);
22638:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22639:     my @locations = sort(keys(%by_location));
22640:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
22641:     my @types = ('exc','inc');
22642:     my (%defaultshash,%changes);
22643:     foreach my $prefix (@prefixes) {
22644:         $defaultshash{'trust'}{$prefix} = {};
22645:     }
22646:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22647:     my $resulttext;
22648:     foreach my $prefix (@prefixes) {
22649:         foreach my $type (@types) {
22650:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22651:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22652:             my @okvals;
22653:             foreach my $val (@vals) {
22654:                 if ($val =~ /:/) {
22655:                     my @items = split(/:/,$val);
22656:                     foreach my $item (@items) {
22657:                         if (ref($by_location{$item}) eq 'ARRAY') {
22658:                             push(@okvals,$item);
22659:                         }
22660:                     }
22661:                 } else {
22662:                     if (ref($by_location{$val}) eq 'ARRAY') {
22663:                         push(@okvals,$val);
22664:                     }
22665:                 }
22666:             }
22667:             @okvals = sort(@okvals);
22668:             if (ref($domconfig{'trust'}) eq 'HASH') {
22669:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
22670:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22671:                         if ($inuse == 0) {
22672:                             $changes{$prefix}{$type} = 1;
22673:                         } else {
22674:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22675:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
22676:                             if (@changed > 0) {
22677:                                 $changes{$prefix}{$type} = 1;
22678:                             }
22679:                         }
22680:                     } else {
22681:                         if ($inuse == 1) {
22682:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22683:                             $changes{$prefix}{$type} = 1;
22684:                         }
22685:                     }
22686:                 } else {
22687:                     if ($inuse == 1) {
22688:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22689:                         $changes{$prefix}{$type} = 1;
22690:                     }
22691:                 }
22692:             } else {
22693:                 if ($inuse == 1) {
22694:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22695:                     $changes{$prefix}{$type} = 1;
22696:                 }
22697:             }
22698:         }
22699:     }
22700:     my $nochgmsg = &mt('No changes made to trust settings.');
22701:     if (keys(%changes) > 0) {
22702:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22703:                                                  $dom);
22704:         if ($putresult eq 'ok') {
22705:             if (ref($defaultshash{'trust'}) eq 'HASH') {
22706:                 foreach my $prefix (@prefixes) {
22707:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
22708:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
22709:                     }
22710:                 }
22711:             }
22712:             my $cachetime = 24*60*60;
22713:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22714:             if (ref($lastactref) eq 'HASH') {
22715:                 $lastactref->{'domdefaults'} = 1;
22716:             }
22717:             if (keys(%changes) > 0) {
22718:                 my %lt = &trust_titles();
22719:                 $resulttext = &mt('Changes made:').'<ul>';
22720:                 foreach my $prefix (@prefixes) {
22721:                     if (ref($changes{$prefix}) eq 'HASH') {
22722:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22723:                         foreach my $type (@types) {
22724:                             if (defined($changes{$prefix}{$type})) {
22725:                                 my ($newvalue,$notinuse);
22726:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
22727:                                     if (ref($defaultshash{'trust'}{$prefix})) {
22728:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22729:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
22730:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
22731:                                             }
22732:                                         } else {
22733:                                             $notinuse = 1;
22734:                                         }
22735:                                     }
22736:                                 }
22737:                                 if ($notinuse) {
22738:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22739:                                 } elsif ($newvalue eq '') {
22740:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22741:                                 } else {
22742:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22743:                                 }
22744:                             }
22745:                         }
22746:                         $resulttext .= '</ul>';
22747:                     }
22748:                 }
22749:                 $resulttext .= '</ul>';
22750:             } else {
22751:                 $resulttext = $nochgmsg;
22752:             }
22753:         } else {
22754:             $resulttext = '<span class="LC_error">'.
22755:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22756:         }
22757:     } else {
22758:         $resulttext = $nochgmsg;
22759:     }
22760:     return $resulttext;
22761: }
22762: 
22763: sub modify_loadbalancing {
22764:     my ($dom,%domconfig) = @_;
22765:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
22766:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
22767:     my ($othertitle,$usertypes,$types) =
22768:         &Apache::loncommon::sorted_inst_types($dom);
22769:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22770:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
22771:     my @sparestypes = ('primary','default');
22772:     my %typetitles = &sparestype_titles();
22773:     my $resulttext;
22774:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
22775:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22776:         %existing = %{$domconfig{'loadbalancing'}};
22777:     }
22778:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
22779:                               \%currtargets,\%currrules,\%currcookies);
22780:     my ($saveloadbalancing,%defaultshash,%changes);
22781:     my ($alltypes,$othertypes,$titles) =
22782:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
22783:     my %ruletitles = &offloadtype_text();
22784:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
22785:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
22786:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
22787:         if ($balancer eq '') {
22788:             next;
22789:         }
22790:         if (!exists($servers{$balancer})) {
22791:             if (exists($currbalancer{$balancer})) {
22792:                 push(@{$changes{'delete'}},$balancer);
22793:             }
22794:             next;
22795:         }
22796:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
22797:             push(@{$changes{'delete'}},$balancer);
22798:             next;
22799:         }
22800:         if (!exists($currbalancer{$balancer})) {
22801:             push(@{$changes{'add'}},$balancer);
22802:         }
22803:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
22804:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
22805:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
22806:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22807:             $saveloadbalancing = 1;
22808:         }
22809:         foreach my $sparetype (@sparestypes) {
22810:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
22811:             my @offloadto;
22812:             foreach my $target (@targets) {
22813:                 if (($servers{$target}) && ($target ne $balancer)) {
22814:                     if ($sparetype eq 'default') {
22815:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
22816:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
22817:                         }
22818:                     }
22819:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
22820:                         push(@offloadto,$target);
22821:                     }
22822:                 }
22823:             }
22824:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
22825:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
22826:                     push(@offloadto,$balancer);
22827:                 }
22828:             }
22829:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
22830:         }
22831:         if ($env{'form.loadbalancing_cookie_'.$i}) {
22832:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
22833:             if (exists($currbalancer{$balancer})) { 
22834:                 unless ($currcookies{$balancer}) {
22835:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
22836:                 }
22837:             }
22838:         } elsif (exists($currbalancer{$balancer})) {
22839:             if ($currcookies{$balancer}) {
22840:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
22841:             }
22842:         }
22843:         if (ref($currtargets{$balancer}) eq 'HASH') {
22844:             foreach my $sparetype (@sparestypes) {
22845:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
22846:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
22847:                     if (@targetdiffs > 0) {
22848:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22849:                     }
22850:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22851:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22852:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22853:                     }
22854:                 }
22855:             }
22856:         } else {
22857:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
22858:                 foreach my $sparetype (@sparestypes) {
22859:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22860:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22861:                             $changes{'curr'}{$balancer}{'targets'} = 1;
22862:                         }
22863:                     }
22864:                 }
22865:             }
22866:         }
22867:         my $ishomedom;
22868:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
22869:             $ishomedom = 1;
22870:         }
22871:         if (ref($alltypes) eq 'ARRAY') {
22872:             foreach my $type (@{$alltypes}) {
22873:                 my $rule;
22874:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
22875:                          (!$ishomedom)) {
22876:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
22877:                 }
22878:                 if ($rule eq 'specific') {
22879:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
22880:                     if (exists($servers{$specifiedhost})) {
22881:                         $rule = $specifiedhost;
22882:                     }
22883:                 }
22884:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
22885:                 if (ref($currrules{$balancer}) eq 'HASH') {
22886:                     if ($rule ne $currrules{$balancer}{$type}) {
22887:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22888:                     }
22889:                 } elsif ($rule ne '') {
22890:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22891:                 }
22892:             }
22893:         }
22894:     }
22895:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
22896:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
22897:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
22898:             $defaultshash{'loadbalancing'} = {};
22899:         }
22900:         my $putresult = &Apache::lonnet::put_dom('configuration',
22901:                                                  \%defaultshash,$dom);
22902:         if ($putresult eq 'ok') {
22903:             if (keys(%changes) > 0) {
22904:                 my %toupdate;
22905:                 if (ref($changes{'delete'}) eq 'ARRAY') {
22906:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
22907:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
22908:                         $toupdate{$balancer} = 1;
22909:                     }
22910:                 }
22911:                 if (ref($changes{'add'}) eq 'ARRAY') {
22912:                     foreach my $balancer (sort(@{$changes{'add'}})) {
22913:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
22914:                         $toupdate{$balancer} = 1;
22915:                     }
22916:                 }
22917:                 if (ref($changes{'curr'}) eq 'HASH') {
22918:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
22919:                         $toupdate{$balancer} = 1;
22920:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
22921:                             if ($changes{'curr'}{$balancer}{'targets'}) {
22922:                                 my %offloadstr;
22923:                                 foreach my $sparetype (@sparestypes) {
22924:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22925:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22926:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
22927:                                         }
22928:                                     }
22929:                                 }
22930:                                 if (keys(%offloadstr) == 0) {
22931:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
22932:                                 } else {
22933:                                     my $showoffload;
22934:                                     foreach my $sparetype (@sparestypes) {
22935:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
22936:                                         if (defined($offloadstr{$sparetype})) {
22937:                                             $showoffload .= $offloadstr{$sparetype};
22938:                                         } else {
22939:                                             $showoffload .= &mt('None');
22940:                                         }
22941:                                         $showoffload .= ('&nbsp;'x3);
22942:                                     }
22943:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
22944:                                 }
22945:                             }
22946:                         }
22947:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
22948:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
22949:                                 foreach my $type (@{$alltypes}) {
22950:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
22951:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
22952:                                         my $balancetext;
22953:                                         if ($rule eq '') {
22954:                                             $balancetext =  $ruletitles{'default'};
22955:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
22956:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
22957:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
22958:                                                 foreach my $sparetype (@sparestypes) {
22959:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22960:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
22961:                                                     }
22962:                                                 }
22963:                                                 foreach my $item (@{$alltypes}) {
22964:                                                     next if ($item =~  /^_LC_ipchange/);
22965:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
22966:                                                     if ($hasrule eq 'homeserver') {
22967:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
22968:                                                     } else {
22969:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
22970:                                                             if ($servers{$hasrule}) {
22971:                                                                 $toupdate{$hasrule} = 1;
22972:                                                             }
22973:                                                         }
22974:                                                     }
22975:                                                 }
22976:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
22977:                                                     $balancetext =  $ruletitles{$rule};
22978:                                                 } else {
22979:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
22980:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
22981:                                                     if ($receiver) {
22982:                                                         $toupdate{$receiver};
22983:                                                     }
22984:                                                 }
22985:                                             } else {
22986:                                                 $balancetext =  $ruletitles{$rule};
22987:                                             }
22988:                                         } else {
22989:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
22990:                                         }
22991:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
22992:                                     }
22993:                                 }
22994:                             }
22995:                         }
22996:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
22997:                             if ($currcookies{$balancer}) {
22998:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
22999:                                                           $balancer).'</li>';
23000:                             } else {
23001:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
23002:                                                           $balancer).'</li>';
23003:                             }
23004:                         }
23005:                     }
23006:                 }
23007:                 if (keys(%toupdate)) {
23008:                     my %thismachine;
23009:                     my $updatedhere;
23010:                     my $cachetime = 60*60*24;
23011:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23012:                     foreach my $lonhost (keys(%toupdate)) {
23013:                         if ($thismachine{$lonhost}) {
23014:                             unless ($updatedhere) {
23015:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
23016:                                                               $defaultshash{'loadbalancing'},
23017:                                                               $cachetime);
23018:                                 $updatedhere = 1;
23019:                             }
23020:                         } else {
23021:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
23022:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
23023:                         }
23024:                     }
23025:                 }
23026:                 if ($resulttext ne '') {
23027:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
23028:                 } else {
23029:                     $resulttext = $nochgmsg;
23030:                 }
23031:             } else {
23032:                 $resulttext = $nochgmsg;
23033:             }
23034:         } else {
23035:             $resulttext = '<span class="LC_error">'.
23036:                           &mt('An error occurred: [_1]',$putresult).'</span>';
23037:         }
23038:     } else {
23039:         $resulttext = $nochgmsg;
23040:     }
23041:     return $resulttext;
23042: }
23043: 
23044: sub recurse_check {
23045:     my ($chkcats,$categories,$depth,$name) = @_;
23046:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
23047:         my $chg = 0;
23048:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
23049:             my $category = $chkcats->[$depth]{$name}[$j];
23050:             my $item;
23051:             if ($category eq '') {
23052:                 $chg ++;
23053:             } else {
23054:                 my $deeper = $depth + 1;
23055:                 $item = &escape($category).':'.&escape($name).':'.$depth;
23056:                 if ($chg) {
23057:                     $categories->{$item} -= $chg;
23058:                 }
23059:                 &recurse_check($chkcats,$categories,$deeper,$category);
23060:                 $deeper --;
23061:             }
23062:         }
23063:     }
23064:     return;
23065: }
23066: 
23067: sub recurse_cat_deletes {
23068:     my ($item,$coursecategories,$deletions) = @_;
23069:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
23070:     my $subdepth = $depth + 1;
23071:     if (ref($coursecategories) eq 'HASH') {
23072:         foreach my $subitem (keys(%{$coursecategories})) {
23073:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
23074:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
23075:                 delete($coursecategories->{$subitem});
23076:                 $deletions->{$subitem} = 1;
23077:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
23078:             }
23079:         }
23080:     }
23081:     return;
23082: }
23083: 
23084: sub active_dc_picker {
23085:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
23086:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
23087:     my @domcoord = keys(%domcoords);
23088:     if (keys(%currhash)) {
23089:         foreach my $dc (keys(%currhash)) {
23090:             unless (exists($domcoords{$dc})) {
23091:                 push(@domcoord,$dc);
23092:             }
23093:         }
23094:     }
23095:     @domcoord = sort(@domcoord);
23096:     my $numdcs = scalar(@domcoord);
23097:     my $rows = 0;
23098:     my $table;
23099:     if ($numdcs > 1) {
23100:         $table = '<table>';
23101:         for (my $i=0; $i<@domcoord; $i++) {
23102:             my $rem = $i%($numinrow);
23103:             if ($rem == 0) {
23104:                 if ($i > 0) {
23105:                     $table .= '</tr>';
23106:                 }
23107:                 $table .= '<tr>';
23108:                 $rows ++;
23109:             }
23110:             my $check = '';
23111:             if ($inputtype eq 'radio') {
23112:                 if (keys(%currhash) == 0) {
23113:                     if (!$i) {
23114:                         $check = ' checked="checked"';
23115:                     }
23116:                 } elsif (exists($currhash{$domcoord[$i]})) {
23117:                     $check = ' checked="checked"';
23118:                 }
23119:             } else {
23120:                 if (exists($currhash{$domcoord[$i]})) {
23121:                     $check = ' checked="checked"';
23122:                 }
23123:             }
23124:             if ($i == @domcoord - 1) {
23125:                 my $colsleft = $numinrow - $rem;
23126:                 if ($colsleft > 1) {
23127:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
23128:                 } else {
23129:                     $table .= '<td class="LC_left_item">';
23130:                 }
23131:             } else {
23132:                 $table .= '<td class="LC_left_item">';
23133:             }
23134:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
23135:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23136:             $table .= '<span class="LC_nobreak"><label>'.
23137:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
23138:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
23139:             if ($user ne $dcname.':'.$dcdom) {
23140:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23141:             }
23142:             $table .= '</label></span></td>';
23143:         }
23144:         $table .= '</tr></table>';
23145:     } elsif ($numdcs == 1) {
23146:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
23147:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23148:         if ($inputtype eq 'radio') {
23149:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
23150:             if ($user ne $dcname.':'.$dcdom) {
23151:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23152:             }
23153:         } else {
23154:             my $check;
23155:             if (exists($currhash{$domcoord[0]})) {
23156:                 $check = ' checked="checked"';
23157:             }
23158:             $table = '<span class="LC_nobreak"><label>'.
23159:                      '<input type="checkbox" name="'.$name.'" '.
23160:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
23161:             if ($user ne $dcname.':'.$dcdom) {
23162:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23163:             }
23164:             $table .= '</label></span>';
23165:             $rows ++;
23166:         }
23167:     }
23168:     return ($numdcs,$table,$rows);
23169: }
23170: 
23171: sub usersession_titles {
23172:     return &Apache::lonlocal::texthash(
23173:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
23174:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
23175:                spares => 'Servers offloaded to, when busy',
23176:                version => 'LON-CAPA version requirement',
23177:                excludedomain => 'Allow all, but exclude specific domains',
23178:                includedomain => 'Deny all, but include specific domains',
23179:                primary => 'Primary (checked first)',
23180:                default => 'Default',
23181:            );
23182: }
23183: 
23184: sub id_for_thisdom {
23185:     my (%servers) = @_;
23186:     my %altids;
23187:     foreach my $server (keys(%servers)) {
23188:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
23189:         if ($serverhome ne $server) {
23190:             $altids{$serverhome} = $server;
23191:         }
23192:     }
23193:     return %altids;
23194: }
23195: 
23196: sub count_servers {
23197:     my ($currbalancer,%servers) = @_;
23198:     my (@spares,$numspares);
23199:     foreach my $lonhost (sort(keys(%servers))) {
23200:         next if ($currbalancer eq $lonhost);
23201:         push(@spares,$lonhost);
23202:     }
23203:     if ($currbalancer) {
23204:         $numspares = scalar(@spares);
23205:     } else {
23206:         $numspares = scalar(@spares) - 1;
23207:     }
23208:     return ($numspares,@spares);
23209: }
23210: 
23211: sub lonbalance_targets_js {
23212:     my ($dom,$types,$servers,$settings) = @_;
23213:     my $select = &mt('Select');
23214:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
23215:     if (ref($servers) eq 'HASH') {
23216:         $alltargets = join("','",sort(keys(%{$servers})));
23217:         my @homedoms;
23218:         foreach my $server (sort(keys(%{$servers}))) {
23219:             if (&Apache::lonnet::host_domain($server) eq $dom) {
23220:                 push(@homedoms,'1');
23221:             } else {
23222:                 push(@homedoms,'0');
23223:             }
23224:         }
23225:         $allishome = join("','",@homedoms);
23226:     }
23227:     if (ref($types) eq 'ARRAY') {
23228:         if (@{$types} > 0) {
23229:             @alltypes = @{$types};
23230:         }
23231:     }
23232:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
23233:     $allinsttypes = join("','",@alltypes);
23234:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
23235:     if (ref($settings) eq 'HASH') {
23236:         %existing = %{$settings};
23237:     }
23238:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
23239:                               \%currtargets,\%currrules,\%currcookies);
23240:     my $balancers = join("','",sort(keys(%currbalancer)));
23241:     return <<"END";
23242: 
23243: <script type="text/javascript">
23244: // <![CDATA[
23245: 
23246: currBalancers = new Array('$balancers');
23247: 
23248: function toggleTargets(balnum) {
23249:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23250:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
23251:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
23252:     var prevbalancer = prevhostitem.value;
23253:     var baltotal = document.getElementById('loadbalancing_total').value;
23254:     prevhostitem.value = balancer;
23255:     if (prevbalancer != '') {
23256:         var prevIdx = currBalancers.indexOf(prevbalancer);
23257:         if (prevIdx != -1) {
23258:             currBalancers.splice(prevIdx,1);
23259:         }
23260:     }
23261:     if (balancer == '') {
23262:         hideSpares(balnum);
23263:     } else {
23264:         var currIdx = currBalancers.indexOf(balancer);
23265:         if (currIdx == -1) {
23266:             currBalancers.push(balancer);
23267:         }
23268:         var homedoms = new Array('$allishome');
23269:         var ishomedom = homedoms[lonhostitem.selectedIndex];
23270:         showSpares(balancer,ishomedom,balnum);
23271:     }
23272:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
23273:     return;
23274: }
23275: 
23276: function showSpares(balancer,ishomedom,balnum) {
23277:     var alltargets = new Array('$alltargets');
23278:     var insttypes = new Array('$allinsttypes');
23279:     var offloadtypes = new Array('primary','default');
23280: 
23281:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
23282:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
23283:  
23284:     for (var i=0; i<offloadtypes.length; i++) {
23285:         var count = 0;
23286:         for (var j=0; j<alltargets.length; j++) {
23287:             if (alltargets[j] != balancer) {
23288:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
23289:                 item.value = alltargets[j];
23290:                 item.style.textAlign='left';
23291:                 item.style.textFace='normal';
23292:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
23293:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
23294:                     item.disabled = '';
23295:                 } else {
23296:                     item.disabled = 'disabled';
23297:                     item.checked = false;
23298:                 }
23299:                 count ++;
23300:             }
23301:         }
23302:     }
23303:     for (var k=0; k<insttypes.length; k++) {
23304:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
23305:             if (ishomedom == 1) {
23306:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23307:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23308:             } else {
23309:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23310:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23311:             }
23312:         } else {
23313:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23314:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23315:         }
23316:         if ((insttypes[k] != '_LC_external') && 
23317:             ((insttypes[k] != '_LC_internetdom') ||
23318:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
23319:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
23320:             item.options.length = 0;
23321:             item.options[0] = new Option("","",true,true);
23322:             var idx = 0;
23323:             for (var m=0; m<alltargets.length; m++) {
23324:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
23325:                     idx ++;
23326:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23327:                 }
23328:             }
23329:         }
23330:     }
23331:     return;
23332: }
23333: 
23334: function hideSpares(balnum) {
23335:     var alltargets = new Array('$alltargets');
23336:     var insttypes = new Array('$allinsttypes');
23337:     var offloadtypes = new Array('primary','default');
23338: 
23339:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
23340:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
23341: 
23342:     var total = alltargets.length - 1;
23343:     for (var i=0; i<offloadtypes; i++) {
23344:         for (var j=0; j<total; j++) {
23345:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
23346:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
23347:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
23348:         }
23349:     }
23350:     for (var k=0; k<insttypes.length; k++) {
23351:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23352:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23353:         if (insttypes[k] != '_LC_external') {
23354:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
23355:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
23356:         }
23357:     }
23358:     return;
23359: }
23360: 
23361: function checkOffloads(item,balnum,type) {
23362:     var alltargets = new Array('$alltargets');
23363:     var offloadtypes = new Array('primary','default');
23364:     if (item.checked) {
23365:         var total = alltargets.length - 1;
23366:         var other;
23367:         if (type == offloadtypes[0]) {
23368:             other = offloadtypes[1];
23369:         } else {
23370:             other = offloadtypes[0];
23371:         }
23372:         for (var i=0; i<total; i++) {
23373:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
23374:             if (server == item.value) {
23375:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
23376:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
23377:                 }
23378:             }
23379:         }
23380:     }
23381:     return;
23382: }
23383: 
23384: function singleServerToggle(balnum,type) {
23385:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
23386:     if (offloadtoSelIdx == 0) {
23387:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
23388:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23389: 
23390:     } else {
23391:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
23392:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23393:     }
23394:     return;
23395: }
23396: 
23397: function balanceruleChange(formname,balnum,type) {
23398:     if (type == '_LC_external') {
23399:         return;
23400:     }
23401:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
23402:     for (var i=0; i<typesRules.length; i++) {
23403:         if (formname.elements[typesRules[i]].checked) {
23404:             if (formname.elements[typesRules[i]].value != 'specific') {
23405:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
23406:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23407:             } else {
23408:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23409:             }
23410:         }
23411:     }
23412:     return;
23413: }
23414: 
23415: function balancerDeleteChange(balnum) {
23416:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23417:     var baltotal = document.getElementById('loadbalancing_total').value;
23418:     var addtarget;
23419:     var removetarget;
23420:     var action = 'delete';
23421:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
23422:         var lonhost = hostitem.value;
23423:         var currIdx = currBalancers.indexOf(lonhost);
23424:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
23425:             if (currIdx != -1) {
23426:                 currBalancers.splice(currIdx,1);
23427:             }
23428:             addtarget = lonhost;
23429:         } else {
23430:             if (currIdx == -1) {
23431:                 currBalancers.push(lonhost);
23432:             }
23433:             removetarget = lonhost;
23434:             action = 'undelete';
23435:         }
23436:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
23437:     }
23438:     return;
23439: }
23440: 
23441: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
23442:     if (baltotal > 1) {
23443:         var offloadtypes = new Array('primary','default');
23444:         var alltargets = new Array('$alltargets');
23445:         var insttypes = new Array('$allinsttypes');
23446:         for (var i=0; i<baltotal; i++) {
23447:             if (i != balnum) {
23448:                 for (var j=0; j<offloadtypes.length; j++) {
23449:                     var total = alltargets.length - 1;
23450:                     for (var k=0; k<total; k++) {
23451:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
23452:                         var server = serveritem.value;
23453:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
23454:                             if (server == addtarget) {
23455:                                 serveritem.disabled = '';
23456:                             }
23457:                         }
23458:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23459:                             if (server == removetarget) {
23460:                                 serveritem.disabled = 'disabled';
23461:                                 serveritem.checked = false;
23462:                             }
23463:                         }
23464:                     }
23465:                 }
23466:                 for (var j=0; j<insttypes.length; j++) {
23467:                     if (insttypes[j] != '_LC_external') {
23468:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
23469:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
23470:                             var currSel = singleserver.selectedIndex;
23471:                             var currVal = singleserver.options[currSel].value;
23472:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
23473:                                 var numoptions = singleserver.options.length;
23474:                                 var needsnew = 1;
23475:                                 for (var k=0; k<numoptions; k++) {
23476:                                     if (singleserver.options[k] == addtarget) {
23477:                                         needsnew = 0;
23478:                                         break;
23479:                                     }
23480:                                 }
23481:                                 if (needsnew == 1) {
23482:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
23483:                                 }
23484:                             }
23485:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23486:                                 singleserver.options.length = 0;
23487:                                 if ((currVal) && (currVal != removetarget)) {
23488:                                     singleserver.options[0] = new Option("","",false,false);
23489:                                 } else {
23490:                                     singleserver.options[0] = new Option("","",true,true);
23491:                                 }
23492:                                 var idx = 0;
23493:                                 for (var m=0; m<alltargets.length; m++) {
23494:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
23495:                                         idx ++;
23496:                                         if (currVal == alltargets[m]) {
23497:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
23498:                                         } else {
23499:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23500:                                         }
23501:                                     }
23502:                                 }
23503:                             }
23504:                         }
23505:                     }
23506:                 }
23507:             }
23508:         }
23509:     }
23510:     return;
23511: }
23512: 
23513: // ]]>
23514: </script>
23515: 
23516: END
23517: }
23518: 
23519: 
23520: sub new_spares_js {
23521:     my @sparestypes = ('primary','default');
23522:     my $types = join("','",@sparestypes);
23523:     my $select = &mt('Select');
23524:     return <<"END";
23525: 
23526: <script type="text/javascript">
23527: // <![CDATA[
23528: 
23529: function updateNewSpares(formname,lonhost) {
23530:     var types = new Array('$types');
23531:     var include = new Array();
23532:     var exclude = new Array();
23533:     for (var i=0; i<types.length; i++) {
23534:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
23535:         for (var j=0; j<spareboxes.length; j++) {
23536:             if (formname.elements[spareboxes[j]].checked) {
23537:                 exclude.push(formname.elements[spareboxes[j]].value);
23538:             } else {
23539:                 include.push(formname.elements[spareboxes[j]].value);
23540:             }
23541:         }
23542:     }
23543:     for (var i=0; i<types.length; i++) {
23544:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
23545:         var selIdx = newSpare.selectedIndex;
23546:         var currnew = newSpare.options[selIdx].value;
23547:         var okSpares = new Array();
23548:         for (var j=0; j<newSpare.options.length; j++) {
23549:             var possible = newSpare.options[j].value;
23550:             if (possible != '') {
23551:                 if (exclude.indexOf(possible) == -1) {
23552:                     okSpares.push(possible);
23553:                 } else {
23554:                     if (currnew == possible) {
23555:                         selIdx = 0;
23556:                     }
23557:                 }
23558:             }
23559:         }
23560:         for (var k=0; k<include.length; k++) {
23561:             if (okSpares.indexOf(include[k]) == -1) {
23562:                 okSpares.push(include[k]);
23563:             }
23564:         }
23565:         okSpares.sort();
23566:         newSpare.options.length = 0;
23567:         if (selIdx == 0) {
23568:             newSpare.options[0] = new Option("$select","",true,true);
23569:         } else {
23570:             newSpare.options[0] = new Option("$select","",false,false);
23571:         }
23572:         for (var m=0; m<okSpares.length; m++) {
23573:             var idx = m+1;
23574:             var selThis = 0;
23575:             if (selIdx != 0) {
23576:                 if (okSpares[m] == currnew) {
23577:                     selThis = 1;
23578:                 }
23579:             }
23580:             if (selThis == 1) {
23581:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
23582:             } else {
23583:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
23584:             }
23585:         }
23586:     }
23587:     return;
23588: }
23589: 
23590: function checkNewSpares(lonhost,type) {
23591:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
23592:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
23593:     if (chosen != '') {
23594:         var othertype;
23595:         var othernewSpare;
23596:         if (type == 'primary') {
23597:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
23598:         }
23599:         if (type == 'default') {
23600:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
23601:         }
23602:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
23603:             othernewSpare.selectedIndex = 0;
23604:         }
23605:     }
23606:     return;
23607: }
23608: 
23609: // ]]>
23610: </script>
23611: 
23612: END
23613: 
23614: }
23615: 
23616: sub common_domprefs_js {
23617:     return <<"END";
23618: 
23619: <script type="text/javascript">
23620: // <![CDATA[
23621: 
23622: function getIndicesByName(formname,item) {
23623:     var group = new Array();
23624:     for (var i=0;i<formname.elements.length;i++) {
23625:         if (formname.elements[i].name == item) {
23626:             group.push(formname.elements[i].id);
23627:         }
23628:     }
23629:     return group;
23630: }
23631: 
23632: // ]]>
23633: </script>
23634: 
23635: END
23636: 
23637: }
23638: 
23639: sub recaptcha_js {
23640:     my %lt = &captcha_phrases();
23641:     return <<"END";
23642: 
23643: <script type="text/javascript">
23644: // <![CDATA[
23645: 
23646: function updateCaptcha(caller,context) {
23647:     var privitem;
23648:     var pubitem;
23649:     var privtext;
23650:     var pubtext;
23651:     var versionitem;
23652:     var versiontext;
23653:     if (document.getElementById(context+'_recaptchapub')) {
23654:         pubitem = document.getElementById(context+'_recaptchapub');
23655:     } else {
23656:         return;
23657:     }
23658:     if (document.getElementById(context+'_recaptchapriv')) {
23659:         privitem = document.getElementById(context+'_recaptchapriv');
23660:     } else {
23661:         return;
23662:     }
23663:     if (document.getElementById(context+'_recaptchapubtxt')) {
23664:         pubtext = document.getElementById(context+'_recaptchapubtxt');
23665:     } else {
23666:         return;
23667:     }
23668:     if (document.getElementById(context+'_recaptchaprivtxt')) {
23669:         privtext = document.getElementById(context+'_recaptchaprivtxt');
23670:     } else {
23671:         return;
23672:     }
23673:     if (document.getElementById(context+'_recaptchaversion')) {
23674:         versionitem = document.getElementById(context+'_recaptchaversion');
23675:     } else {
23676:         return;
23677:     }
23678:     if (document.getElementById(context+'_recaptchavertxt')) {
23679:         versiontext = document.getElementById(context+'_recaptchavertxt');
23680:     } else {
23681:         return;
23682:     }
23683:     if (caller.checked) {
23684:         if (caller.value == 'recaptcha') {
23685:             pubitem.type = 'text';
23686:             privitem.type = 'text';
23687:             pubitem.size = '40';
23688:             privitem.size = '40';
23689:             pubtext.innerHTML = "$lt{'pub'}";
23690:             privtext.innerHTML = "$lt{'priv'}";
23691:             versionitem.type = 'text';
23692:             versionitem.size = '3';
23693:             versiontext.innerHTML = "$lt{'ver'}";
23694:         } else {
23695:             pubitem.type = 'hidden';
23696:             privitem.type = 'hidden';
23697:             versionitem.type = 'hidden';
23698:             pubtext.innerHTML = '';
23699:             privtext.innerHTML = '';
23700:             versiontext.innerHTML = '';
23701:         }
23702:     }
23703:     return;
23704: }
23705: 
23706: // ]]>
23707: </script>
23708: 
23709: END
23710: 
23711: }
23712: 
23713: sub toggle_display_js {
23714:     return <<"END";
23715: 
23716: <script type="text/javascript">
23717: // <![CDATA[
23718: 
23719: function toggleDisplay(domForm,caller) {
23720:     if (document.getElementById(caller)) {
23721:         var divitem = document.getElementById(caller);
23722:         var optionsElement = domForm.coursecredits;
23723:         var checkval = 1;
23724:         var dispval = 'block';
23725:         var selfcreateRegExp = /^cancreate_emailverified/;
23726:         if (caller == 'emailoptions') {
23727:             optionsElement = domForm.cancreate_email;
23728:         }
23729:         if (caller == 'studentsubmission') {
23730:             optionsElement = domForm.postsubmit;
23731:         }
23732:         if (caller == 'cloneinstcode') {
23733:             optionsElement = domForm.canclone;
23734:             checkval = 'instcode';
23735:         }
23736:         if (selfcreateRegExp.test(caller)) {
23737:             optionsElement = domForm.elements[caller];
23738:             checkval = 'other';
23739:             dispval = 'inline'
23740:         }
23741:         if (optionsElement.length) {
23742:             var currval;
23743:             for (var i=0; i<optionsElement.length; i++) {
23744:                 if (optionsElement[i].checked) {
23745:                    currval = optionsElement[i].value;
23746:                 }
23747:             }
23748:             if (currval == checkval) {
23749:                 divitem.style.display = dispval;
23750:             } else {
23751:                 divitem.style.display = 'none';
23752:             }
23753:         }
23754:     }
23755:     return;
23756: }
23757: 
23758: // ]]>
23759: </script>
23760: 
23761: END
23762: 
23763: }
23764: 
23765: sub captcha_phrases {
23766:     return &Apache::lonlocal::texthash (
23767:                  priv => 'Private key',
23768:                  pub  => 'Public key',
23769:                  original  => 'original (CAPTCHA)',
23770:                  recaptcha => 'successor (ReCAPTCHA)',
23771:                  notused   => 'unused',
23772:                  ver => 'ReCAPTCHA version (1 or 2)',
23773:     );
23774: }
23775: 
23776: sub devalidate_remote_domconfs {
23777:     my ($dom,$cachekeys) = @_;
23778:     return unless (ref($cachekeys) eq 'HASH');
23779:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
23780:     my %thismachine;
23781:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23782:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
23783:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
23784:                       'ipaccess');
23785:     my %cache_by_lonhost;
23786:     if (exists($cachekeys->{'samllanding'})) {
23787:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
23788:             my %landing = %{$cachekeys->{'samllanding'}};
23789:             my %domservers = &Apache::lonnet::get_servers($dom);
23790:             if (keys(%domservers)) {
23791:                 foreach my $server (keys(%domservers)) {
23792:                     my @cached;
23793:                     next if ($thismachine{$server});
23794:                     if ($landing{$server}) {
23795:                         push(@cached,&escape('samllanding').':'.&escape($server));
23796:                     }
23797:                     if (@cached) {
23798:                         $cache_by_lonhost{$server} = \@cached;
23799:                     }
23800:                 }
23801:             }
23802:         }
23803:     }
23804:     if (keys(%servers)) {
23805:         foreach my $server (keys(%servers)) {
23806:             next if ($thismachine{$server});
23807:             my @cached;
23808:             foreach my $name (@posscached) {
23809:                 if ($cachekeys->{$name}) {
23810:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
23811:                         if (ref($cachekeys->{$name}) eq 'HASH') {
23812:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
23813:                                 push(@cached,&escape($name).':'.&escape($key));
23814:                             }
23815:                         }
23816:                     } else {
23817:                         push(@cached,&escape($name).':'.&escape($dom));
23818:                     }
23819:                 }
23820:             }
23821:             if ((exists($cache_by_lonhost{$server})) &&
23822:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
23823:                 push(@cached,@{$cache_by_lonhost{$server}});
23824:             }
23825:             if (@cached) {
23826:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
23827:             }
23828:         }
23829:     }
23830:     return;
23831: }
23832: 
23833: 1;

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