File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.411: download - view: text, annotated - select for diffs
Tue Jul 26 01:11:43 2022 UTC (22 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Prevent ISE in unconfigured domain.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.411 2022/07/26 01:11: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:                                  {col1 => 'Mapping for missing usernames via standard log-in',
  332:                                   col2 => 'Rules in use'}],
  333:                       print => \&print_defaults,
  334:                       modify => \&modify_defaults,
  335:                     },
  336:         'wafproxy' =>
  337:                     { text => 'Web Application Firewall/Reverse Proxy',
  338:                       help => 'Domain_Configuration_WAF_Proxy',
  339:                       header => [{col1 => 'Domain(s)',
  340:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  341:                                  },
  342:                                  {col1 => 'Domain(s)',
  343:                                   col2 => 'WAF Configuration',}],
  344:                       print => \&print_wafproxy,
  345:                       modify => \&modify_wafproxy,
  346:                     },
  347:         'passwords' =>
  348:                     { text => 'Passwords (Internal authentication)',
  349:                       help => 'Domain_Configuration_Passwords',
  350:                       header => [{col1 => 'Resetting Forgotten Password',
  351:                                   col2 => 'Settings'},
  352:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  353:                                   col2 => 'Settings'},
  354:                                  {col1 => 'Rules for LON-CAPA Passwords',
  355:                                   col2 => 'Settings'},
  356:                                  {col1 => 'Course Owner Changing Student Passwords',
  357:                                   col2 => 'Settings'}],
  358:                       print => \&print_passwords,
  359:                       modify => \&modify_passwords,
  360:                     },
  361:         'quotas' => 
  362:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  363:                       help => 'Domain_Configuration_Quotas',
  364:                       header => [{col1 => 'User affiliation',
  365:                                   col2 => 'Available tools',
  366:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  367:                       print => \&print_quotas,
  368:                       modify => \&modify_quotas,
  369:                     },
  370:         'autoenroll' =>
  371:                    { text => 'Auto-enrollment settings',
  372:                      help => 'Domain_Configuration_Auto_Enrollment',
  373:                      header => [{col1 => 'Configuration setting',
  374:                                  col2 => 'Value(s)'}],
  375:                      print => \&print_autoenroll,
  376:                      modify => \&modify_autoenroll,
  377:                    },
  378:         'autoupdate' => 
  379:                    { text => 'Auto-update settings',
  380:                      help => 'Domain_Configuration_Auto_Updates',
  381:                      header => [{col1 => 'Setting',
  382:                                  col2 => 'Value',},
  383:                                 {col1 => 'Setting',
  384:                                  col2 => 'Affiliation'},
  385:                                 {col1 => 'User population',
  386:                                  col2 => 'Updatable user data'}],
  387:                      print => \&print_autoupdate,
  388:                      modify => \&modify_autoupdate,
  389:                   },
  390:         'autocreate' => 
  391:                   { text => 'Auto-course creation settings',
  392:                      help => 'Domain_Configuration_Auto_Creation',
  393:                      header => [{col1 => 'Configuration Setting',
  394:                                  col2 => 'Value',}],
  395:                      print => \&print_autocreate,
  396:                      modify => \&modify_autocreate,
  397:                   },
  398:         'directorysrch' => 
  399:                   { text => 'Directory searches',
  400:                     help => 'Domain_Configuration_InstDirectory_Search',
  401:                     header => [{col1 => 'Institutional Directory Setting',
  402:                                 col2 => 'Value',},
  403:                                {col1 => 'LON-CAPA Directory Setting',
  404:                                 col2 => 'Value',}],
  405:                     print => \&print_directorysrch,
  406:                     modify => \&modify_directorysrch,
  407:                   },
  408:         'contacts' =>
  409:                   { text => 'E-mail addresses and helpform',
  410:                     help => 'Domain_Configuration_Contact_Info',
  411:                     header => [{col1 => 'Default e-mail addresses',
  412:                                 col2 => 'Value',},
  413:                                {col1 => 'Recipient(s) for notifications',
  414:                                 col2 => 'Value',},
  415:                                {col1 => 'Nightly status check e-mail',
  416:                                 col2 => 'Settings',},
  417:                                {col1 => 'Ask helpdesk form settings',
  418:                                 col2 => 'Value',},],
  419:                     print => \&print_contacts,
  420:                     modify => \&modify_contacts,
  421:                   },
  422:         'usercreation' => 
  423:                   { text => 'User creation',
  424:                     help => 'Domain_Configuration_User_Creation',
  425:                     header => [{col1 => 'Format rule type',
  426:                                 col2 => 'Format rules in force'},
  427:                                {col1 => 'User account creation',
  428:                                 col2 => 'Usernames which may be created',},
  429:                                {col1 => 'Context',
  430:                                 col2 => 'Assignable authentication types'}],
  431:                     print => \&print_usercreation,
  432:                     modify => \&modify_usercreation,
  433:                   },
  434:         'selfcreation' => 
  435:                   { text => 'Users self-creating accounts',
  436:                     help => 'Domain_Configuration_Self_Creation', 
  437:                     header => [{col1 => 'Self-creation with institutional username',
  438:                                 col2 => 'Enabled?'},
  439:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  440:                                 col2 => 'Information user can enter'},
  441:                                {col1 => 'Self-creation with e-mail verification',
  442:                                 col2 => 'Settings'}],
  443:                     print => \&print_selfcreation,
  444:                     modify => \&modify_selfcreation,
  445:                   },
  446:         'usermodification' =>
  447:                   { text => 'User modification',
  448:                     help => 'Domain_Configuration_User_Modification',
  449:                     header => [{col1 => 'Target user has role',
  450:                                 col2 => 'User information updatable in author context'},
  451:                                {col1 => 'Target user has role',
  452:                                 col2 => 'User information updatable in course context'}],
  453:                     print => \&print_usermodification,
  454:                     modify => \&modify_usermodification,
  455:                   },
  456:         'scantron' =>
  457:                   { text => 'Bubblesheet format',
  458:                     help => 'Domain_Configuration_Scantron_Format',
  459:                     header => [ {col1 => 'Bubblesheet format file',
  460:                                  col2 => ''},
  461:                                 {col1 => 'Bubblesheet data upload formats',
  462:                                  col2 => 'Settings'}],
  463:                     print => \&print_scantron,
  464:                     modify => \&modify_scantron,
  465:                   },
  466:         'requestcourses' => 
  467:                  {text => 'Request creation of courses',
  468:                   help => 'Domain_Configuration_Request_Courses',
  469:                   header => [{col1 => 'User affiliation',
  470:                               col2 => 'Availability/Processing of requests',},
  471:                              {col1 => 'Setting',
  472:                               col2 => 'Value'},
  473:                              {col1 => 'Available textbooks',
  474:                               col2 => ''},
  475:                              {col1 => 'Available templates',
  476:                               col2 => ''},
  477:                              {col1 => 'Validation (not official courses)',
  478:                               col2 => 'Value'},],
  479:                   print => \&print_quotas,
  480:                   modify => \&modify_quotas,
  481:                  },
  482:         'requestauthor' =>
  483:                  {text => 'Request Authoring Space',
  484:                   help => 'Domain_Configuration_Request_Author',
  485:                   header => [{col1 => 'User affiliation',
  486:                               col2 => 'Availability/Processing of requests',},
  487:                              {col1 => 'Setting',
  488:                               col2 => 'Value'}],
  489:                   print => \&print_quotas,
  490:                   modify => \&modify_quotas,
  491:                  },
  492:         'coursecategories' =>
  493:                   { text => 'Cataloging of courses/communities',
  494:                     help => 'Domain_Configuration_Cataloging_Courses',
  495:                     header => [{col1 => 'Catalog type/availability',
  496:                                 col2 => '',},
  497:                                {col1 => 'Category settings for standard catalog',
  498:                                 col2 => '',},
  499:                                {col1 => 'Categories',
  500:                                 col2 => '',
  501:                                }],
  502:                     print => \&print_coursecategories,
  503:                     modify => \&modify_coursecategories,
  504:                   },
  505:         'serverstatuses' =>
  506:                  {text   => 'Access to server status pages',
  507:                   help   => 'Domain_Configuration_Server_Status',
  508:                   header => [{col1 => 'Status Page',
  509:                               col2 => 'Other named users',
  510:                               col3 => 'Specific IPs',
  511:                             }],
  512:                   print => \&print_serverstatuses,
  513:                   modify => \&modify_serverstatuses,
  514:                  },
  515:         'helpsettings' =>
  516:                  {text   => 'Support settings',
  517:                   help   => 'Domain_Configuration_Help_Settings',
  518:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  519:                               col2 => 'Value'},
  520:                              {col1 => 'Helpdesk Roles',
  521:                               col2 => 'Settings'},],
  522:                   print  => \&print_helpsettings,
  523:                   modify => \&modify_helpsettings,
  524:                  },
  525:         'coursedefaults' => 
  526:                  {text => 'Course/Community defaults',
  527:                   help => 'Domain_Configuration_Course_Defaults',
  528:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  529:                               col2 => 'Value',},
  530:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  531:                               col2 => 'Value',},],
  532:                   print => \&print_coursedefaults,
  533:                   modify => \&modify_coursedefaults,
  534:                  },
  535:         'selfenrollment' => 
  536:                  {text   => 'Self-enrollment in Course/Community',
  537:                   help   => 'Domain_Configuration_Selfenrollment',
  538:                   header => [{col1 => 'Configuration Rights',
  539:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  540:                              {col1 => 'Defaults',
  541:                               col2 => 'Value'},
  542:                              {col1 => 'Self-enrollment validation (optional)',
  543:                               col2 => 'Value'},],
  544:                   print => \&print_selfenrollment,
  545:                   modify => \&modify_selfenrollment,
  546:                  },
  547:         'privacy' => 
  548:                  {text   => 'Availability of User Information',
  549:                   help   => 'Domain_Configuration_User_Privacy',
  550:                   header => [{col1 => 'Role assigned in different domain',
  551:                               col2 => 'Approval options'},
  552:                              {col1 => 'Role assigned in different domain to user of type',
  553:                               col2 => 'User information available in that domain'},
  554:                              {col1 => "Role assigned in user's domain",
  555:                               col2 => 'Information viewable by privileged user'},
  556:                              {col1 => "Role assigned in user's domain",
  557:                               col2 => 'Information viewable by unprivileged user'}],
  558:                   print => \&print_privacy,
  559:                   modify => \&modify_privacy,
  560:                  },
  561:         'usersessions' =>
  562:                  {text  => 'User session hosting/offloading',
  563:                   help  => 'Domain_Configuration_User_Sessions',
  564:                   header => [{col1 => 'Domain server',
  565:                               col2 => 'Servers to offload sessions to when busy'},
  566:                              {col1 => 'Hosting of users from other domains',
  567:                               col2 => 'Rules'},
  568:                              {col1 => "Hosting domain's own users elsewhere",
  569:                               col2 => 'Rules'}],
  570:                   print => \&print_usersessions,
  571:                   modify => \&modify_usersessions,
  572:                  },
  573:         'loadbalancing' =>
  574:                  {text  => 'Dedicated Load Balancer(s)',
  575:                   help  => 'Domain_Configuration_Load_Balancing',
  576:                   header => [{col1 => 'Balancers',
  577:                               col2 => 'Default destinations',
  578:                               col3 => 'User affiliation',
  579:                               col4 => 'Overrides'},
  580:                             ],
  581:                   print => \&print_loadbalancing,
  582:                   modify => \&modify_loadbalancing,
  583:                  },
  584:         'ltitools' => 
  585:                  {text => 'External Tools (LTI)',
  586:                   help => 'Domain_Configuration_LTI_Tools',
  587:                   header => [{col1 => 'Setting',
  588:                               col2 => 'Value',}],
  589:                   print => \&print_ltitools,
  590:                   modify => \&modify_ltitools,
  591:                  },
  592:         'proctoring' =>
  593:                  {text => 'Remote Proctoring Integration',
  594:                   help => 'Domain_Configuration_Proctoring',
  595:                   header => [{col1 => 'Name',
  596:                               col2 => 'Configuration'}],
  597:                   print => \&print_proctoring,
  598:                   modify => \&modify_proctoring,
  599:                  },
  600:         'ssl' =>
  601:                  {text  => 'LON-CAPA Network (SSL)',
  602:                   help  => 'Domain_Configuration_Network_SSL',
  603:                   header => [{col1 => 'Server',
  604:                               col2 => 'Certificate Status'},
  605:                              {col1 => 'Connections to other servers',
  606:                               col2 => 'Rules'},
  607:                              {col1 => 'Connections from other servers',
  608:                               col2 => 'Rules'},
  609:                              {col1 => "Replicating domain's published content",
  610:                               col2 => 'Rules'}],
  611:                   print => \&print_ssl,
  612:                   modify => \&modify_ssl,
  613:                  },
  614:         'trust' =>
  615:                  {text   => 'Trust Settings',
  616:                   help   => 'Domain_Configuration_Trust',
  617:                   header => [{col1 => "Access to this domain's content by others",
  618:                               col2 => 'Rules'},
  619:                              {col1 => "Access to other domain's content by this domain",
  620:                               col2 => 'Rules'},
  621:                              {col1 => "Enrollment in this domain's courses by others",
  622:                               col2 => 'Rules',},
  623:                              {col1 => "Co-author roles in this domain for others",
  624:                               col2 => 'Rules',},
  625:                              {col1 => "Co-author roles for this domain's users elsewhere",
  626:                               col2 => 'Rules',},
  627:                              {col1 => "Domain roles in this domain assignable to others",
  628:                               col2 => 'Rules'},
  629:                              {col1 => "Course catalog for this domain displayed elsewhere",
  630:                               col2 => 'Rules'},
  631:                              {col1 => "Requests for creation of courses in this domain by others",
  632:                               col2 => 'Rules'},
  633:                              {col1 => "Users in other domains can send messages to this domain",
  634:                               col2 => 'Rules'},],
  635:                   print => \&print_trust,
  636:                   modify => \&modify_trust,
  637:                  },
  638:           'lti' =>
  639:                  {text => 'LTI Link Protection and LTI Consumers',
  640:                   help => 'Domain_Configuration_LTI_Provider',
  641:                   header => [{col1 => 'Encryption of shared secrets',
  642:                               col2 => 'Settings'},
  643:                              {col1 => 'Rules for shared secrets', 
  644:                               col2 => 'Settings'},
  645:                              {col1 => 'Link Protectors',
  646:                               col2 => 'Settings'},
  647:                              {col1 => 'Consumers',
  648:                               col2 => 'Settings'},],
  649:                   print => \&print_lti,
  650:                   modify => \&modify_lti,
  651:                  },
  652:            'ipaccess' =>
  653:                        {text => 'IP-based access control',
  654:                         help => 'Domain_Configuration_IP_Access',
  655:                         header => [{col1 => 'Setting',
  656:                                     col2 => 'Value'},],
  657:                         print  => \&print_ipaccess,
  658:                         modify => \&modify_ipaccess,
  659:                        },
  660:     );
  661:     if (keys(%servers) > 1) {
  662:         $prefs{'login'}  = { text   => 'Log-in page options',
  663:                              help   => 'Domain_Configuration_Login_Page',
  664:                             header => [{col1 => 'Log-in Service',
  665:                                         col2 => 'Server Setting',},
  666:                                        {col1 => 'Log-in Page Items',
  667:                                         col2 => 'Settings'},
  668:                                        {col1 => 'Log-in Help',
  669:                                         col2 => 'Value'},
  670:                                        {col1 => 'Custom HTML in document head',
  671:                                         col2 => 'Value'},
  672:                                        {col1 => 'SSO',
  673:                                         col2 => 'Dual login: SSO and non-SSO options'},
  674:                                       ],
  675:                             print => \&print_login,
  676:                             modify => \&modify_login,
  677:                            };
  678:     }
  679: 
  680:     my @roles = ('student','coordinator','author','admin');
  681:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  682:     &Apache::lonhtmlcommon::add_breadcrumb
  683:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  684:       text=>"Settings to display/modify"});
  685:     my $confname = $dom.'-domainconfig';
  686: 
  687:     if ($phase eq 'process') {
  688:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  689:                                                               \%prefs,\%domconfig,$confname,\@roles);
  690:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  691:             $r->rflush();
  692:             &devalidate_remote_domconfs($dom,$result);
  693:         }
  694:     } elsif ($phase eq 'display') {
  695:         my $js = &recaptcha_js().
  696:                  &toggle_display_js();
  697:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  698:             my ($othertitle,$usertypes,$types) =
  699:                 &Apache::loncommon::sorted_inst_types($dom);
  700:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  701:                                           $domconfig{'loadbalancing'}).
  702:                    &new_spares_js().
  703:                    &common_domprefs_js().
  704:                    &Apache::loncommon::javascript_array_indexof();
  705:         }
  706:         if (grep(/^requestcourses$/,@actions)) {
  707:             my $javascript_validations;
  708:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  709:             $js .= <<END;
  710: <script type="text/javascript">
  711: $javascript_validations
  712: </script>
  713: $coursebrowserjs
  714: END
  715:         } elsif (grep(/^ipaccess$/,@actions)) {
  716:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  717:         }
  718:         if (grep(/^selfcreation$/,@actions)) {
  719:             $js .= &selfcreate_javascript();
  720:         }
  721:         if (grep(/^contacts$/,@actions)) {
  722:             $js .= &contacts_javascript();
  723:         }
  724:         if (grep(/^scantron$/,@actions)) {
  725:             $js .= &scantron_javascript();
  726:         }
  727:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  728:     } else {
  729: # check if domconfig user exists for the domain.
  730:         my $servadm = $r->dir_config('lonAdmEMail');
  731:         my ($configuserok,$author_ok,$switchserver) =
  732:             &config_check($dom,$confname,$servadm);
  733:         unless ($configuserok eq 'ok') {
  734:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  735:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  736:                           $confname).
  737:                       '<br />'
  738:             );
  739:             if ($switchserver) {
  740:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  741:                           '<br />'.
  742:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  743:                           '<br />'.
  744:                           &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).
  745:                           '<br />'.
  746:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  747:                 );
  748:             } else {
  749:                 $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.').
  750:                           '<br />'.
  751:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  752:                 );
  753:             }
  754:             $r->print(&Apache::loncommon::end_page());
  755:             return OK;
  756:         }
  757:         if (keys(%domconfig) == 0) {
  758:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  759:             my @ids=&Apache::lonnet::current_machine_ids();
  760:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  761:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  762:                 my @loginimages = ('img','logo','domlogo','login');
  763:                 my $custom_img_count = 0;
  764:                 foreach my $img (@loginimages) {
  765:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  766:                         $custom_img_count ++;
  767:                     }
  768:                 }
  769:                 foreach my $role (@roles) {
  770:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  771:                         $custom_img_count ++;
  772:                     }
  773:                 }
  774:                 if ($custom_img_count > 0) {
  775:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  776:                     my $switch_server = &check_switchserver($dom,$confname);
  777:                     $r->print(
  778:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  779:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  780:     &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 />'.
  781:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  782:                     if ($switch_server) {
  783:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  784:                     }
  785:                     $r->print(&Apache::loncommon::end_page());
  786:                     return OK;
  787:                 }
  788:             }
  789:         }
  790:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  791:     }
  792:     return OK;
  793: }
  794: 
  795: sub process_changes {
  796:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  797:     my %domconfig;
  798:     if (ref($values) eq 'HASH') {
  799:         %domconfig = %{$values};
  800:     }
  801:     my $output;
  802:     if ($action eq 'login') {
  803:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  804:     } elsif ($action eq 'rolecolors') {
  805:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  806:                                      $lastactref,%domconfig);
  807:     } elsif ($action eq 'quotas') {
  808:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  809:     } elsif ($action eq 'autoenroll') {
  810:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  811:     } elsif ($action eq 'autoupdate') {
  812:         $output = &modify_autoupdate($dom,%domconfig);
  813:     } elsif ($action eq 'autocreate') {
  814:         $output = &modify_autocreate($dom,%domconfig);
  815:     } elsif ($action eq 'directorysrch') {
  816:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  817:     } elsif ($action eq 'usercreation') {
  818:         $output = &modify_usercreation($dom,%domconfig);
  819:     } elsif ($action eq 'selfcreation') {
  820:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  821:     } elsif ($action eq 'usermodification') {
  822:         $output = &modify_usermodification($dom,%domconfig);
  823:     } elsif ($action eq 'contacts') {
  824:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  825:     } elsif ($action eq 'defaults') {
  826:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  827:     } elsif ($action eq 'scantron') {
  828:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  829:     } elsif ($action eq 'coursecategories') {
  830:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  831:     } elsif ($action eq 'serverstatuses') {
  832:         $output = &modify_serverstatuses($dom,%domconfig);
  833:     } elsif ($action eq 'requestcourses') {
  834:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  835:     } elsif ($action eq 'requestauthor') {
  836:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  837:     } elsif ($action eq 'helpsettings') {
  838:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  839:     } elsif ($action eq 'coursedefaults') {
  840:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  841:     } elsif ($action eq 'selfenrollment') {
  842:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  843:     } elsif ($action eq 'usersessions') {
  844:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  845:     } elsif ($action eq 'loadbalancing') {
  846:         $output = &modify_loadbalancing($dom,%domconfig);
  847:     } elsif ($action eq 'ltitools') {
  848:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  849:     } elsif ($action eq 'proctoring') {
  850:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  851:     } elsif ($action eq 'ssl') {
  852:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  853:     } elsif ($action eq 'trust') {
  854:         $output = &modify_trust($dom,$lastactref,%domconfig);
  855:     } elsif ($action eq 'lti') {
  856:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  857:     } elsif ($action eq 'privacy') {
  858:         $output = &modify_privacy($dom,%domconfig);
  859:     } elsif ($action eq 'passwords') {
  860:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  861:     } elsif ($action eq 'wafproxy') {
  862:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  863:     } elsif ($action eq 'ipaccess') {
  864:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  865:     }
  866:     return $output;
  867: }
  868: 
  869: sub print_config_box {
  870:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  871:     my $rowtotal = 0;
  872:     my $output;
  873:     if ($action eq 'coursecategories') {
  874:         $output = &coursecategories_javascript($settings);
  875:     } elsif ($action eq 'defaults') {
  876:         $output = &defaults_javascript($settings); 
  877:     } elsif ($action eq 'passwords') {
  878:         $output = &passwords_javascript($action);
  879:     } elsif ($action eq 'helpsettings') {
  880:         my (%privs,%levelscurrent);
  881:         my %full=();
  882:         my %levels=(
  883:                      course => {},
  884:                      domain => {},
  885:                      system => {},
  886:                    );
  887:         my $context = 'domain';
  888:         my $crstype = 'Course';
  889:         my $formname = 'display';
  890:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  891:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  892:         $output =
  893:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  894:                                                       \@templateroles);
  895:     } elsif ($action eq 'ltitools') {
  896:         $output .= &ltitools_javascript($settings);
  897:     } elsif ($action eq 'lti') {
  898:         $output .= &passwords_javascript('secrets')."\n".
  899:                    &lti_javascript($dom,$settings);
  900:     } elsif ($action eq 'proctoring') {
  901:         $output .= &proctoring_javascript($settings);
  902:     } elsif ($action eq 'wafproxy') {
  903:         $output .= &wafproxy_javascript($dom);
  904:     } elsif ($action eq 'autoupdate') {
  905:         $output .= &autoupdate_javascript();
  906:     } elsif ($action eq 'autoenroll') {
  907:         $output .= &autoenroll_javascript();
  908:     } elsif ($action eq 'login') {
  909:         $output .= &saml_javascript();
  910:     } elsif ($action eq 'ipaccess') {
  911:         $output .= &ipaccess_javascript($settings);
  912:     }
  913:     $output .=
  914:          '<table class="LC_nested_outer">
  915:           <tr>
  916:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  917:            &mt($item->{text}).'&nbsp;'.
  918:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  919:           '</tr>';
  920:     $rowtotal ++;
  921:     my $numheaders = 1;
  922:     if (ref($item->{'header'}) eq 'ARRAY') {
  923:         $numheaders = scalar(@{$item->{'header'}});
  924:     }
  925:     if ($numheaders > 1) {
  926:         my $colspan = '';
  927:         my $rightcolspan = '';
  928:         my $leftnobr = '';
  929:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  930:             ($action eq 'directorysrch') ||
  931:             (($action eq 'login') && ($numheaders < 5))) {
  932:             $colspan = ' colspan="2"';
  933:         }
  934:         if ($action eq 'usersessions') {
  935:             $rightcolspan = ' colspan="3"'; 
  936:         }
  937:         if ($action eq 'passwords') {
  938:             $leftnobr = ' LC_nobreak';
  939:         }
  940:         $output .= '
  941:           <tr>
  942:            <td>
  943:             <table class="LC_nested">
  944:              <tr class="LC_info_row">
  945:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  946:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  947:              </tr>';
  948:         $rowtotal ++;
  949:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  950:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  951:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  952:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  953:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') || ($action eq 'lti')) {
  954:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  955:         } elsif ($action eq 'passwords') {
  956:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  957:         } elsif ($action eq 'coursecategories') {
  958:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  959:         } elsif ($action eq 'scantron') {
  960:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  961:         } elsif ($action eq 'login') {
  962:             if ($numheaders == 5) {
  963:                 $colspan = ' colspan="2"';
  964:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  965:             } else {
  966:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  967:             }
  968:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  969:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  970:         } elsif ($action eq 'rolecolors') {
  971:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  972:         }
  973:         $output .= '
  974:            </table>
  975:           </td>
  976:          </tr>
  977:          <tr>
  978:            <td>
  979:             <table class="LC_nested">
  980:              <tr class="LC_info_row">
  981:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  982:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  983:              </tr>';
  984:             $rowtotal ++;
  985:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  986:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  987:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  988:             ($action eq 'trust') || ($action eq 'contacts') || ($action eq 'defaults') ||
  989:             ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti')) {
  990:             if ($action eq 'coursecategories') {
  991:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  992:                 $colspan = ' colspan="2"';
  993:             } elsif ($action eq 'trust') {
  994:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  995:             } elsif ($action eq 'passwords') {
  996:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  997:             } else {
  998:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  999:             }
 1000:             if ($action eq 'trust') {
 1001:                 $output .= '
 1002:             </table>
 1003:           </td>
 1004:          </tr>';
 1005:                 my @trusthdrs = qw(2 3 4 5 6 7);
 1006:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
 1007:                 for (my $i=0; $i<@trusthdrs; $i++) {
 1008:                     $output .= '
 1009:          <tr>
 1010:            <td>
 1011:             <table class="LC_nested">
 1012:              <tr class="LC_info_row">
 1013:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
 1014:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
 1015:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
 1016:             </table>
 1017:           </td>
 1018:          </tr>';
 1019:                 }
 1020:                 $output .= '
 1021:          <tr>
 1022:            <td>
 1023:             <table class="LC_nested">
 1024:              <tr class="LC_info_row">
 1025:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
 1026:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
 1027:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1028:             } else {
 1029:                 $output .= '
 1030:            </table>
 1031:           </td>
 1032:          </tr>
 1033:          <tr>
 1034:            <td>
 1035:             <table class="LC_nested">
 1036:              <tr class="LC_info_row">
 1037:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1038:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1039:              </tr>'."\n";
 1040:                 if ($action eq 'coursecategories') {
 1041:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
 1042:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || 
 1043:                          ($action eq 'passwords') || ($action eq 'lti')) {
 1044:                     if ($action eq 'passwords') {
 1045:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
 1046:                     } else {
 1047:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
 1048:                     }
 1049:                     $output .= '
 1050:              </tr>
 1051:             </table>
 1052:            </td>
 1053:           </tr>
 1054:           <tr>
 1055:            <td>
 1056:             <table class="LC_nested">
 1057:              <tr class="LC_info_row">
 1058:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1059:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1060:                     if ($action eq 'passwords') {
 1061:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1062:                     } else {
 1063:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1064:                     }
 1065:                     $output .= '
 1066:             </table>
 1067:           </td>
 1068:          </tr>
 1069:          <tr>';
 1070:                 } else {
 1071:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1072:                 }
 1073:             }
 1074:             $rowtotal ++;
 1075:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1076:                  ($action eq 'directorysrch') || ($action eq 'helpsettings') ||
 1077:                  ($action eq 'wafproxy')) {
 1078:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1079:         } elsif ($action eq 'scantron') {
 1080:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1081:         } elsif ($action eq 'ssl') {
 1082:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1083:             </table>
 1084:           </td>
 1085:          </tr>
 1086:          <tr>
 1087:            <td>
 1088:             <table class="LC_nested">
 1089:              <tr class="LC_info_row">
 1090:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1091:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1092:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
 1093:             </table>
 1094:           </td>
 1095:          </tr>
 1096:          <tr>
 1097:            <td>
 1098:             <table class="LC_nested">
 1099:              <tr class="LC_info_row">
 1100:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1101:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1102:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1103:         } elsif ($action eq 'login') {
 1104:             if ($numheaders == 5) {
 1105:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1106:            </table>
 1107:           </td>
 1108:          </tr>
 1109:          <tr>
 1110:            <td>
 1111:             <table class="LC_nested">
 1112:              <tr class="LC_info_row">
 1113:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1114:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1115:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1116:                 $rowtotal ++;
 1117:             } else {
 1118:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1119:             }
 1120:             $output .= '
 1121:            </table>
 1122:           </td>
 1123:          </tr>
 1124:          <tr>
 1125:            <td>
 1126:             <table class="LC_nested">
 1127:              <tr class="LC_info_row">';
 1128:             if ($numheaders == 5) {
 1129:                 $output .= '
 1130:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1131:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1132:              </tr>';
 1133:             } else {
 1134:                 $output .= '
 1135:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1136:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1137:              </tr>';
 1138:             }
 1139:             $rowtotal ++;
 1140:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1141:            </table>
 1142:           </td>
 1143:          </tr>
 1144:          <tr>
 1145:            <td>
 1146:             <table class="LC_nested">
 1147:              <tr class="LC_info_row">';
 1148:             if ($numheaders == 5) {
 1149:                 $output .= '
 1150:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1151:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1152:              </tr>';
 1153:             } else {
 1154:                 $output .= '
 1155:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1156:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1157:              </tr>';
 1158:             }
 1159:             $rowtotal ++;
 1160:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1161:         } elsif ($action eq 'requestcourses') {
 1162:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1163:             $rowtotal ++;
 1164:             $output .= &print_studentcode($settings,\$rowtotal).'
 1165:            </table>
 1166:           </td>
 1167:          </tr>
 1168:          <tr>
 1169:            <td>
 1170:             <table class="LC_nested">
 1171:              <tr class="LC_info_row">
 1172:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1173:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1174:                        &textbookcourses_javascript($settings).
 1175:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1176:             </table>
 1177:            </td>
 1178:           </tr>
 1179:          <tr>
 1180:            <td>
 1181:             <table class="LC_nested">
 1182:              <tr class="LC_info_row">
 1183:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1184:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1185:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1186:             </table>
 1187:            </td>
 1188:           </tr>
 1189:           <tr>
 1190:            <td>
 1191:             <table class="LC_nested">
 1192:              <tr class="LC_info_row">
 1193:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1194:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1195:              </tr>'.
 1196:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1197:         } elsif ($action eq 'requestauthor') {
 1198:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1199:             $rowtotal ++;
 1200:         } elsif ($action eq 'rolecolors') {
 1201:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1202:            </table>
 1203:           </td>
 1204:          </tr>
 1205:          <tr>
 1206:            <td>
 1207:             <table class="LC_nested">
 1208:              <tr class="LC_info_row">
 1209:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1210:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1211:               <td class="LC_right_item" style="vertical-align: top">'.
 1212:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1213:              </tr>'.
 1214:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1215:            </table>
 1216:           </td>
 1217:          </tr>
 1218:          <tr>
 1219:            <td>
 1220:             <table class="LC_nested">
 1221:              <tr class="LC_info_row">
 1222:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1223:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1224:              </tr>'.
 1225:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1226:             $rowtotal += 2;
 1227:         }
 1228:     } else {
 1229:         $output .= '
 1230:           <tr>
 1231:            <td>
 1232:             <table class="LC_nested">
 1233:              <tr class="LC_info_row">';
 1234:         if ($action eq 'login') {
 1235:             $output .= '  
 1236:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1237:         } elsif ($action eq 'serverstatuses') {
 1238:             $output .= '
 1239:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1240:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1241: 
 1242:         } else {
 1243:             $output .= '
 1244:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1245:         }
 1246:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1247:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1248:                        &mt($item->{'header'}->[0]->{'col2'});
 1249:             if ($action eq 'serverstatuses') {
 1250:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1251:             } 
 1252:         } else {
 1253:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1254:                        &mt($item->{'header'}->[0]->{'col2'});
 1255:         }
 1256:         $output .= '</td>';
 1257:         if ($item->{'header'}->[0]->{'col3'}) {
 1258:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1259:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1260:                             &mt($item->{'header'}->[0]->{'col3'});
 1261:             } else {
 1262:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1263:                            &mt($item->{'header'}->[0]->{'col3'});
 1264:             }
 1265:             if ($action eq 'serverstatuses') {
 1266:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1267:             }
 1268:             $output .= '</td>';
 1269:         }
 1270:         if ($item->{'header'}->[0]->{'col4'}) {
 1271:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1272:                        &mt($item->{'header'}->[0]->{'col4'});
 1273:         }
 1274:         $output .= '</tr>';
 1275:         $rowtotal ++;
 1276:         if ($action eq 'quotas') {
 1277:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1278:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1279:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1280:                  ($action eq 'ltitools') || ($action eq 'proctoring') ||
 1281:                  ($action eq 'ipaccess')) {
 1282:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1283:         }
 1284:     }
 1285:     $output .= '
 1286:    </table>
 1287:   </td>
 1288:  </tr>
 1289: </table><br />';
 1290:     return ($output,$rowtotal);
 1291: }
 1292: 
 1293: sub print_login {
 1294:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1295:     my ($css_class,$datatable,$switchserver,%lt);
 1296:     my %choices = &login_choices();
 1297:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1298:         %lt = &login_file_options();
 1299:         $switchserver = &check_switchserver($dom,$confname);
 1300:     }
 1301:     if ($caller eq 'service') {
 1302:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1303:         my $choice = $choices{'disallowlogin'};
 1304:         $css_class = ' class="LC_odd_row"';
 1305:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1306:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1307:                       '<th>'.$choices{'server'}.'</th>'.
 1308:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1309:                       '<th>'.$choices{'custompath'}.'</th>'.
 1310:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1311:         my %disallowed;
 1312:         if (ref($settings) eq 'HASH') {
 1313:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1314:                %disallowed = %{$settings->{'loginvia'}};
 1315:             }
 1316:         }
 1317:         foreach my $lonhost (sort(keys(%servers))) {
 1318:             my $direct = 'selected="selected"';
 1319:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1320:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1321:                     $direct = '';
 1322:                 }
 1323:             }
 1324:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1325:                           '<td><select name="'.$lonhost.'_server">'.
 1326:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1327:                           '</option>';
 1328:             foreach my $hostid (sort(keys(%servers))) {
 1329:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1330:                 my $selected = '';
 1331:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1332:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1333:                         $selected = 'selected="selected"';
 1334:                     }
 1335:                 }
 1336:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1337:                               $servers{$hostid}.'</option>';
 1338:             }
 1339:             $datatable .= '</select></td>'.
 1340:                           '<td><select name="'.$lonhost.'_serverpath">';
 1341:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1342:                 my $pathname = $path;
 1343:                 if ($path eq 'custom') {
 1344:                     $pathname = &mt('Custom Path').' ->';
 1345:                 }
 1346:                 my $selected = '';
 1347:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1348:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1349:                         $selected = 'selected="selected"';
 1350:                     }
 1351:                 } elsif ($path eq '') {
 1352:                     $selected = 'selected="selected"';
 1353:                 }
 1354:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1355:             }
 1356:             $datatable .= '</select></td>';
 1357:             my ($custom,$exempt);
 1358:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1359:                 $custom = $disallowed{$lonhost}{'custompath'};
 1360:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1361:             }
 1362:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1363:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1364:                           '</tr>';
 1365:         }
 1366:         $datatable .= '</table></td></tr>';
 1367:         return $datatable;
 1368:     } elsif ($caller eq 'page') {
 1369:         my %defaultchecked = ( 
 1370:                                'coursecatalog' => 'on',
 1371:                                'helpdesk'      => 'on',
 1372:                                'adminmail'     => 'off',
 1373:                                'newuser'       => 'off',
 1374:                              );
 1375:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1376:         my (%checkedon,%checkedoff);
 1377:         foreach my $item (@toggles) {
 1378:             if ($defaultchecked{$item} eq 'on') { 
 1379:                 $checkedon{$item} = ' checked="checked" ';
 1380:                 $checkedoff{$item} = ' ';
 1381:             } elsif ($defaultchecked{$item} eq 'off') {
 1382:                 $checkedoff{$item} = ' checked="checked" ';
 1383:                 $checkedon{$item} = ' ';
 1384:             }
 1385:         }
 1386:         my @images = ('img','logo','domlogo','login');
 1387:         my @alttext = ('img','logo','domlogo');
 1388:         my @logintext = ('textcol','bgcol');
 1389:         my @bgs = ('pgbg','mainbg','sidebg');
 1390:         my @links = ('link','alink','vlink');
 1391:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1392:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1393:         my (%is_custom,%designs);
 1394:         my %defaults = (
 1395:                        font => $defaultdesign{'login.font'},
 1396:                        );
 1397:         foreach my $item (@images) {
 1398:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1399:             $defaults{'showlogo'}{$item} = 1;
 1400:         }
 1401:         foreach my $item (@bgs) {
 1402:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1403:         }
 1404:         foreach my $item (@logintext) {
 1405:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1406:         }
 1407:         foreach my $item (@links) {
 1408:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1409:         }
 1410:         if (ref($settings) eq 'HASH') {
 1411:             foreach my $item (@toggles) {
 1412:                 if ($settings->{$item} eq '1') {
 1413:                     $checkedon{$item} =  ' checked="checked" ';
 1414:                     $checkedoff{$item} = ' ';
 1415:                 } elsif ($settings->{$item} eq '0') {
 1416:                     $checkedoff{$item} =  ' checked="checked" ';
 1417:                     $checkedon{$item} = ' ';
 1418:                 }
 1419:             }
 1420:             foreach my $item (@images) {
 1421:                 if (defined($settings->{$item})) {
 1422:                     $designs{$item} = $settings->{$item};
 1423:                     $is_custom{$item} = 1;
 1424:                 }
 1425:                 if (defined($settings->{'showlogo'}{$item})) {
 1426:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1427:                 }
 1428:             }
 1429:             foreach my $item (@alttext) {
 1430:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1431:                     if ($settings->{'alttext'}->{$item} ne '') {
 1432:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1433:                     }
 1434:                 }
 1435:             }
 1436:             foreach my $item (@logintext) {
 1437:                 if ($settings->{$item} ne '') {
 1438:                     $designs{'logintext'}{$item} = $settings->{$item};
 1439:                     $is_custom{$item} = 1;
 1440:                 }
 1441:             }
 1442:             if ($settings->{'font'} ne '') {
 1443:                 $designs{'font'} = $settings->{'font'};
 1444:                 $is_custom{'font'} = 1;
 1445:             }
 1446:             foreach my $item (@bgs) {
 1447:                 if ($settings->{$item} ne '') {
 1448:                     $designs{'bgs'}{$item} = $settings->{$item};
 1449:                     $is_custom{$item} = 1;
 1450:                 }
 1451:             }
 1452:             foreach my $item (@links) {
 1453:                 if ($settings->{$item} ne '') {
 1454:                     $designs{'links'}{$item} = $settings->{$item};
 1455:                     $is_custom{$item} = 1;
 1456:                 }
 1457:             }
 1458:         } else {
 1459:             if ($designhash{$dom.'.login.font'} ne '') {
 1460:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1461:                 $is_custom{'font'} = 1;
 1462:             }
 1463:             foreach my $item (@images) {
 1464:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1465:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1466:                     $is_custom{$item} = 1;
 1467:                 }
 1468:             }
 1469:             foreach my $item (@bgs) {
 1470:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1471:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1472:                     $is_custom{$item} = 1;
 1473:                 }
 1474:             }
 1475:             foreach my $item (@links) {
 1476:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1477:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1478:                     $is_custom{$item} = 1;
 1479:                 }
 1480:             }
 1481:         }
 1482:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1483:                                                       logo => 'Institution Logo',
 1484:                                                       domlogo => 'Domain Logo',
 1485:                                                       login => 'Login box');
 1486:         my $itemcount = 1;
 1487:         foreach my $item (@toggles) {
 1488:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1489:             $datatable .=  
 1490:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1491:                 '</td><td>'.
 1492:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1493:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1494:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1495:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1496:                 '</tr>';
 1497:             $itemcount ++;
 1498:         }
 1499:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1500:         $datatable .= '</tr></table></td></tr>';
 1501:     } elsif ($caller eq 'help') {
 1502:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1503:         my $itemcount = 1;
 1504:         $defaulturl = '/adm/loginproblems.html';
 1505:         $defaulttype = 'default';
 1506:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1507:         my @currlangs;
 1508:         if (ref($settings) eq 'HASH') {
 1509:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1510:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1511:                     next if ($settings->{'helpurl'}{$key} eq '');
 1512:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1513:                     $type{$key} = 'custom';
 1514:                     unless ($key eq 'nolang') {
 1515:                         push(@currlangs,$key);
 1516:                     }
 1517:                 }
 1518:             } elsif ($settings->{'helpurl'} ne '') {
 1519:                 $type{'nolang'} = 'custom';
 1520:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1521:             }
 1522:         }
 1523:         foreach my $lang ('nolang',sort(@currlangs)) {
 1524:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1525:             $datatable .= '<tr'.$css_class.'>';
 1526:             if ($url{$lang} eq '') {
 1527:                 $url{$lang} = $defaulturl;
 1528:             }
 1529:             if ($type{$lang} eq '') {
 1530:                 $type{$lang} = $defaulttype;
 1531:             }
 1532:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1533:             if ($lang eq 'nolang') {
 1534:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1535:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1536:             } else {
 1537:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1538:                                   $langchoices{$lang},
 1539:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1540:             }
 1541:             $datatable .= '</span></td>'."\n".
 1542:                           '<td class="LC_left_item">';
 1543:             if ($type{$lang} eq 'custom') {
 1544:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1545:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1546:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1547:             } else {
 1548:                 $datatable .= $lt{'upl'};
 1549:             }
 1550:             $datatable .='<br />';
 1551:             if ($switchserver) {
 1552:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1553:             } else {
 1554:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1555:             }
 1556:             $datatable .= '</td></tr>';
 1557:             $itemcount ++;
 1558:         }
 1559:         my @addlangs;
 1560:         foreach my $lang (sort(keys(%langchoices))) {
 1561:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1562:             push(@addlangs,$lang);
 1563:         }
 1564:         if (@addlangs > 0) {
 1565:             my %toadd;
 1566:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1567:             $toadd{''} = &mt('Select');
 1568:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1569:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1570:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1571:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1572:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1573:             if ($switchserver) {
 1574:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1575:             } else {
 1576:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1577:             }
 1578:             $datatable .= '</td></tr>';
 1579:             $itemcount ++;
 1580:         }
 1581:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1582:     } elsif ($caller eq 'headtag') {
 1583:         my %domservers = &Apache::lonnet::get_servers($dom);
 1584:         my $choice = $choices{'headtag'};
 1585:         $css_class = ' class="LC_odd_row"';
 1586:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1587:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1588:                       '<th>'.$choices{'current'}.'</th>'.
 1589:                       '<th>'.$choices{'action'}.'</th>'.
 1590:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1591:         my (%currurls,%currexempt);
 1592:         if (ref($settings) eq 'HASH') {
 1593:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1594:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1595:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1596:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1597:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1598:                     }
 1599:                 }
 1600:             }
 1601:         }
 1602:         foreach my $lonhost (sort(keys(%domservers))) {
 1603:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1604:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1605:             if ($currurls{$lonhost}) {
 1606:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1607:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1608:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1609:                               '">'.$lt{'curr'}.'</a></td>'.
 1610:                               '<td><span class="LC_nobreak"><label>'.
 1611:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1612:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1613:             } else {
 1614:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1615:             }
 1616:             $datatable .='<br />';
 1617:             if ($switchserver) {
 1618:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1619:             } else {
 1620:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1621:             }
 1622:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1623:         }
 1624:         $datatable .= '</table></td></tr>';
 1625:     } elsif ($caller eq 'saml') {
 1626:         my %domservers = &Apache::lonnet::get_servers($dom);
 1627:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1628:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1629:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1630:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1631:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1632:         foreach my $lonhost (keys(%domservers)) {
 1633:             $samlurl{$lonhost} = '/adm/sso';
 1634:             $styleon{$lonhost} = 'display:none';
 1635:             $styleoff{$lonhost} = '';
 1636:         }
 1637:         if ((ref($settings) eq 'HASH') && (ref($settings->{'saml'}) eq 'HASH')) {
 1638:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1639:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1640:                     $saml{$lonhost} = 1;
 1641:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1642:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1643:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1644:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1645:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1646:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1647:                     $styleon{$lonhost} = '';
 1648:                     $styleoff{$lonhost} = 'display:none';
 1649:                 } else {
 1650:                     $styleon{$lonhost} = 'display:none';
 1651:                     $styleoff{$lonhost} = '';
 1652:                 }
 1653:             }
 1654:         }
 1655:         my $itemcount = 1;
 1656:         foreach my $lonhost (sort(keys(%domservers))) {
 1657:             my $samlon = ' ';
 1658:             my $samloff = ' checked="checked" ';
 1659:             if ($saml{$lonhost}) {
 1660:                 $samlon = $samloff;
 1661:                 $samloff = ' ';
 1662:             }
 1663:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1664:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1665:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1666:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1667:                           &mt('No').'</label>'.('&nbsp;'x2).
 1668:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1669:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1670:                           &mt('Yes').'</label></span></td>'.
 1671:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1672:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1673:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1674:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1675:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1676:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1677:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1678:                           $samltext{$lonhost}.'" /></td><td>';
 1679:             if ($samlimg{$lonhost}) {
 1680:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1681:                               '<span class="LC_nobreak"><label>'.
 1682:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1683:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1684:             } else {
 1685:                 $datatable .= $lt{'upl'};
 1686:             }
 1687:             $datatable .='<br />';
 1688:             if ($switchserver) {
 1689:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1690:             } else {
 1691:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1692:             }
 1693:             $datatable .= '</td>'.
 1694:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1695:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1696:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1697:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1698:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1699:                           $samltitle{$lonhost}.'</textarea></td>'.
 1700:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1701:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1702:                           '</table></td>'.
 1703:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1704:            $itemcount ++;
 1705:         }
 1706:         $datatable .= '</table></td></tr>';
 1707:     }
 1708:     return $datatable;
 1709: }
 1710: 
 1711: sub login_choices {
 1712:     my %choices =
 1713:         &Apache::lonlocal::texthash (
 1714:             coursecatalog => 'Display Course/Community Catalog link?',
 1715:             adminmail     => "Display Administrator's E-mail Address?",
 1716:             helpdesk      => 'Display "Contact Helpdesk" link',
 1717:             disallowlogin => "Login page requests redirected",
 1718:             hostid        => "Server",
 1719:             server        => "Redirect to:",
 1720:             serverpath    => "Path",
 1721:             custompath    => "Custom", 
 1722:             exempt        => "Exempt IP(s)",
 1723:             directlogin   => "No redirect",
 1724:             newuser       => "Link to create a user account",
 1725:             img           => "Header",
 1726:             logo          => "Main Logo",
 1727:             domlogo       => "Domain Logo",
 1728:             login         => "Log-in Header", 
 1729:             textcol       => "Text color",
 1730:             bgcol         => "Box color",
 1731:             bgs           => "Background colors",
 1732:             links         => "Link colors",
 1733:             font          => "Font color",
 1734:             pgbg          => "Header",
 1735:             mainbg        => "Page",
 1736:             sidebg        => "Login box",
 1737:             link          => "Link",
 1738:             alink         => "Active link",
 1739:             vlink         => "Visited link",
 1740:             headtag       => "Custom markup",
 1741:             action        => "Action",
 1742:             current       => "Current",
 1743:             samllanding   => "Dual login?",
 1744:             samloptions   => "Options",
 1745:             alttext       => "Alt text",
 1746:         );
 1747:     return %choices;
 1748: }
 1749: 
 1750: sub login_file_options {
 1751:       return &Apache::lonlocal::texthash(
 1752:                                            del     => 'Delete?',
 1753:                                            rep     => 'Replace:',
 1754:                                            upl     => 'Upload:',
 1755:                                            curr    => 'View contents',
 1756:                                            default => 'Default',
 1757:                                            custom  => 'Custom',
 1758:                                            none    => 'None',
 1759:       );
 1760: }
 1761: 
 1762: sub print_ipaccess {
 1763:     my ($dom,$settings,$rowtotal) = @_;
 1764:     my $css_class;
 1765:     my $itemcount = 0;
 1766:     my $datatable;
 1767:     my %ordered;
 1768:     if (ref($settings) eq 'HASH') {
 1769:         foreach my $item (keys(%{$settings})) {
 1770:             if (ref($settings->{$item}) eq 'HASH') {
 1771:                 my $num = $settings->{$item}{'order'};
 1772:                 if ($num eq '') {
 1773:                     $num = scalar(keys(%{$settings}));
 1774:                 }
 1775:                 $ordered{$num} = $item;
 1776:             }
 1777:         }
 1778:     }
 1779:     my $maxnum = scalar(keys(%ordered));
 1780:     if (keys(%ordered)) {
 1781:         my @items = sort { $a <=> $b } keys(%ordered);
 1782:         for (my $i=0; $i<@items; $i++) {
 1783:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1784:             my $item = $ordered{$items[$i]};
 1785:             my ($name,$ipranges,%commblocks,%courses);
 1786:             if (ref($settings->{$item}) eq 'HASH') {
 1787:                 $name = $settings->{$item}->{'name'};
 1788:                 $ipranges = $settings->{$item}->{'ip'};
 1789:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1790:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1791:                 }
 1792:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1793:                     %courses = %{$settings->{$item}->{'courses'}};
 1794:                 }
 1795:             }
 1796:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1797:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1798:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1799:             for (my $k=0; $k<=$maxnum; $k++) {
 1800:                 my $vpos = $k+1;
 1801:                 my $selstr;
 1802:                 if ($k == $i) {
 1803:                     $selstr = ' selected="selected" ';
 1804:                 }
 1805:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1806:             }
 1807:             $datatable .= '</select>'.('&nbsp;'x2).
 1808:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1809:                 &mt('Delete?').'</label></span></td>'.
 1810:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1811:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1812:                 '</td></tr>';
 1813:             $itemcount ++;
 1814:         }
 1815:     }
 1816:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1817:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1818:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1819:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1820:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1821:     for (my $k=0; $k<$maxnum+1; $k++) {
 1822:         my $vpos = $k+1;
 1823:         my $selstr;
 1824:         if ($k == $maxnum) {
 1825:             $selstr = ' selected="selected" ';
 1826:         }
 1827:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1828:     }
 1829:     $datatable .= '</select>&nbsp;'."\n".
 1830:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1831:                   '<td colspan="2">'.
 1832:                   &ipaccess_options('add',$itemcount,$dom).
 1833:                   '</td>'."\n".
 1834:                   '</tr>'."\n";
 1835:     $$rowtotal ++;
 1836:     return $datatable;
 1837: }
 1838: 
 1839: sub ipaccess_options {
 1840:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1841:     my (%currblocks,%currcourses,$output);
 1842:     if (ref($blocksref) eq 'HASH') {
 1843:         %currblocks = %{$blocksref};
 1844:     }
 1845:     if (ref($coursesref) eq 'HASH') {
 1846:         %currcourses = %{$coursesref};
 1847:     }
 1848:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1849:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1850:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1851:               '</span></fieldset>'.
 1852:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1853:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1854:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1855:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1856:               $ipranges.'</textarea></fieldset>'.
 1857:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1858:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1859:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1860:               '<table>';
 1861:     foreach my $cid (sort(keys(%currcourses))) {
 1862:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1863:         $output .= '<tr><td><span class="LC_nobreak">'.
 1864:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1865:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1866:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1867:     }
 1868:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1869:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1870:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1871:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1872:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1873:                '</span></td></tr></table>'."\n".
 1874:                '</fieldset>';
 1875:     return $output;
 1876: }
 1877: 
 1878: sub blocker_checkboxes {
 1879:     my ($num,$blocks) = @_;
 1880:     my ($typeorder,$types) = &commblocktype_text();
 1881:     my $numinrow = 6;
 1882:     my $output = '<table>';
 1883:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1884:         my $block = $typeorder->[$i];
 1885:         my $blockstatus;
 1886:         if (ref($blocks) eq 'HASH') {
 1887:             if ($blocks->{$block} eq 'on') {
 1888:                 $blockstatus = 'checked="checked"';
 1889:             }
 1890:         }
 1891:         my $rem = $i%($numinrow);
 1892:         if ($rem == 0) {
 1893:             if ($i > 0) {
 1894:                 $output .= '</tr>';
 1895:             }
 1896:             $output .= '<tr>';
 1897:         }
 1898:         if ($i == scalar(@{$typeorder})-1) {
 1899:             my $colsleft = $numinrow-$rem;
 1900:             if ($colsleft > 1) {
 1901:                 $output .= '<td colspan="'.$colsleft.'">';
 1902:             } else {
 1903:                 $output .= '<td>';
 1904:             }
 1905:         } else {
 1906:             $output .= '<td>';
 1907:         }
 1908:         my $item = 'ipaccess_block_'.$num;
 1909:         if ($blockstatus) {
 1910:             $blockstatus = ' '.$blockstatus;
 1911:         }
 1912:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1913:                    '<input type="checkbox" name="'.$item.'"'.
 1914:                    $blockstatus.' value="'.$block.'"'.' />'.
 1915:                    $types->{$block}.'</label></span>'."\n".
 1916:                    '<br /></td>';
 1917:     }
 1918:     $output .= '</tr></table>';
 1919:     return $output;
 1920: }
 1921: 
 1922: sub commblocktype_text {
 1923:     my %types = &Apache::lonlocal::texthash(
 1924:         'com' => 'Messaging',
 1925:         'chat' => 'Chat Room',
 1926:         'boards' => 'Discussion',
 1927:         'port' => 'Portfolio',
 1928:         'groups' => 'Groups',
 1929:         'blogs' => 'Blogs',
 1930:         'about' => 'User Information',
 1931:         'printout' => 'Printouts',
 1932:         'passwd' => 'Change Password',
 1933:         'grades' => 'Gradebook',
 1934:         'search' => 'Course search',
 1935:         'wishlist' => 'Stored links',
 1936:         'annotate' => 'Annotations',
 1937:     );
 1938:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1939:     return ($typeorder,\%types);
 1940: }
 1941: 
 1942: sub print_rolecolors {
 1943:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1944:     my %choices = &color_font_choices();
 1945:     my @bgs = ('pgbg','tabbg','sidebg');
 1946:     my @links = ('link','alink','vlink');
 1947:     my @images = ('img');
 1948:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1949:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1950:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1951:     my (%is_custom,%designs);
 1952:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1953:     if (ref($settings) eq 'HASH') {
 1954:         if (ref($settings->{$role}) eq 'HASH') {
 1955:             if ($settings->{$role}->{'img'} ne '') {
 1956:                 $designs{'img'} = $settings->{$role}->{'img'};
 1957:                 $is_custom{'img'} = 1;
 1958:             }
 1959:             if ($settings->{$role}->{'font'} ne '') {
 1960:                 $designs{'font'} = $settings->{$role}->{'font'};
 1961:                 $is_custom{'font'} = 1;
 1962:             }
 1963:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1964:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1965:                 $is_custom{'fontmenu'} = 1;
 1966:             }
 1967:             foreach my $item (@bgs) {
 1968:                 if ($settings->{$role}->{$item} ne '') {
 1969:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1970:                     $is_custom{$item} = 1;
 1971:                 }
 1972:             }
 1973:             foreach my $item (@links) {
 1974:                 if ($settings->{$role}->{$item} ne '') {
 1975:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1976:                     $is_custom{$item} = 1;
 1977:                 }
 1978:             }
 1979:         }
 1980:     } else {
 1981:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1982:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1983:             $is_custom{'img'} = 1;
 1984:         }
 1985:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1986:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1987:             $is_custom{'fontmenu'} = 1; 
 1988:         }
 1989:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1990:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1991:             $is_custom{'font'} = 1;
 1992:         }
 1993:         foreach my $item (@bgs) {
 1994:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1995:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1996:                 $is_custom{$item} = 1;
 1997:             
 1998:             }
 1999:         }
 2000:         foreach my $item (@links) {
 2001:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 2002:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 2003:                 $is_custom{$item} = 1;
 2004:             }
 2005:         }
 2006:     }
 2007:     my $itemcount = 1;
 2008:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 2009:     $datatable .= '</tr></table></td></tr>';
 2010:     return $datatable;
 2011: }
 2012: 
 2013: sub role_defaults {
 2014:     my ($role,$bgs,$links,$images,$logintext) = @_;
 2015:     my %defaults;
 2016:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 2017:         return %defaults;
 2018:     }
 2019:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 2020:     if ($role eq 'login') {
 2021:         %defaults = (
 2022:                        font => $defaultdesign{$role.'.font'},
 2023:                     );
 2024:         if (ref($logintext) eq 'ARRAY') {
 2025:             foreach my $item (@{$logintext}) {
 2026:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 2027:             }
 2028:         }
 2029:         foreach my $item (@{$images}) {
 2030:             $defaults{'showlogo'}{$item} = 1;
 2031:         }
 2032:     } else {
 2033:         %defaults = (
 2034:                        img => $defaultdesign{$role.'.img'},
 2035:                        font => $defaultdesign{$role.'.font'},
 2036:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 2037:                     );
 2038:     }
 2039:     foreach my $item (@{$bgs}) {
 2040:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 2041:     }
 2042:     foreach my $item (@{$links}) {
 2043:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 2044:     }
 2045:     foreach my $item (@{$images}) {
 2046:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 2047:     }
 2048:     return %defaults;
 2049: }
 2050: 
 2051: sub display_color_options {
 2052:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 2053:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 2054:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2055:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2056:     my $datatable = '<tr'.$css_class.'>'.
 2057:         '<td>'.$choices->{'font'}.'</td>';
 2058:     if (!$is_custom->{'font'}) {
 2059:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 2060:     } else {
 2061:         $datatable .= '<td>&nbsp;</td>';
 2062:     }
 2063:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 2064: 
 2065:     $datatable .= '<td><span class="LC_nobreak">'.
 2066:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 2067:                   ' value="'.$current_color.'" />&nbsp;'.
 2068:                   '&nbsp;</span></td></tr>';
 2069:     unless ($role eq 'login') { 
 2070:         $datatable .= '<tr'.$css_class.'>'.
 2071:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 2072:         if (!$is_custom->{'fontmenu'}) {
 2073:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 2074:         } else {
 2075:             $datatable .= '<td>&nbsp;</td>';
 2076:         }
 2077: 	$current_color = $designs->{'fontmenu'} ?
 2078: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 2079:         $datatable .= '<td><span class="LC_nobreak">'.
 2080:                       '<input class="colorchooser" type="text" size="10" name="'
 2081: 		      .$role.'_fontmenu"'.
 2082:                       ' value="'.$current_color.'" />&nbsp;'.
 2083:                       '&nbsp;</span></td></tr>';
 2084:     }
 2085:     my $switchserver = &check_switchserver($dom,$confname);
 2086:     foreach my $img (@{$images}) {
 2087: 	$itemcount ++;
 2088:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2089:         $datatable .= '<tr'.$css_class.'>'.
 2090:                       '<td>'.$choices->{$img};
 2091:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 2092:         if ($role eq 'login') {
 2093:             if ($img eq 'login') {
 2094:                 $login_hdr_pick =
 2095:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 2096:                 $logincolors =
 2097:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 2098:                                        $designs,$defaults);
 2099:             } else {
 2100:                 if ($img ne 'domlogo') {
 2101:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 2102:                 }
 2103:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 2104:                     $alttext = $designs->{'alttext'}{$img};
 2105:                 }
 2106:             }
 2107:         }
 2108:         $datatable .= '</td>';
 2109:         if ($designs->{$img} ne '') {
 2110:             $imgfile = $designs->{$img};
 2111: 	    $img_import = ($imgfile =~ m{^/adm/});
 2112:         } else {
 2113:             $imgfile = $defaults->{$img};
 2114:         }
 2115:         if ($imgfile) {
 2116:             my ($showfile,$fullsize);
 2117:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 2118:                 my $urldir = $1;
 2119:                 my $filename = $2;
 2120:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 2121:                 if (@info) {
 2122:                     my $thumbfile = 'tn-'.$filename;
 2123:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 2124:                     if (@thumb) {
 2125:                         $showfile = $urldir.'/'.$thumbfile;
 2126:                     } else {
 2127:                         $showfile = $imgfile;
 2128:                     }
 2129:                 } else {
 2130:                     $showfile = '';
 2131:                 }
 2132:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 2133:                 $showfile = $imgfile;
 2134:                 my $imgdir = $1;
 2135:                 my $filename = $2;
 2136:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 2137:                     $showfile = "/$imgdir/tn-".$filename;
 2138:                 } else {
 2139:                     my $input = $londocroot.$imgfile;
 2140:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 2141:                     if (!-e $output) {
 2142:                         my ($width,$height) = &thumb_dimensions();
 2143:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 2144:                         if ($fullwidth ne '' && $fullheight ne '') {
 2145:                             if ($fullwidth > $width && $fullheight > $height) { 
 2146:                                 my $size = $width.'x'.$height;
 2147:                                 my @args = ('convert','-sample',$size,$input,$output);
 2148:                                 system({$args[0]} @args);
 2149:                                 $showfile = "/$imgdir/tn-".$filename;
 2150:                             }
 2151:                         }
 2152:                     }
 2153:                 }
 2154:             }
 2155:             if ($showfile) {
 2156:                 if ($showfile =~ m{^/(adm|res)/}) {
 2157:                     if ($showfile =~ m{^/res/}) {
 2158:                         my $local_showfile =
 2159:                             &Apache::lonnet::filelocation('',$showfile);
 2160:                         &Apache::lonnet::repcopy($local_showfile);
 2161:                     }
 2162:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2163:                 }
 2164:                 if ($imgfile) {
 2165:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2166:                         if ($imgfile =~ m{^/res/}) {
 2167:                             my $local_imgfile =
 2168:                                 &Apache::lonnet::filelocation('',$imgfile);
 2169:                             &Apache::lonnet::repcopy($local_imgfile);
 2170:                         }
 2171:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2172:                     } else {
 2173:                         $fullsize = $imgfile;
 2174:                     }
 2175:                 }
 2176:                 $datatable .= '<td>';
 2177:                 if ($img eq 'login') {
 2178:                     $datatable .= $login_hdr_pick;
 2179:                 } 
 2180:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2181:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2182:             } else {
 2183:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2184:                               &mt('Upload:').'<br />';
 2185:             }
 2186:         } else {
 2187:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2188:                           &mt('Upload:').'<br />';
 2189:         }
 2190:         if ($switchserver) {
 2191:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2192:         } else {
 2193:             if ($img ne 'login') { # suppress file selection for Log-in header
 2194:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2195:             }
 2196:         }
 2197:         if (($role eq 'login') && ($img ne 'login')) {
 2198:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2199:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2200:                           '</label></span>';
 2201:         }
 2202:         $datatable .= '</td></tr>';
 2203:     }
 2204:     $itemcount ++;
 2205:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2206:     $datatable .= '<tr'.$css_class.'>'.
 2207:                   '<td>'.$choices->{'bgs'}.'</td>';
 2208:     my $bgs_def;
 2209:     foreach my $item (@{$bgs}) {
 2210:         if (!$is_custom->{$item}) {
 2211:             $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>';
 2212:         }
 2213:     }
 2214:     if ($bgs_def) {
 2215:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2216:     } else {
 2217:         $datatable .= '<td>&nbsp;</td>';
 2218:     }
 2219:     $datatable .= '<td class="LC_right_item">'.
 2220:                   '<table border="0"><tr>';
 2221: 
 2222:     foreach my $item (@{$bgs}) {
 2223:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 2224: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2225:         if ($designs->{'bgs'}{$item}) {
 2226:             $datatable .= '&nbsp;';
 2227:         }
 2228:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2229:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2230:     }
 2231:     $datatable .= '</tr></table></td></tr>';
 2232:     $itemcount ++;
 2233:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2234:     $datatable .= '<tr'.$css_class.'>'.
 2235:                   '<td>'.$choices->{'links'}.'</td>';
 2236:     my $links_def;
 2237:     foreach my $item (@{$links}) {
 2238:         if (!$is_custom->{$item}) {
 2239:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2240:         }
 2241:     }
 2242:     if ($links_def) {
 2243:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2244:     } else {
 2245:         $datatable .= '<td>&nbsp;</td>';
 2246:     }
 2247:     $datatable .= '<td class="LC_right_item">'.
 2248:                   '<table border="0"><tr>';
 2249:     foreach my $item (@{$links}) {
 2250: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2251:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 2252:         if ($designs->{'links'}{$item}) {
 2253:             $datatable.='&nbsp;';
 2254:         }
 2255:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2256:                       '" /></td>';
 2257:     }
 2258:     $$rowtotal += $itemcount;
 2259:     return $datatable;
 2260: }
 2261: 
 2262: sub logo_display_options {
 2263:     my ($img,$defaults,$designs) = @_;
 2264:     my $checkedon;
 2265:     if (ref($defaults) eq 'HASH') {
 2266:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2267:             if ($defaults->{'showlogo'}{$img}) {
 2268:                 $checkedon = 'checked="checked" ';     
 2269:             }
 2270:         } 
 2271:     }
 2272:     if (ref($designs) eq 'HASH') {
 2273:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2274:             if (defined($designs->{'showlogo'}{$img})) {
 2275:                 if ($designs->{'showlogo'}{$img} == 0) {
 2276:                     $checkedon = '';
 2277:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2278:                     $checkedon = 'checked="checked" ';
 2279:                 }
 2280:             }
 2281:         }
 2282:     }
 2283:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2284:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2285:            &mt('show').'</label>'."\n";
 2286: }
 2287: 
 2288: sub login_header_options  {
 2289:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2290:     my $output = '';
 2291:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2292:         $output .= &mt('Text default(s):').'<br />';
 2293:         if (!$is_custom->{'textcol'}) {
 2294:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2295:                        '&nbsp;&nbsp;&nbsp;';
 2296:         }
 2297:         if (!$is_custom->{'bgcol'}) {
 2298:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2299:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2300:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2301:         }
 2302:         $output .= '<br />';
 2303:     }
 2304:     $output .='<br />';
 2305:     return $output;
 2306: }
 2307: 
 2308: sub login_text_colors {
 2309:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2310:     my $color_menu = '<table border="0"><tr>';
 2311:     foreach my $item (@{$logintext}) {
 2312:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 2313:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2314:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2315:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2316:     }
 2317:     $color_menu .= '</tr></table><br />';
 2318:     return $color_menu;
 2319: }
 2320: 
 2321: sub image_changes {
 2322:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2323:     my $output;
 2324:     if ($img eq 'login') {
 2325:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2326:     } elsif (!$is_custom) {
 2327:         if ($img ne 'domlogo') {
 2328:             $output = &mt('Default image:').'<br />';
 2329:         } else {
 2330:             $output = &mt('Default in use:').'<br />';
 2331:         }
 2332:     }
 2333:     if ($img ne 'login') {
 2334:         if ($img_import) {
 2335:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2336:         }
 2337:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2338:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2339:         if ($is_custom) {
 2340:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2341:                        '<input type="checkbox" name="'.
 2342:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2343:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2344:         } else {
 2345:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 2346:         }
 2347:     }
 2348:     return $output;
 2349: }
 2350: 
 2351: sub print_quotas {
 2352:     my ($dom,$settings,$rowtotal,$action) = @_;
 2353:     my $context;
 2354:     if ($action eq 'quotas') {
 2355:         $context = 'tools';
 2356:     } else {
 2357:         $context = $action;
 2358:     }
 2359:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2360:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2361:     my $typecount = 0;
 2362:     my ($css_class,%titles);
 2363:     if ($context eq 'requestcourses') {
 2364:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2365:         @options =('norequest','approval','validate','autolimit');
 2366:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2367:         %titles = &courserequest_titles();
 2368:     } elsif ($context eq 'requestauthor') {
 2369:         @usertools = ('author');
 2370:         @options = ('norequest','approval','automatic');
 2371:         %titles = &authorrequest_titles();
 2372:     } else {
 2373:         @usertools = ('aboutme','blog','webdav','portfolio');
 2374:         %titles = &tool_titles();
 2375:     }
 2376:     if (ref($types) eq 'ARRAY') {
 2377:         foreach my $type (@{$types}) {
 2378:             my ($currdefquota,$currauthorquota);
 2379:             unless (($context eq 'requestcourses') ||
 2380:                     ($context eq 'requestauthor')) {
 2381:                 if (ref($settings) eq 'HASH') {
 2382:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2383:                         $currdefquota = $settings->{defaultquota}->{$type};
 2384:                     } else {
 2385:                         $currdefquota = $settings->{$type};
 2386:                     }
 2387:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2388:                         $currauthorquota = $settings->{authorquota}->{$type};
 2389:                     }
 2390:                 }
 2391:             }
 2392:             if (defined($usertypes->{$type})) {
 2393:                 $typecount ++;
 2394:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2395:                 $datatable .= '<tr'.$css_class.'>'.
 2396:                               '<td>'.$usertypes->{$type}.'</td>'.
 2397:                               '<td class="LC_left_item">';
 2398:                 if ($context eq 'requestcourses') {
 2399:                     $datatable .= '<table><tr>';
 2400:                 }
 2401:                 my %cell;  
 2402:                 foreach my $item (@usertools) {
 2403:                     if ($context eq 'requestcourses') {
 2404:                         my ($curroption,$currlimit);
 2405:                         if (ref($settings) eq 'HASH') {
 2406:                             if (ref($settings->{$item}) eq 'HASH') {
 2407:                                 $curroption = $settings->{$item}->{$type};
 2408:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2409:                                     $currlimit = $1; 
 2410:                                 }
 2411:                             }
 2412:                         }
 2413:                         if (!$curroption) {
 2414:                             $curroption = 'norequest';
 2415:                         }
 2416:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2417:                         foreach my $option (@options) {
 2418:                             my $val = $option;
 2419:                             if ($option eq 'norequest') {
 2420:                                 $val = 0;  
 2421:                             }
 2422:                             if ($option eq 'validate') {
 2423:                                 my $canvalidate = 0;
 2424:                                 if (ref($validations{$item}) eq 'HASH') { 
 2425:                                     if ($validations{$item}{$type}) {
 2426:                                         $canvalidate = 1;
 2427:                                     }
 2428:                                 }
 2429:                                 next if (!$canvalidate);
 2430:                             }
 2431:                             my $checked = '';
 2432:                             if ($option eq $curroption) {
 2433:                                 $checked = ' checked="checked"';
 2434:                             } elsif ($option eq 'autolimit') {
 2435:                                 if ($curroption =~ /^autolimit/) {
 2436:                                     $checked = ' checked="checked"';
 2437:                                 }                       
 2438:                             } 
 2439:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2440:                                   '<input type="radio" name="crsreq_'.$item.
 2441:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2442:                                   $titles{$option}.'</label>';
 2443:                             if ($option eq 'autolimit') {
 2444:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2445:                                                 $item.'_limit_'.$type.'" size="1" '.
 2446:                                                 'value="'.$currlimit.'" />';
 2447:                             }
 2448:                             $cell{$item} .= '</span> ';
 2449:                             if ($option eq 'autolimit') {
 2450:                                 $cell{$item} .= $titles{'unlimited'};
 2451:                             }
 2452:                         }
 2453:                     } elsif ($context eq 'requestauthor') {
 2454:                         my $curroption;
 2455:                         if (ref($settings) eq 'HASH') {
 2456:                             $curroption = $settings->{$type};
 2457:                         }
 2458:                         if (!$curroption) {
 2459:                             $curroption = 'norequest';
 2460:                         }
 2461:                         foreach my $option (@options) {
 2462:                             my $val = $option;
 2463:                             if ($option eq 'norequest') {
 2464:                                 $val = 0;
 2465:                             }
 2466:                             my $checked = '';
 2467:                             if ($option eq $curroption) {
 2468:                                 $checked = ' checked="checked"';
 2469:                             }
 2470:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2471:                                   '<input type="radio" name="authorreq_'.$type.
 2472:                                   '" value="'.$val.'"'.$checked.' />'.
 2473:                                   $titles{$option}.'</label></span>&nbsp; ';
 2474:                         }
 2475:                     } else {
 2476:                         my $checked = 'checked="checked" ';
 2477:                         if (ref($settings) eq 'HASH') {
 2478:                             if (ref($settings->{$item}) eq 'HASH') {
 2479:                                 if ($settings->{$item}->{$type} == 0) {
 2480:                                     $checked = '';
 2481:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2482:                                     $checked =  'checked="checked" ';
 2483:                                 }
 2484:                             }
 2485:                         }
 2486:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2487:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2488:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2489:                                       '</label></span>&nbsp; ';
 2490:                     }
 2491:                 }
 2492:                 if ($context eq 'requestcourses') {
 2493:                     $datatable .= '</tr><tr>';
 2494:                     foreach my $item (@usertools) {
 2495:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2496:                     }
 2497:                     $datatable .= '</tr></table>';
 2498:                 }
 2499:                 $datatable .= '</td>';
 2500:                 unless (($context eq 'requestcourses') ||
 2501:                         ($context eq 'requestauthor')) {
 2502:                     $datatable .= 
 2503:                               '<td class="LC_right_item">'.
 2504:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2505:                               '<input type="text" name="quota_'.$type.
 2506:                               '" value="'.$currdefquota.
 2507:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2508:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2509:                               '<input type="text" name="authorquota_'.$type.
 2510:                               '" value="'.$currauthorquota.
 2511:                               '" size="5" /></span></td>';
 2512:                 }
 2513:                 $datatable .= '</tr>';
 2514:             }
 2515:         }
 2516:     }
 2517:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2518:         $defaultquota = '20';
 2519:         $authorquota = '500';
 2520:         if (ref($settings) eq 'HASH') {
 2521:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2522:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2523:             } elsif (defined($settings->{'default'})) {
 2524:                 $defaultquota = $settings->{'default'};
 2525:             }
 2526:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2527:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2528:             }
 2529:         }
 2530:     }
 2531:     $typecount ++;
 2532:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2533:     $datatable .= '<tr'.$css_class.'>'.
 2534:                   '<td>'.$othertitle.'</td>'.
 2535:                   '<td class="LC_left_item">';
 2536:     if ($context eq 'requestcourses') {
 2537:         $datatable .= '<table><tr>';
 2538:     }
 2539:     my %defcell;
 2540:     foreach my $item (@usertools) {
 2541:         if ($context eq 'requestcourses') {
 2542:             my ($curroption,$currlimit);
 2543:             if (ref($settings) eq 'HASH') {
 2544:                 if (ref($settings->{$item}) eq 'HASH') {
 2545:                     $curroption = $settings->{$item}->{'default'};
 2546:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2547:                         $currlimit = $1;
 2548:                     }
 2549:                 }
 2550:             }
 2551:             if (!$curroption) {
 2552:                 $curroption = 'norequest';
 2553:             }
 2554:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2555:             foreach my $option (@options) {
 2556:                 my $val = $option;
 2557:                 if ($option eq 'norequest') {
 2558:                     $val = 0;
 2559:                 }
 2560:                 if ($option eq 'validate') {
 2561:                     my $canvalidate = 0;
 2562:                     if (ref($validations{$item}) eq 'HASH') {
 2563:                         if ($validations{$item}{'default'}) {
 2564:                             $canvalidate = 1;
 2565:                         }
 2566:                     }
 2567:                     next if (!$canvalidate);
 2568:                 }
 2569:                 my $checked = '';
 2570:                 if ($option eq $curroption) {
 2571:                     $checked = ' checked="checked"';
 2572:                 } elsif ($option eq 'autolimit') {
 2573:                     if ($curroption =~ /^autolimit/) {
 2574:                         $checked = ' checked="checked"';
 2575:                     }
 2576:                 }
 2577:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2578:                                   '<input type="radio" name="crsreq_'.$item.
 2579:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2580:                                   $titles{$option}.'</label>';
 2581:                 if ($option eq 'autolimit') {
 2582:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2583:                                        $item.'_limit_default" size="1" '.
 2584:                                        'value="'.$currlimit.'" />';
 2585:                 }
 2586:                 $defcell{$item} .= '</span> ';
 2587:                 if ($option eq 'autolimit') {
 2588:                     $defcell{$item} .= $titles{'unlimited'};
 2589:                 }
 2590:             }
 2591:         } elsif ($context eq 'requestauthor') {
 2592:             my $curroption;
 2593:             if (ref($settings) eq 'HASH') {
 2594:                 $curroption = $settings->{'default'};
 2595:             }
 2596:             if (!$curroption) {
 2597:                 $curroption = 'norequest';
 2598:             }
 2599:             foreach my $option (@options) {
 2600:                 my $val = $option;
 2601:                 if ($option eq 'norequest') {
 2602:                     $val = 0;
 2603:                 }
 2604:                 my $checked = '';
 2605:                 if ($option eq $curroption) {
 2606:                     $checked = ' checked="checked"';
 2607:                 }
 2608:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2609:                               '<input type="radio" name="authorreq_default"'.
 2610:                               ' value="'.$val.'"'.$checked.' />'.
 2611:                               $titles{$option}.'</label></span>&nbsp; ';
 2612:             }
 2613:         } else {
 2614:             my $checked = 'checked="checked" ';
 2615:             if (ref($settings) eq 'HASH') {
 2616:                 if (ref($settings->{$item}) eq 'HASH') {
 2617:                     if ($settings->{$item}->{'default'} == 0) {
 2618:                         $checked = '';
 2619:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2620:                         $checked = 'checked="checked" ';
 2621:                     }
 2622:                 }
 2623:             }
 2624:             $datatable .= '<span class="LC_nobreak"><label>'.
 2625:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2626:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2627:                           '</label></span>&nbsp; ';
 2628:         }
 2629:     }
 2630:     if ($context eq 'requestcourses') {
 2631:         $datatable .= '</tr><tr>';
 2632:         foreach my $item (@usertools) {
 2633:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2634:         }
 2635:         $datatable .= '</tr></table>';
 2636:     }
 2637:     $datatable .= '</td>';
 2638:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2639:         $datatable .= '<td class="LC_right_item">'.
 2640:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2641:                       '<input type="text" name="defaultquota" value="'.
 2642:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2643:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2644:                       '<input type="text" name="authorquota" value="'.
 2645:                       $authorquota.'" size="5" /></span></td>';
 2646:     }
 2647:     $datatable .= '</tr>';
 2648:     $typecount ++;
 2649:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2650:     $datatable .= '<tr'.$css_class.'>'.
 2651:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2652:     if ($context eq 'requestcourses') {
 2653:         $datatable .= &mt('(overrides affiliation, if set)').
 2654:                       '</td>'.
 2655:                       '<td class="LC_left_item">'.
 2656:                       '<table><tr>';
 2657:     } else {
 2658:         $datatable .= &mt('(overrides affiliation, if checked)').
 2659:                       '</td>'.
 2660:                       '<td class="LC_left_item" colspan="2">'.
 2661:                       '<br />';
 2662:     }
 2663:     my %advcell;
 2664:     foreach my $item (@usertools) {
 2665:         if ($context eq 'requestcourses') {
 2666:             my ($curroption,$currlimit);
 2667:             if (ref($settings) eq 'HASH') {
 2668:                 if (ref($settings->{$item}) eq 'HASH') {
 2669:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2670:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2671:                         $currlimit = $1;
 2672:                     }
 2673:                 }
 2674:             }
 2675:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2676:             my $checked = '';
 2677:             if ($curroption eq '') {
 2678:                 $checked = ' checked="checked"';
 2679:             }
 2680:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2681:                                '<input type="radio" name="crsreq_'.$item.
 2682:                                '__LC_adv" value=""'.$checked.' />'.
 2683:                                &mt('No override set').'</label></span>&nbsp; ';
 2684:             foreach my $option (@options) {
 2685:                 my $val = $option;
 2686:                 if ($option eq 'norequest') {
 2687:                     $val = 0;
 2688:                 }
 2689:                 if ($option eq 'validate') {
 2690:                     my $canvalidate = 0;
 2691:                     if (ref($validations{$item}) eq 'HASH') {
 2692:                         if ($validations{$item}{'_LC_adv'}) {
 2693:                             $canvalidate = 1;
 2694:                         }
 2695:                     }
 2696:                     next if (!$canvalidate);
 2697:                 }
 2698:                 my $checked = '';
 2699:                 if ($val eq $curroption) {
 2700:                     $checked = ' checked="checked"';
 2701:                 } elsif ($option eq 'autolimit') {
 2702:                     if ($curroption =~ /^autolimit/) {
 2703:                         $checked = ' checked="checked"';
 2704:                     }
 2705:                 }
 2706:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2707:                                   '<input type="radio" name="crsreq_'.$item.
 2708:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2709:                                   $titles{$option}.'</label>';
 2710:                 if ($option eq 'autolimit') {
 2711:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2712:                                        $item.'_limit__LC_adv" size="1" '.
 2713:                                        'value="'.$currlimit.'" />';
 2714:                 }
 2715:                 $advcell{$item} .= '</span> ';
 2716:                 if ($option eq 'autolimit') {
 2717:                     $advcell{$item} .= $titles{'unlimited'};
 2718:                 }
 2719:             }
 2720:         } elsif ($context eq 'requestauthor') {
 2721:             my $curroption;
 2722:             if (ref($settings) eq 'HASH') {
 2723:                 $curroption = $settings->{'_LC_adv'};
 2724:             }
 2725:             my $checked = '';
 2726:             if ($curroption eq '') {
 2727:                 $checked = ' checked="checked"';
 2728:             }
 2729:             $datatable .= '<span class="LC_nobreak"><label>'.
 2730:                           '<input type="radio" name="authorreq__LC_adv"'.
 2731:                           ' value=""'.$checked.' />'.
 2732:                           &mt('No override set').'</label></span>&nbsp; ';
 2733:             foreach my $option (@options) {
 2734:                 my $val = $option;
 2735:                 if ($option eq 'norequest') {
 2736:                     $val = 0;
 2737:                 }
 2738:                 my $checked = '';
 2739:                 if ($val eq $curroption) {
 2740:                     $checked = ' checked="checked"';
 2741:                 }
 2742:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2743:                               '<input type="radio" name="authorreq__LC_adv"'.
 2744:                               ' value="'.$val.'"'.$checked.' />'.
 2745:                               $titles{$option}.'</label></span>&nbsp; ';
 2746:             }
 2747:         } else {
 2748:             my $checked = 'checked="checked" ';
 2749:             if (ref($settings) eq 'HASH') {
 2750:                 if (ref($settings->{$item}) eq 'HASH') {
 2751:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2752:                         $checked = '';
 2753:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2754:                         $checked = 'checked="checked" ';
 2755:                     }
 2756:                 }
 2757:             }
 2758:             $datatable .= '<span class="LC_nobreak"><label>'.
 2759:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2760:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2761:                           '</label></span>&nbsp; ';
 2762:         }
 2763:     }
 2764:     if ($context eq 'requestcourses') {
 2765:         $datatable .= '</tr><tr>';
 2766:         foreach my $item (@usertools) {
 2767:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2768:         }
 2769:         $datatable .= '</tr></table>';
 2770:     }
 2771:     $datatable .= '</td></tr>';
 2772:     $$rowtotal += $typecount;
 2773:     return $datatable;
 2774: }
 2775: 
 2776: sub print_requestmail {
 2777:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2778:     my ($now,$datatable,%currapp);
 2779:     $now = time;
 2780:     if (ref($settings) eq 'HASH') {
 2781:         if (ref($settings->{'notify'}) eq 'HASH') {
 2782:             if ($settings->{'notify'}{'approval'} ne '') {
 2783:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2784:             }
 2785:         }
 2786:     }
 2787:     my $numinrow = 2;
 2788:     my $css_class;
 2789:     if ($$rowtotal%2) {
 2790:         $css_class = 'LC_odd_row';
 2791:     }
 2792:     if ($customcss) {
 2793:         $css_class .= " $customcss";
 2794:     }
 2795:     $css_class =~ s/^\s+//;
 2796:     if ($css_class) {
 2797:         $css_class = ' class="'.$css_class.'"';
 2798:     }
 2799:     if ($rowstyle) {
 2800:         $css_class .= ' style="'.$rowstyle.'"';
 2801:     }
 2802:     my $text;
 2803:     if ($action eq 'requestcourses') {
 2804:         $text = &mt('Receive notification of course requests requiring approval');
 2805:     } elsif ($action eq 'requestauthor') {
 2806:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2807:     } else {
 2808:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2809:     }
 2810:     $datatable = '<tr'.$css_class.'>'.
 2811:                  ' <td>'.$text.'</td>'.
 2812:                  ' <td class="LC_left_item">';
 2813:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2814:                                                  $action.'notifyapproval',%currapp);
 2815:     if ($numdc > 0) {
 2816:         $datatable .= $table;
 2817:     } else {
 2818:         $datatable .= &mt('There are no active Domain Coordinators');
 2819:     }
 2820:     $datatable .='</td></tr>';
 2821:     return $datatable;
 2822: }
 2823: 
 2824: sub print_studentcode {
 2825:     my ($settings,$rowtotal) = @_;
 2826:     my $rownum = 0; 
 2827:     my ($output,%current);
 2828:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2829:     if (ref($settings) eq 'HASH') {
 2830:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2831:             foreach my $type (@crstypes) {
 2832:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2833:             }
 2834:         }
 2835:     }
 2836:     $output .= '<tr>'.
 2837:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2838:                '<td class="LC_left_item">';
 2839:     foreach my $type (@crstypes) {
 2840:         my $check = ' ';
 2841:         if ($current{$type}) {
 2842:             $check = ' checked="checked" ';
 2843:         }
 2844:         $output .= '<span class="LC_nobreak"><label>'.
 2845:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2846:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2847:     }
 2848:     $output .= '</td></tr>';
 2849:     $$rowtotal ++;
 2850:     return $output;
 2851: }
 2852: 
 2853: sub print_textbookcourses {
 2854:     my ($dom,$type,$settings,$rowtotal) = @_;
 2855:     my $rownum = 0;
 2856:     my $css_class;
 2857:     my $itemcount = 1;
 2858:     my $maxnum = 0;
 2859:     my $bookshash;
 2860:     if (ref($settings) eq 'HASH') {
 2861:         $bookshash = $settings->{$type};
 2862:     }
 2863:     my %ordered;
 2864:     if (ref($bookshash) eq 'HASH') {
 2865:         foreach my $item (keys(%{$bookshash})) {
 2866:             if (ref($bookshash->{$item}) eq 'HASH') {
 2867:                 my $num = $bookshash->{$item}{'order'};
 2868:                 $ordered{$num} = $item;
 2869:             }
 2870:         }
 2871:     }
 2872:     my $confname = $dom.'-domainconfig';
 2873:     my $switchserver = &check_switchserver($dom,$confname);
 2874:     my $maxnum = scalar(keys(%ordered));
 2875:     my $datatable;
 2876:     if (keys(%ordered)) {
 2877:         my @items = sort { $a <=> $b } keys(%ordered);
 2878:         for (my $i=0; $i<@items; $i++) {
 2879:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2880:             my $key = $ordered{$items[$i]};
 2881:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2882:             my $coursetitle = $coursehash{'description'};
 2883:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2884:             if (ref($bookshash->{$key}) eq 'HASH') {
 2885:                 $subject = $bookshash->{$key}->{'subject'};
 2886:                 $title = $bookshash->{$key}->{'title'};
 2887:                 if ($type eq 'textbooks') {
 2888:                     $publisher = $bookshash->{$key}->{'publisher'};
 2889:                     $author = $bookshash->{$key}->{'author'};
 2890:                     $image = $bookshash->{$key}->{'image'};
 2891:                     if ($image ne '') {
 2892:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2893:                         my $imagethumb = "$path/tn-".$imagefile;
 2894:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2895:                     }
 2896:                 }
 2897:             }
 2898:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2899:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2900:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2901:             for (my $k=0; $k<=$maxnum; $k++) {
 2902:                 my $vpos = $k+1;
 2903:                 my $selstr;
 2904:                 if ($k == $i) {
 2905:                     $selstr = ' selected="selected" ';
 2906:                 }
 2907:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2908:             }
 2909:             $datatable .= '</select>'.('&nbsp;'x2).
 2910:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2911:                 &mt('Delete?').'</label></span></td>'.
 2912:                 '<td colspan="2">'.
 2913:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2914:                 ('&nbsp;'x2).
 2915:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2916:             if ($type eq 'textbooks') {
 2917:                 $datatable .= ('&nbsp;'x2).
 2918:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2919:                               ('&nbsp;'x2).
 2920:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2921:                               ('&nbsp;'x2).
 2922:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2923:                 if ($image) {
 2924:                     $datatable .= $imgsrc.
 2925:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2926:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2927:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2928:                 }
 2929:                 if ($switchserver) {
 2930:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2931:                 } else {
 2932:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2933:                 }
 2934:             }
 2935:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2936:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2937:                           $coursetitle.'</span></td></tr>'."\n";
 2938:             $itemcount ++;
 2939:         }
 2940:     }
 2941:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2942:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2943:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2944:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2945:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2946:     for (my $k=0; $k<$maxnum+1; $k++) {
 2947:         my $vpos = $k+1;
 2948:         my $selstr;
 2949:         if ($k == $maxnum) {
 2950:             $selstr = ' selected="selected" ';
 2951:         }
 2952:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2953:     }
 2954:     $datatable .= '</select>&nbsp;'."\n".
 2955:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2956:                   '<td colspan="2">'.
 2957:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2958:                   ('&nbsp;'x2).
 2959:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2960:                   ('&nbsp;'x2);
 2961:     if ($type eq 'textbooks') {
 2962:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2963:                       ('&nbsp;'x2).
 2964:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2965:                       ('&nbsp;'x2).
 2966:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2967:         if ($switchserver) {
 2968:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2969:         } else {
 2970:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2971:         }
 2972:         $datatable .= '</span>'."\n";
 2973:     }
 2974:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2975:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2976:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2977:                   &Apache::loncommon::selectcourse_link
 2978:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2979:                   '</span></td>'."\n".
 2980:                   '</tr>'."\n";
 2981:     $itemcount ++;
 2982:     return $datatable;
 2983: }
 2984: 
 2985: sub textbookcourses_javascript {
 2986:     my ($settings) = @_;
 2987:     return unless(ref($settings) eq 'HASH');
 2988:     my (%ordered,%total,%jstext);
 2989:     foreach my $type ('textbooks','templates') {
 2990:         $total{$type} = 0;
 2991:         if (ref($settings->{$type}) eq 'HASH') {
 2992:             foreach my $item (keys(%{$settings->{$type}})) {
 2993:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2994:                     my $num = $settings->{$type}->{$item}{'order'};
 2995:                     $ordered{$type}{$num} = $item;
 2996:                 }
 2997:             }
 2998:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2999:         }
 3000:         my @jsarray = ();
 3001:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 3002:             push(@jsarray,$ordered{$type}{$item});
 3003:         }
 3004:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 3005:     }
 3006:     return <<"ENDSCRIPT";
 3007: <script type="text/javascript">
 3008: // <![CDATA[
 3009: function reorderBooks(form,item,caller) {
 3010:     var changedVal;
 3011: $jstext{'textbooks'};
 3012: $jstext{'templates'};
 3013:     var newpos;
 3014:     var maxh;
 3015:     if (caller == 'textbooks') {  
 3016:         newpos = 'textbooks_addbook_pos';
 3017:         maxh = 1 + $total{'textbooks'};
 3018:     } else {
 3019:         newpos = 'templates_addbook_pos';
 3020:         maxh = 1 + $total{'templates'};
 3021:     }
 3022:     var current = new Array;
 3023:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3024:     if (item == newpos) {
 3025:         changedVal = newitemVal;
 3026:     } else {
 3027:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3028:         current[newitemVal] = newpos;
 3029:     }
 3030:     if (caller == 'textbooks') {
 3031:         for (var i=0; i<textbooks.length; i++) {
 3032:             var elementName = 'textbooks_'+textbooks[i];
 3033:             if (elementName != item) {
 3034:                 if (form.elements[elementName]) {
 3035:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3036:                     current[currVal] = elementName;
 3037:                 }
 3038:             }
 3039:         }
 3040:     }
 3041:     if (caller == 'templates') {
 3042:         for (var i=0; i<templates.length; i++) {
 3043:             var elementName = 'templates_'+templates[i];
 3044:             if (elementName != item) {
 3045:                 if (form.elements[elementName]) {
 3046:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3047:                     current[currVal] = elementName;
 3048:                 }
 3049:             }
 3050:         }
 3051:     }
 3052:     var oldVal;
 3053:     for (var j=0; j<maxh; j++) {
 3054:         if (current[j] == undefined) {
 3055:             oldVal = j;
 3056:         }
 3057:     }
 3058:     if (oldVal < changedVal) {
 3059:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3060:            var elementName = current[k];
 3061:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3062:         }
 3063:     } else {
 3064:         for (var k=changedVal; k<oldVal; k++) {
 3065:             var elementName = current[k];
 3066:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3067:         }
 3068:     }
 3069:     return;
 3070: }
 3071: 
 3072: // ]]>
 3073: </script>
 3074: 
 3075: ENDSCRIPT
 3076: }
 3077: 
 3078: sub ltitools_javascript {
 3079:     my ($settings) = @_;
 3080:     my $togglejs = &ltitools_toggle_js();
 3081:     unless (ref($settings) eq 'HASH') {
 3082:         return $togglejs;
 3083:     }
 3084:     my (%ordered,$total,%jstext);
 3085:     $total = 0;
 3086:     foreach my $item (keys(%{$settings})) {
 3087:         if (ref($settings->{$item}) eq 'HASH') {
 3088:             my $num = $settings->{$item}{'order'};
 3089:             $ordered{$num} = $item;
 3090:         }
 3091:     }
 3092:     $total = scalar(keys(%{$settings}));
 3093:     my @jsarray = ();
 3094:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3095:         push(@jsarray,$ordered{$item});
 3096:     }
 3097:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 3098:     return <<"ENDSCRIPT";
 3099: <script type="text/javascript">
 3100: // <![CDATA[
 3101: function reorderLTITools(form,item) {
 3102:     var changedVal;
 3103: $jstext
 3104:     var newpos = 'ltitools_add_pos';
 3105:     var maxh = 1 + $total;
 3106:     var current = new Array;
 3107:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3108:     if (item == newpos) {
 3109:         changedVal = newitemVal;
 3110:     } else {
 3111:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3112:         current[newitemVal] = newpos;
 3113:     }
 3114:     for (var i=0; i<ltitools.length; i++) {
 3115:         var elementName = 'ltitools_'+ltitools[i];
 3116:         if (elementName != item) {
 3117:             if (form.elements[elementName]) {
 3118:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3119:                 current[currVal] = elementName;
 3120:             }
 3121:         }
 3122:     }
 3123:     var oldVal;
 3124:     for (var j=0; j<maxh; j++) {
 3125:         if (current[j] == undefined) {
 3126:             oldVal = j;
 3127:         }
 3128:     }
 3129:     if (oldVal < changedVal) {
 3130:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3131:            var elementName = current[k];
 3132:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3133:         }
 3134:     } else {
 3135:         for (var k=changedVal; k<oldVal; k++) {
 3136:             var elementName = current[k];
 3137:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3138:         }
 3139:     }
 3140:     return;
 3141: }
 3142: 
 3143: // ]]>
 3144: </script>
 3145: 
 3146: $togglejs
 3147: 
 3148: ENDSCRIPT
 3149: }
 3150: 
 3151: sub ltitools_toggle_js {
 3152:     return <<"ENDSCRIPT";
 3153: <script type="text/javascript">
 3154: // <![CDATA[
 3155: 
 3156: function toggleLTITools(form,setting,item) {
 3157:     var radioname = '';
 3158:     var divid = '';
 3159:     if ((setting == 'passback') || (setting == 'roster')) {
 3160:         radioname = 'ltitools_'+setting+'_'+item;
 3161:         divid = 'ltitools_'+setting+'time_'+item;
 3162:         var num = form.elements[radioname].length;
 3163:         if (num) {
 3164:             var setvis = '';
 3165:             for (var i=0; i<num; i++) {
 3166:                 if (form.elements[radioname][i].checked) {
 3167:                     if (form.elements[radioname][i].value == '1') {
 3168:                         if (document.getElementById(divid)) {
 3169:                             document.getElementById(divid).style.display = 'inline-block';
 3170:                         }
 3171:                         setvis = 1;
 3172:                     }
 3173:                     break;
 3174:                 }
 3175:             }
 3176:         }
 3177:         if (!setvis) {
 3178:             if (document.getElementById(divid)) {
 3179:                 document.getElementById(divid).style.display = 'none';
 3180:             }
 3181:         }
 3182:     }
 3183:     if (setting == 'user') {
 3184:         divid = 'ltitools_'+setting+'_div_'+item;
 3185:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3186:         if (document.getElementById(divid)) {
 3187:             if (document.getElementById(checkid)) {
 3188:                 if (document.getElementById(checkid).checked) {
 3189:                     document.getElementById(divid).style.display = 'inline-block';
 3190:                 } else {
 3191:                     document.getElementById(divid).style.display = 'none';
 3192:                 }
 3193:             }
 3194:         }
 3195:     }
 3196:     return;
 3197: }
 3198: // ]]>
 3199: </script>
 3200: 
 3201: ENDSCRIPT
 3202: }
 3203: 
 3204: sub wafproxy_javascript {
 3205:     my ($dom) = @_;
 3206:     return <<"ENDSCRIPT";
 3207: <script type="text/javascript">
 3208: // <![CDATA[
 3209: function updateWAF() {
 3210:     if (document.getElementById('wafproxy_remoteip')) {
 3211:         var wafremote = 0;
 3212:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3213:             wafremote = 1;
 3214:         }
 3215:         var fields = new Array('header','trust');
 3216:         for (var i=0; i<fields.length; i++) {
 3217:             if (document.getElementById('wafproxy_'+fields[i])) {
 3218:                 if (wafremote == 1) {
 3219:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3220:                 }
 3221:                 else {
 3222:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3223:                 }
 3224:             }
 3225:         }
 3226:         if (document.getElementById('wafproxyranges_$dom')) {
 3227:             if (wafremote == 1) {
 3228:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3229:             } else {
 3230:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3231:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3232:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3233:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3234:                         }
 3235:                     }
 3236:                 }
 3237:             }
 3238:         }
 3239:     }
 3240:     return;
 3241: }
 3242: 
 3243: function checkWAF() {
 3244:     if (document.getElementById('wafproxy_remoteip')) {
 3245:         var wafvpn = 0;
 3246:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3247:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3248:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3249:                     wafvpn = 1;
 3250:                 }
 3251:                 break;
 3252:             }
 3253:         }
 3254:         var vpn = new Array('vpnint','vpnext');
 3255:         for (var i=0; i<vpn.length; i++) {
 3256:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3257:                 if (wafvpn == 1) {
 3258:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3259:                 }
 3260:                 else {
 3261:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3262:                 }
 3263:             }
 3264:         }
 3265:         if (document.getElementById('wafproxyranges_$dom')) {
 3266:             if (wafvpn == 1) {
 3267:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3268:             }
 3269:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3270:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3271:             }
 3272:         }
 3273:     }
 3274:     return;
 3275: }
 3276: 
 3277: function toggleWAF() {
 3278:     if (document.getElementById('wafproxy_table')) {
 3279:         var wafproxy = 0;
 3280:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3281:              if (document.display.wafproxy_${dom}[i].checked) {
 3282:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3283:                      wafproxy = 1;
 3284:                      break;
 3285:                 }
 3286:             }
 3287:         }
 3288:         if (wafproxy == 1) {
 3289:             document.getElementById('wafproxy_table').style.display='inline';
 3290:         }
 3291:         else {
 3292:            document.getElementById('wafproxy_table').style.display='none';
 3293:         }
 3294:         if (document.getElementById('wafproxyrow_${dom}')) {
 3295:             if (wafproxy == 1) {
 3296:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3297:             }
 3298:             else {
 3299:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3300:             }
 3301:         }
 3302:         if (document.getElementById('nowafproxyrow_$dom')) {
 3303:             if (wafproxy == 1) {
 3304:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3305:             }
 3306:             else {
 3307:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3308:             }
 3309:         }
 3310:     }
 3311:     return;
 3312: }
 3313: // ]]>
 3314: </script>
 3315: 
 3316: ENDSCRIPT
 3317: }
 3318: 
 3319: sub proctoring_javascript {
 3320:     my ($settings) = @_;
 3321:     my (%ordered,$total,%jstext);
 3322:     $total = 0;
 3323:     if (ref($settings) eq 'HASH') {
 3324:         foreach my $item (keys(%{$settings})) {
 3325:             if (ref($settings->{$item}) eq 'HASH') {
 3326:                 my $num = $settings->{$item}{'order'};
 3327:                 $ordered{$num} = $item;
 3328:             }
 3329:         }
 3330:         $total = scalar(keys(%{$settings}));
 3331:     } else {
 3332:         %ordered = (
 3333:                        0 => 'proctorio',
 3334:                        1 => 'examity',
 3335:                    );
 3336:         $total = 2; 
 3337:     }
 3338:     my @jsarray = ();
 3339:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3340:         push(@jsarray,$ordered{$item});
 3341:     }
 3342:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 3343:     return <<"ENDSCRIPT";
 3344: <script type="text/javascript">
 3345: // <![CDATA[
 3346: function reorderProctoring(form,item) {
 3347:     var changedVal;
 3348: $jstext
 3349:     var maxh = $total;
 3350:     var current = new Array;
 3351:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3352:     for (var i=0; i<proctors.length; i++) {
 3353:         var elementName = 'proctoring_pos_'+proctors[i];
 3354:         if (elementName != item) {
 3355:             if (form.elements[elementName]) {
 3356:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3357:                 current[currVal] = elementName;
 3358:             }
 3359:         }
 3360:     }
 3361:     var oldVal;
 3362:     for (var j=0; j<maxh; j++) {
 3363:         if (current[j] == undefined) {
 3364:             oldVal = j;
 3365:         }
 3366:     }
 3367:     if (oldVal < changedVal) {
 3368:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3369:            var elementName = current[k];
 3370:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3371:         }
 3372:     } else {
 3373:         for (var k=changedVal; k<oldVal; k++) {
 3374:             var elementName = current[k];
 3375:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3376:         }
 3377:     }
 3378:     return;
 3379: }
 3380: 
 3381: function toggleProctoring(form,item) {
 3382:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3383:     if (fieldsets.length) {
 3384:         var radioname = 'proctoring_available_'+item;
 3385:         var num = form.elements[radioname].length;
 3386:         if (num) {
 3387:             var setvis = '';
 3388:             for (var i=0; i<num; i++) {
 3389:                 if (form.elements[radioname][i].checked) {
 3390:                     if (form.elements[radioname][i].value == '1') {
 3391:                        setvis = 1;
 3392:                        break;
 3393:                     }
 3394:                 }
 3395:             }
 3396:             for (var j=0; j<fieldsets.length; j++) {
 3397:                 if (setvis) {
 3398:                     fieldsets[j].style.display = 'block';
 3399:                 } else {
 3400:                     fieldsets[j].style.display = 'none';
 3401:                 }
 3402:             }
 3403:         }
 3404:     }
 3405:     return;
 3406: }
 3407: 
 3408: // ]]>
 3409: </script>
 3410: 
 3411: ENDSCRIPT
 3412: }
 3413: 
 3414: 
 3415: sub lti_javascript {
 3416:     my ($dom,$settings) = @_;
 3417:     my $togglejs = &lti_toggle_js($dom);
 3418:     unless (ref($settings) eq 'HASH') {
 3419:         return $togglejs;
 3420:     }
 3421:     my (%ordered,$total,%jstext);
 3422:     $total = scalar(keys(%{$settings}));
 3423:     foreach my $item (keys(%{$settings})) {
 3424:         if (ref($settings->{$item}) eq 'HASH') {
 3425:             my $num = $settings->{$item}{'order'};
 3426:             if ($num eq '') {
 3427:                 $num = $total - 1;
 3428:             }
 3429:             $ordered{$num} = $item;
 3430:         }
 3431:     }
 3432:     my @jsarray = ();
 3433:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3434:         push(@jsarray,$ordered{$item});
 3435:     }
 3436:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3437:     my $linkprot_js = &Apache::courseprefs::linkprot_javascript();
 3438:     return <<"ENDSCRIPT";
 3439: <script type="text/javascript">
 3440: // <![CDATA[
 3441: function reorderLTI(form,item) {
 3442:     var changedVal;
 3443: $jstext
 3444:     var newpos = 'lti_pos_add';
 3445:     var maxh = 1 + $total;
 3446:     var current = new Array;
 3447:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3448:     if (item == newpos) {
 3449:         changedVal = newitemVal;
 3450:     } else {
 3451:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3452:         current[newitemVal] = newpos;
 3453:     }
 3454:     for (var i=0; i<lti.length; i++) {
 3455:         var elementName = 'lti_pos_'+lti[i];
 3456:         if (elementName != item) {
 3457:             if (form.elements[elementName]) {
 3458:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3459:                 current[currVal] = elementName;
 3460:             }
 3461:         }
 3462:     }
 3463:     var oldVal;
 3464:     for (var j=0; j<maxh; j++) {
 3465:         if (current[j] == undefined) {
 3466:             oldVal = j;
 3467:         }
 3468:     }
 3469:     if (oldVal < changedVal) {
 3470:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3471:            var elementName = current[k];
 3472:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3473:         }
 3474:     } else {
 3475:         for (var k=changedVal; k<oldVal; k++) {
 3476:             var elementName = current[k];
 3477:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3478:         }
 3479:     }
 3480:     return;
 3481: }
 3482: 
 3483: $linkprot_js
 3484: 
 3485: // ]]>
 3486: </script>
 3487: 
 3488: $togglejs
 3489: 
 3490: ENDSCRIPT
 3491: }
 3492: 
 3493: sub lti_toggle_js {
 3494:     my ($dom) = @_;
 3495:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3496:                             localauth => 'Local auth argument',
 3497:                             krb       => 'Kerberos domain',
 3498:                          );
 3499:     my $crsincalert = &mt('"User\'s identity sent" needs to be set to "Yes" first,[_1] before setting "Course\'s identity sent" to "Yes"',"\n");
 3500:     &js_escape(\$crsincalert);
 3501:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3502:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3503:     my $course_servers = "'".join("','",keys(%servers))."'";
 3504: 
 3505:     return <<"ENDSCRIPT";
 3506: <script type="text/javascript">
 3507: // <![CDATA[
 3508: 
 3509: function toggleLTI(form,setting,item) {
 3510:     if ((setting == 'requser') || (setting == 'crsinc')) {
 3511:         var usrfieldsets = document.getElementsByClassName('ltioption_usr_'+item);
 3512:         var setvis = '';
 3513:         var radioname = 'lti_requser_'+item;
 3514:         var num = form.elements[radioname].length;
 3515:         if (num) {
 3516:             for (var i=0; i<num; i++) {
 3517:                 if (form.elements[radioname][i].checked) {
 3518:                     if (form.elements[radioname][i].value == '1') {
 3519:                         setvis = 1;
 3520:                         break;
 3521:                     }
 3522:                 }
 3523:             }
 3524:         }
 3525:         if (usrfieldsets.length) {
 3526:             for (var j=0; j<usrfieldsets.length; j++) {
 3527:                 if (setvis) {
 3528:                     usrfieldsets[j].style.display = 'block';
 3529:                 } else {
 3530:                     usrfieldsets[j].style.display = 'none';
 3531:                 }
 3532:             }
 3533:         }
 3534:         var crsfieldsets = document.getElementsByClassName('ltioption_crs_'+item);
 3535:         if (crsfieldsets.length) {
 3536:             radioname = 'lti_crsinc_'+item;
 3537:             var num = form.elements[radioname].length;
 3538:             if (num) {
 3539:                 var crsvis = '';
 3540:                 for (var i=0; i<num; i++) {
 3541:                     if (form.elements[radioname][i].checked) {
 3542:                         if (form.elements[radioname][i].value == '1') {
 3543:                             if (setvis == '') {
 3544:                                 if (setting == 'crsinc'){
 3545:                                     alert("$crsincalert");
 3546:                                     form.elements[radioname][0].checked = true;
 3547:                                 }
 3548:                             } else {
 3549:                                 crsvis = 1;
 3550:                             }
 3551:                             break;
 3552:                         }
 3553:                     }
 3554:                 }
 3555:                 setvis = crsvis;
 3556:             }
 3557:             for (var j=0; j<crsfieldsets.length; j++) {
 3558:                 if (setvis) {
 3559:                     crsfieldsets[j].style.display = 'block';
 3560:                 } else {
 3561:                     crsfieldsets[j].style.display = 'none';
 3562:                 }
 3563:             }
 3564:         }
 3565:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3566:         var radioname = '';
 3567:         var divid = '';
 3568:         if (setting == 'user') {
 3569:             radioname = 'lti_mapuser_'+item;
 3570:             divid = 'lti_userfield_'+item;
 3571:         } else if (setting == 'crs') {
 3572:             radioname = 'lti_mapcrs_'+item;
 3573:             divid = 'lti_crsfield_'+item;
 3574:         } else if (setting == 'callback') {
 3575:             radioname = 'lti_callback_'+item;
 3576:             divid = 'lti_callbackfield_'+item;
 3577:         } else {
 3578:             radioname = 'lti_passback_'+item;
 3579:             divid =  'lti_passback_'+item;
 3580:         }
 3581:         var num = form.elements[radioname].length;
 3582:         if (num) {
 3583:             var setvis = '';
 3584:             for (var i=0; i<num; i++) {
 3585:                if (form.elements[radioname][i].checked) {
 3586:                    if ((setting == 'passback') || (setting == 'callback')) {
 3587:                        if (form.elements[radioname][i].value == '1') {
 3588:                            if (document.getElementById(divid)) {
 3589:                                document.getElementById(divid).style.display = 'inline-block';
 3590:                            }
 3591:                            setvis = 1;
 3592:                            break;
 3593:                        }
 3594:                    } else {
 3595:                        if (form.elements[radioname][i].value == 'other') {
 3596:                            if (document.getElementById(divid)) {
 3597:                                document.getElementById(divid).style.display = 'inline-block';
 3598:                            }
 3599:                            setvis = 1;
 3600:                            break;
 3601:                        }
 3602:                    }
 3603:                } 
 3604:             }
 3605:             if (!setvis) {
 3606:                 if (document.getElementById(divid)) {
 3607:                     document.getElementById(divid).style.display = 'none';
 3608:                 }
 3609:             }
 3610:         }
 3611:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3612:         var numsec = form.elements['lti_crssec_'+item].length;
 3613:         if (numsec) {
 3614:             var setvis = '';
 3615:             for (var i=0; i<numsec; i++) {
 3616:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3617:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3618:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3619:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3620:                             setvis = 1;
 3621:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3622:                             if (numsrcsec) {
 3623:                                 var setsrcvis = '';
 3624:                                 for (var j=0; j<numsrcsec; j++) {
 3625:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3626:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3627:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3628:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3629:                                                 setsrcvis = 1;
 3630:                                             }
 3631:                                         }
 3632:                                     }
 3633:                                 }
 3634:                                 if (!setsrcvis) {
 3635:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3636:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3637:                                     }
 3638:                                 }
 3639:                             }
 3640:                         }
 3641:                     }
 3642:                 }
 3643:             }
 3644:             if (!setvis) {
 3645:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3646:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3647:                 }
 3648:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3649:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3650:                 }
 3651:             }
 3652:         }
 3653:     } else if (setting == 'lcauth') {
 3654:         var numauth = form.elements['lti_lcauth_'+item].length;
 3655:         if (numauth) {
 3656:             for (var i=0; i<numauth; i++) {
 3657:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3658:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3659:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3660:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3661:                         } else {
 3662:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3663:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3664:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3665:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3666:                                 } else {
 3667:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3668:                                 }
 3669:                             }
 3670:                         }
 3671:                     }
 3672:                 }
 3673:             }
 3674:         }
 3675:     } else if (setting == 'lcmenu') {
 3676:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3677:         var divid = 'lti_menufield_'+item;
 3678:         var setvis = '';
 3679:         for (var i=0; i<menus.length; i++) {
 3680:             var radioname = menus[i];  
 3681:             var num = form.elements[radioname].length;
 3682:             if (num) {
 3683:                 for (var j=0; j<num; j++) {
 3684:                     if (form.elements[radioname][j].checked) {
 3685:                         if (form.elements[radioname][j].value == '1') {
 3686:                             if (document.getElementById(divid)) {
 3687:                                 document.getElementById(divid).style.display = 'inline-block';
 3688:                             }
 3689:                             setvis = 1;
 3690:                             break;
 3691:                         }
 3692:                     }
 3693:                 }
 3694:             }
 3695:             if (setvis == 1) {
 3696:                 break;
 3697:             }
 3698:         }
 3699:         if (!setvis) {
 3700:             if (document.getElementById(divid)) {
 3701:                 document.getElementById(divid).style.display = 'none';
 3702:             }
 3703:         }
 3704:     }
 3705:     return;
 3706: }
 3707: 
 3708: function toggleLTIEncKey(form) {
 3709:     var shownhosts = new Array();
 3710:     var hiddenhosts = new Array();
 3711:     var forcourse = new Array($course_servers);
 3712:     var fromdomain = '$primary';
 3713:     var crsradio = form.elements['ltisec_crslinkprot'];
 3714:     if (crsradio.length) {
 3715:         for (var i=0; i<crsradio.length; i++) {
 3716:             if (crsradio[i].checked) {
 3717:                 if (crsradio[i].value == 1) {
 3718:                     if (forcourse.length > 0) {
 3719:                         for (var j=0; j<forcourse.length; j++) {
 3720:                             if (!shownhosts.includes(forcourse[j])) {
 3721:                                 shownhosts.push(forcourse[j]);
 3722:                             }
 3723:                         }
 3724:                     }
 3725:                 } else {
 3726:                     if (forcourse.length > 0) {
 3727:                         for (var j=0; j<forcourse.length; j++) {
 3728:                             if (!hiddenhosts.includes(forcourse[j])) { 
 3729:                                 hiddenhosts.push(forcourse[j]);
 3730:                             }
 3731:                         }
 3732:                     } 
 3733:                 }
 3734:             }
 3735:         }
 3736:     }
 3737:     var domradio = form.elements['ltisec_domlinkprot'];
 3738:     if (domradio.length) {
 3739:         for (var i=0; i<domradio.length; i++) {
 3740:             if (domradio[i].checked) {
 3741:                 if (domradio[i].value == 1) {
 3742:                     if (!shownhosts.includes(fromdomain)) { 
 3743:                         shownhosts.push(fromdomain);
 3744:                     }
 3745:                 } else {
 3746:                     if (!hiddenhosts.includes(fromdomain)) {
 3747:                         hiddenhosts.push(fromdomain);
 3748:                     }
 3749:                 }
 3750:             }
 3751:         }
 3752:     }
 3753:     var consumersradio = form.elements['ltisec_consumers'];
 3754:     if (consumersradio.length) {
 3755:         for (var i=0; i<consumersradio.length; i++) {
 3756:             if (consumersradio[i].checked) {
 3757:                 if (consumersradio[i].value == 1) {
 3758:                     if (!shownhosts.includes(fromdomain)) {     
 3759:                         shownhosts.push(fromdomain);
 3760:                     }
 3761:                 } else {
 3762:                     if (!hiddenhosts.includes(fromdomain)) {
 3763:                         hiddenhosts.push(fromdomain);
 3764:                     }
 3765:                 }
 3766:             }
 3767:         }
 3768:     }
 3769:     if (shownhosts.length > 0) {
 3770:         for (var i=0; i<shownhosts.length; i++) {
 3771:             if (document.getElementById('ltisec_info_'+shownhosts[i])) {
 3772:                 document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';                 
 3773:             }
 3774:         }
 3775:         if (document.getElementById('ltisec_noprivkey')) {
 3776:             document.getElementById('ltisec_noprivkey').style.display = 'none';
 3777:         }
 3778:     } else {
 3779:         if (document.getElementById('ltisec_noprivkey')) {
 3780:             document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
 3781:         }
 3782:     }
 3783:     if (hiddenhosts.length > 0) {
 3784:         for (var i=0; i<hiddenhosts.length; i++) {
 3785:             if (!shownhosts.includes(hiddenhosts[i])) {
 3786:                 if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
 3787:                     document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
 3788:                 }
 3789:             }
 3790:         }
 3791:     }
 3792:     return;
 3793: }
 3794: 
 3795: function togglePrivKey(form,hostid) {
 3796:     var radioname = '';
 3797:     var currdivid = '';
 3798:     var newdivid = '';
 3799:     if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
 3800:         (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
 3801:         currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
 3802:         newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
 3803:         radioname = form.elements['ltisec_changeprivkey_'+hostid];
 3804:         if (radioname) {
 3805:             if (radioname.length > 0) {
 3806:                 var setvis;
 3807:                 for (var i=0; i<radioname.length; i++) {
 3808:                     if (radioname[i].checked == true) {
 3809:                         if (radioname[i].value == 1) {
 3810:                             newdivid.style.display = 'inline-block';
 3811:                             currdivid.style.display = 'none';
 3812:                             setvis = 1;
 3813:                         }
 3814:                         break;
 3815:                     }
 3816:                 }
 3817:                 if (!setvis) {
 3818:                     newdivid.style.display = 'none';
 3819:                     currdivid.style.display = 'inline-block';
 3820:                 }
 3821:             }
 3822:         }
 3823:     }
 3824: }
 3825: 
 3826: // ]]>
 3827: </script>
 3828: 
 3829: ENDSCRIPT
 3830: }
 3831: 
 3832: sub autoupdate_javascript {
 3833:     return <<"ENDSCRIPT";
 3834: <script type="text/javascript">
 3835: // <![CDATA[
 3836: function toggleLastActiveDays(form) {
 3837:     var radioname = 'lastactive';
 3838:     var divid = 'lastactive_div';
 3839:     var num = form.elements[radioname].length;
 3840:     if (num) {
 3841:         var setvis = '';
 3842:         for (var i=0; i<num; i++) {
 3843:             if (form.elements[radioname][i].checked) {
 3844:                 if (form.elements[radioname][i].value == '1') {
 3845:                     if (document.getElementById(divid)) {
 3846:                         document.getElementById(divid).style.display = 'inline-block';
 3847:                     }
 3848:                     setvis = 1;
 3849:                 }
 3850:                 break;
 3851:             }
 3852:         }
 3853:         if (!setvis) {
 3854:             if (document.getElementById(divid)) {
 3855:                 document.getElementById(divid).style.display = 'none';
 3856:             }
 3857:         }
 3858:     }
 3859:     return;
 3860: }
 3861: // ]]>
 3862: </script>
 3863: 
 3864: ENDSCRIPT
 3865: }
 3866: 
 3867: sub autoenroll_javascript {
 3868:     return <<"ENDSCRIPT";
 3869: <script type="text/javascript">
 3870: // <![CDATA[
 3871: function toggleFailsafe(form) {
 3872:     var radioname = 'autoenroll_failsafe';
 3873:     var divid = 'autoenroll_failsafe_div';
 3874:     var num = form.elements[radioname].length;
 3875:     if (num) {
 3876:         var setvis = '';
 3877:         for (var i=0; i<num; i++) {
 3878:             if (form.elements[radioname][i].checked) {
 3879:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3880:                     if (document.getElementById(divid)) {
 3881:                         document.getElementById(divid).style.display = 'inline-block';
 3882:                     }
 3883:                     setvis = 1;
 3884:                 }
 3885:                 break;
 3886:             }
 3887:         }
 3888:         if (!setvis) {
 3889:             if (document.getElementById(divid)) {
 3890:                 document.getElementById(divid).style.display = 'none';
 3891:             }
 3892:         }
 3893:     }
 3894:     return;
 3895: }
 3896: // ]]>
 3897: </script>
 3898: 
 3899: ENDSCRIPT
 3900: }
 3901: 
 3902: sub saml_javascript {
 3903:     return <<"ENDSCRIPT";
 3904: <script type="text/javascript">
 3905: // <![CDATA[
 3906: function toggleSamlOptions(form,hostid) { 
 3907:     var radioname = 'saml_'+hostid;
 3908:     var tablecellon = 'samloptionson_'+hostid;
 3909:     var tablecelloff = 'samloptionsoff_'+hostid;
 3910:     var num = form.elements[radioname].length;
 3911:     if (num) {
 3912:         var setvis = ''; 
 3913:         for (var i=0; i<num; i++) {
 3914:             if (form.elements[radioname][i].checked) {
 3915:                 if (form.elements[radioname][i].value == '1') { 
 3916:                     if (document.getElementById(tablecellon)) {
 3917:                         document.getElementById(tablecellon).style.display='';
 3918:                     }
 3919:                     if (document.getElementById(tablecelloff)) {
 3920:                         document.getElementById(tablecelloff).style.display='none';
 3921:                     }
 3922:                     setvis = 1;
 3923:                 }
 3924:                 break;
 3925:             }
 3926:         }
 3927:         if (!setvis) {
 3928:             if (document.getElementById(tablecellon)) {
 3929:                 document.getElementById(tablecellon).style.display='none';
 3930:             }
 3931:             if (document.getElementById(tablecelloff)) {
 3932:                 document.getElementById(tablecelloff).style.display='';
 3933:             }
 3934:         }
 3935:     }
 3936:     return;
 3937: }
 3938: // ]]>
 3939: </script>
 3940: 
 3941: ENDSCRIPT
 3942: }
 3943: 
 3944: sub ipaccess_javascript {
 3945:     my ($settings) = @_;
 3946:     my (%ordered,$total,%jstext);
 3947:     $total = 0;
 3948:     if (ref($settings) eq 'HASH') {
 3949:         foreach my $item (keys(%{$settings})) {
 3950:             if (ref($settings->{$item}) eq 'HASH') {
 3951:                 my $num = $settings->{$item}{'order'};
 3952:                 $ordered{$num} = $item;
 3953:             }
 3954:         }
 3955:         $total = scalar(keys(%{$settings}));
 3956:     }
 3957:     my @jsarray = ();
 3958:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3959:         push(@jsarray,$ordered{$item});
 3960:     }
 3961:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3962:     return <<"ENDSCRIPT";
 3963: <script type="text/javascript">
 3964: // <![CDATA[
 3965: function reorderIPaccess(form,item) {
 3966:     var changedVal;
 3967: $jstext
 3968:     var newpos = 'ipaccess_pos_add';
 3969:     var maxh = 1 + $total;
 3970:     var current = new Array;
 3971:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3972:     if (item == newpos) {
 3973:         changedVal = newitemVal;
 3974:     } else {
 3975:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3976:         current[newitemVal] = newpos;
 3977:     }
 3978:     for (var i=0; i<ipaccess.length; i++) {
 3979:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3980:         if (elementName != item) {
 3981:             if (form.elements[elementName]) {
 3982:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3983:                 current[currVal] = elementName;
 3984:             }
 3985:         }
 3986:     }
 3987:     var oldVal;
 3988:     for (var j=0; j<maxh; j++) {
 3989:         if (current[j] == undefined) {
 3990:             oldVal = j;
 3991:         }
 3992:     }
 3993:     if (oldVal < changedVal) {
 3994:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3995:            var elementName = current[k];
 3996:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3997:         }
 3998:     } else {
 3999:         for (var k=changedVal; k<oldVal; k++) {
 4000:             var elementName = current[k];
 4001:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 4002:         }
 4003:     }
 4004:     return;
 4005: }
 4006: // ]]>
 4007: </script>
 4008: 
 4009: ENDSCRIPT
 4010: }
 4011: 
 4012: sub print_autoenroll {
 4013:     my ($dom,$settings,$rowtotal) = @_;
 4014:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 4015:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 4016:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 4017:     $failsafesty = 'none';
 4018:     %failsafechecked = (
 4019:         off => ' checked="checked"',
 4020:     );
 4021:     if (ref($settings) eq 'HASH') {
 4022:         if (exists($settings->{'run'})) {
 4023:             if ($settings->{'run'} eq '0') {
 4024:                 $runoff = ' checked="checked" ';
 4025:                 $runon = ' ';
 4026:             } else {
 4027:                 $runon = ' checked="checked" ';
 4028:                 $runoff = ' ';
 4029:             }
 4030:         } else {
 4031:             if ($autorun) {
 4032:                 $runon = ' checked="checked" ';
 4033:                 $runoff = ' ';
 4034:             } else {
 4035:                 $runoff = ' checked="checked" ';
 4036:                 $runon = ' ';
 4037:             }
 4038:         }
 4039:         if (exists($settings->{'co-owners'})) {
 4040:             if ($settings->{'co-owners'} eq '0') {
 4041:                 $coownersoff = ' checked="checked" ';
 4042:                 $coownerson = ' ';
 4043:             } else {
 4044:                 $coownerson = ' checked="checked" ';
 4045:                 $coownersoff = ' ';
 4046:             }
 4047:         } else {
 4048:             $coownersoff = ' checked="checked" ';
 4049:             $coownerson = ' ';
 4050:         }
 4051:         if (exists($settings->{'sender_domain'})) {
 4052:             $defdom = $settings->{'sender_domain'};
 4053:         }
 4054:         if (exists($settings->{'failsafe'})) {
 4055:             $failsafe = $settings->{'failsafe'};
 4056:             if ($failsafe eq 'zero') {
 4057:                 $failsafechecked{'zero'} = ' checked="checked"';
 4058:                 $failsafechecked{'off'} = '';
 4059:                 $failsafesty = 'inline-block';
 4060:             } elsif ($failsafe eq 'any') {
 4061:                 $failsafechecked{'any'} = ' checked="checked"';
 4062:                 $failsafechecked{'off'} = '';
 4063:             }
 4064:             $autofailsafe = $settings->{'autofailsafe'};
 4065:         } elsif (exists($settings->{'autofailsafe'})) {
 4066:             $autofailsafe = $settings->{'autofailsafe'};
 4067:             if ($autofailsafe ne '') {
 4068:                 $failsafechecked{'zero'} = ' checked="checked"';
 4069:                 $failsafe = 'zero';
 4070:                 $failsafechecked{'off'} = '';
 4071:             }
 4072:         }
 4073:     } else {
 4074:         if ($autorun) {
 4075:             $runon = ' checked="checked" ';
 4076:             $runoff = ' ';
 4077:         } else {
 4078:             $runoff = ' checked="checked" ';
 4079:             $runon = ' ';
 4080:         }
 4081:     }
 4082:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 4083:     my $notif_sender;
 4084:     if (ref($settings) eq 'HASH') {
 4085:         $notif_sender = $settings->{'sender_uname'};
 4086:     }
 4087:     my $datatable='<tr class="LC_odd_row">'.
 4088:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 4089:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4090:                   '<input type="radio" name="autoenroll_run"'.
 4091:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4092:                   '<label><input type="radio" name="autoenroll_run"'.
 4093:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4094:                   '</tr><tr>'.
 4095:                   '<td>'.&mt('Notification messages - sender').
 4096:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 4097:                   &mt('username').':&nbsp;'.
 4098:                   '<input type="text" name="sender_uname" value="'.
 4099:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 4100:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 4101:                   '<tr class="LC_odd_row">'.
 4102:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 4103:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4104:                   '<input type="radio" name="autoassign_coowners"'.
 4105:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4106:                   '<label><input type="radio" name="autoassign_coowners"'.
 4107:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4108:                   '</tr><tr>'.
 4109:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 4110:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 4111:                   '<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; '.
 4112:                   '<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 />'.
 4113:                   '<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>'.
 4114:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 4115:                   '<span class="LC_nobreak">'.
 4116:                   &mt('Threshold for number of students in section to drop: [_1]',
 4117:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 4118:                   '</span></div></td></tr>';
 4119:     $$rowtotal += 4;
 4120:     return $datatable;
 4121: }
 4122: 
 4123: sub print_autoupdate {
 4124:     my ($position,$dom,$settings,$rowtotal) = @_;
 4125:     my ($enable,$datatable);
 4126:     if ($position eq 'top') {
 4127:         my %choices = &Apache::lonlocal::texthash (
 4128:                           run        => 'Auto-update active?',
 4129:                           classlists => 'Update information in classlists?',
 4130:                           unexpired  => 'Skip updates for users without active or future roles?',
 4131:                           lastactive => 'Skip updates for inactive users?',
 4132:         );
 4133:         my $itemcount = 0;
 4134:         my $updateon = ' ';
 4135:         my $updateoff = ' checked="checked" ';
 4136:         if (ref($settings) eq 'HASH') {
 4137:             if ($settings->{'run'} eq '1') {
 4138:                 $updateon = $updateoff;
 4139:                 $updateoff = ' ';
 4140:             }
 4141:         }
 4142:         $enable = '<tr class="LC_odd_row">'.
 4143:                   '<td>'.$choices{'run'}.'</td>'.
 4144:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4145:                   '<input type="radio" name="autoupdate_run"'.
 4146:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 4147:                   '<label><input type="radio" name="autoupdate_run"'.
 4148:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 4149:                   '</tr>';
 4150:         my @toggles = ('classlists','unexpired');
 4151:         my %defaultchecked = ('classlists' => 'off',
 4152:                               'unexpired'  => 'off'
 4153:                               );
 4154:         $$rowtotal ++;
 4155:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4156:                                                      \%choices,$itemcount,'','','left','no');
 4157:         $datatable = $enable.$datatable;
 4158:         $$rowtotal += $itemcount;
 4159:         my $lastactiveon = ' ';
 4160:         my $lastactiveoff = ' checked="checked" ';
 4161:         my $lastactivestyle = 'none';
 4162:         my $lastactivedays;
 4163:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 4164:         if (ref($settings) eq 'HASH') {
 4165:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 4166:                 $lastactiveon = $lastactiveoff;
 4167:                 $lastactiveoff = ' ';
 4168:                 $lastactivestyle = 'inline-block';
 4169:                 $lastactivedays = $settings->{'lastactive'};
 4170:             }
 4171:         }
 4172:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4173:         $datatable .= '<tr'.$css_class.'>'.
 4174:                       '<td>'.$choices{'lastactive'}.'</td>'.
 4175:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4176:                       '<input type="radio" name="lastactive"'.
 4177:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4178:                       '&nbsp;<label>'.
 4179:                       '<input type="radio" name="lastactive"'.
 4180:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 4181:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 4182:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 4183:                           '<input type="text" size="5" name="lastactivedays" value="'.
 4184:                           $lastactivedays.'" />').
 4185:                       '</span></td>'.
 4186:                       '</tr>';
 4187:         $$rowtotal ++;
 4188:     } elsif ($position eq 'middle') {
 4189:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4190:         my $numinrow = 3;
 4191:         my $locknamesettings;
 4192:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 4193:                                      $dom,$numinrow,$othertitle,
 4194:                                     'lockablenames',$rowtotal);
 4195:         $$rowtotal ++;
 4196:     } else {
 4197:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4198:         my @fields = ('lastname','firstname','middlename','generation',
 4199:                       'permanentemail','id');
 4200:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4201:         my $numrows = 0;
 4202:         if (ref($types) eq 'ARRAY') {
 4203:             if (@{$types} > 0) {
 4204:                 $datatable = 
 4205:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 4206:                                          \@fields,$types,\$numrows);
 4207:                     $$rowtotal += @{$types}; 
 4208:             }
 4209:         }
 4210:         $datatable .= 
 4211:             &usertype_update_row($settings,{'default' => $othertitle},
 4212:                                  \%fieldtitles,\@fields,['default'],
 4213:                                  \$numrows);
 4214:         $$rowtotal ++;     
 4215:     }
 4216:     return $datatable;
 4217: }
 4218: 
 4219: sub print_autocreate {
 4220:     my ($dom,$settings,$rowtotal) = @_;
 4221:     my (%createon,%createoff,%currhash);
 4222:     my @types = ('xml','req');
 4223:     if (ref($settings) eq 'HASH') {
 4224:         foreach my $item (@types) {
 4225:             $createoff{$item} = ' checked="checked" ';
 4226:             $createon{$item} = ' ';
 4227:             if (exists($settings->{$item})) {
 4228:                 if ($settings->{$item}) {
 4229:                     $createon{$item} = ' checked="checked" ';
 4230:                     $createoff{$item} = ' ';
 4231:                 }
 4232:             }
 4233:         }
 4234:         if ($settings->{'xmldc'} ne '') {
 4235:             $currhash{$settings->{'xmldc'}} = 1;
 4236:         }
 4237:     } else {
 4238:         foreach my $item (@types) {
 4239:             $createoff{$item} = ' checked="checked" ';
 4240:             $createon{$item} = ' ';
 4241:         }
 4242:     }
 4243:     $$rowtotal += 2;
 4244:     my $numinrow = 2;
 4245:     my $datatable='<tr class="LC_odd_row">'.
 4246:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 4247:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4248:                   '<input type="radio" name="autocreate_xml"'.
 4249:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4250:                   '<label><input type="radio" name="autocreate_xml"'.
 4251:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 4252:                   '</td></tr><tr>'.
 4253:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 4254:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4255:                   '<input type="radio" name="autocreate_req"'.
 4256:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4257:                   '<label><input type="radio" name="autocreate_req"'.
 4258:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 4259:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 4260:                                                    'autocreate_xmldc',%currhash);
 4261:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 4262:     if ($numdc > 1) {
 4263:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 4264:                       '</td><td class="LC_left_item">';
 4265:     } else {
 4266:         $datatable .= &mt('Course creation processed as:').
 4267:                       '</td><td class="LC_right_item">';
 4268:     }
 4269:     $datatable .= $dctable.'</td></tr>';
 4270:     $$rowtotal += $rows;
 4271:     return $datatable;
 4272: }
 4273: 
 4274: sub print_directorysrch {
 4275:     my ($position,$dom,$settings,$rowtotal) = @_;
 4276:     my $datatable;
 4277:     if ($position eq 'top') {
 4278:         my $instsrchon = ' ';
 4279:         my $instsrchoff = ' checked="checked" ';
 4280:         my ($exacton,$containson,$beginson);
 4281:         my $instlocalon = ' ';
 4282:         my $instlocaloff = ' checked="checked" ';
 4283:         if (ref($settings) eq 'HASH') {
 4284:             if ($settings->{'available'} eq '1') {
 4285:                 $instsrchon = $instsrchoff;
 4286:                 $instsrchoff = ' ';
 4287:             }
 4288:             if ($settings->{'localonly'} eq '1') {
 4289:                 $instlocalon = $instlocaloff;
 4290:                 $instlocaloff = ' ';
 4291:             }
 4292:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 4293:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 4294:                     if ($type eq 'exact') {
 4295:                         $exacton = ' checked="checked" ';
 4296:                     } elsif ($type eq 'contains') {
 4297:                         $containson = ' checked="checked" ';
 4298:                     } elsif ($type eq 'begins') {
 4299:                         $beginson = ' checked="checked" ';
 4300:                     }
 4301:                 }
 4302:             } else {
 4303:                 if ($settings->{'searchtypes'} eq 'exact') {
 4304:                     $exacton = ' checked="checked" ';
 4305:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 4306:                     $containson = ' checked="checked" ';
 4307:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 4308:                     $exacton = ' checked="checked" ';
 4309:                     $containson = ' checked="checked" ';
 4310:                 }
 4311:             }
 4312:         }
 4313:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 4314:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4315: 
 4316:         my $numinrow = 4;
 4317:         my $cansrchrow = 0;
 4318:         $datatable='<tr class="LC_odd_row">'.
 4319:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 4320:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4321:                    '<input type="radio" name="dirsrch_available"'.
 4322:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4323:                    '<label><input type="radio" name="dirsrch_available"'.
 4324:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4325:                    '</tr><tr>'.
 4326:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 4327:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4328:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 4329:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4330:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 4331:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4332:                    '</tr>';
 4333:         $$rowtotal += 2;
 4334:         if (ref($usertypes) eq 'HASH') {
 4335:             if (keys(%{$usertypes}) > 0) {
 4336:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4337:                                              $numinrow,$othertitle,'cansearch',
 4338:                                              $rowtotal);
 4339:                 $cansrchrow = 1;
 4340:             }
 4341:         }
 4342:         if ($cansrchrow) {
 4343:             $$rowtotal ++;
 4344:             $datatable .= '<tr>';
 4345:         } else {
 4346:             $datatable .= '<tr class="LC_odd_row">';
 4347:         }
 4348:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 4349:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 4350:         foreach my $title (@{$titleorder}) {
 4351:             if (defined($searchtitles->{$title})) {
 4352:                 my $check = ' ';
 4353:                 if (ref($settings) eq 'HASH') {
 4354:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 4355:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 4356:                             $check = ' checked="checked" ';
 4357:                         }
 4358:                     }
 4359:                 }
 4360:                 $datatable .= '<td class="LC_left_item">'.
 4361:                               '<span class="LC_nobreak"><label>'.
 4362:                               '<input type="checkbox" name="searchby" '.
 4363:                               'value="'.$title.'"'.$check.'/>'.
 4364:                               $searchtitles->{$title}.'</label></span></td>';
 4365:             }
 4366:         }
 4367:         $datatable .= '</tr></table></td></tr>';
 4368:         $$rowtotal ++;
 4369:         if ($cansrchrow) {
 4370:             $datatable .= '<tr class="LC_odd_row">';
 4371:         } else {
 4372:             $datatable .= '<tr>';
 4373:         }
 4374:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 4375:                       '<td class="LC_left_item" colspan="2">'.
 4376:                       '<span class="LC_nobreak"><label>'.
 4377:                       '<input type="checkbox" name="searchtypes" '.
 4378:                       $exacton.' value="exact" />'.&mt('Exact match').
 4379:                       '</label>&nbsp;'.
 4380:                       '<label><input type="checkbox" name="searchtypes" '.
 4381:                       $beginson.' value="begins" />'.&mt('Begins with').
 4382:                       '</label>&nbsp;'.
 4383:                       '<label><input type="checkbox" name="searchtypes" '.
 4384:                       $containson.' value="contains" />'.&mt('Contains').
 4385:                       '</label></span></td></tr>';
 4386:         $$rowtotal ++;
 4387:     } else {
 4388:         my $domsrchon = ' checked="checked" ';
 4389:         my $domsrchoff = ' ';
 4390:         my $domlocalon = ' ';
 4391:         my $domlocaloff = ' checked="checked" ';
 4392:         if (ref($settings) eq 'HASH') {
 4393:             if ($settings->{'lclocalonly'} eq '1') {
 4394:                 $domlocalon = $domlocaloff;
 4395:                 $domlocaloff = ' ';
 4396:             }
 4397:             if ($settings->{'lcavailable'} eq '0') {
 4398:                 $domsrchoff = $domsrchon;
 4399:                 $domsrchon = ' ';
 4400:             }
 4401:         }
 4402:         $datatable='<tr class="LC_odd_row">'.
 4403:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 4404:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4405:                       '<input type="radio" name="dirsrch_domavailable"'.
 4406:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4407:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 4408:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4409:                       '</tr><tr>'.
 4410:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 4411:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4412:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 4413:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4414:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 4415:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4416:                       '</tr>';
 4417:         $$rowtotal += 2;
 4418:     }
 4419:     return $datatable;
 4420: }
 4421: 
 4422: sub print_contacts {
 4423:     my ($position,$dom,$settings,$rowtotal) = @_;
 4424:     my $datatable;
 4425:     my @contacts = ('adminemail','supportemail');
 4426:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 4427:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 4428:     if ($position eq 'top') {
 4429:         if (ref($settings) eq 'HASH') {
 4430:             foreach my $item (@contacts) {
 4431:                 if (exists($settings->{$item})) {
 4432:                     $to{$item} = $settings->{$item};
 4433:                 }
 4434:             }
 4435:         }
 4436:     } elsif ($position eq 'middle') {
 4437:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 4438:                      'updatesmail','idconflictsmail','hostipmail');
 4439:         foreach my $type (@mailings) {
 4440:             $otheremails{$type} = '';
 4441:         }
 4442:     } elsif ($position eq 'lower') {
 4443:         if (ref($settings) eq 'HASH') {
 4444:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 4445:                 %lonstatus = %{$settings->{'lonstatus'}};
 4446:             }
 4447:         }
 4448:     } else {
 4449:         @mailings = ('helpdeskmail','otherdomsmail');
 4450:         foreach my $type (@mailings) {
 4451:             $otheremails{$type} = '';
 4452:         }
 4453:         $bccemails{'helpdeskmail'} = '';
 4454:         $bccemails{'otherdomsmail'} = '';
 4455:         $includestr{'helpdeskmail'} = '';
 4456:         $includestr{'otherdomsmail'} = '';
 4457:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 4458:     }
 4459:     if (ref($settings) eq 'HASH') {
 4460:         unless (($position eq 'top') || ($position eq 'lower')) {
 4461:             foreach my $type (@mailings) {
 4462:                 if (exists($settings->{$type})) {
 4463:                     if (ref($settings->{$type}) eq 'HASH') {
 4464:                         foreach my $item (@contacts) {
 4465:                             if ($settings->{$type}{$item}) {
 4466:                                 $checked{$type}{$item} = ' checked="checked" ';
 4467:                             }
 4468:                         }
 4469:                         $otheremails{$type} = $settings->{$type}{'others'};
 4470:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4471:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 4472:                             if ($settings->{$type}{'include'} ne '') {
 4473:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4474:                                 $includestr{$type} = &unescape($includestr{$type});
 4475:                             }
 4476:                         }
 4477:                     }
 4478:                 } elsif ($type eq 'lonstatusmail') {
 4479:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4480:                 }
 4481:             }
 4482:         }
 4483:         if ($position eq 'bottom') {
 4484:             foreach my $type (@mailings) {
 4485:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 4486:                 if ($settings->{$type}{'include'} ne '') {
 4487:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4488:                     $includestr{$type} = &unescape($includestr{$type});
 4489:                 }
 4490:             }
 4491:             if (ref($settings->{'helpform'}) eq 'HASH') {
 4492:                 if (ref($fields) eq 'ARRAY') {
 4493:                     foreach my $field (@{$fields}) {
 4494:                         $currfield{$field} = $settings->{'helpform'}{$field};
 4495:                     }
 4496:                 }
 4497:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 4498:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 4499:                 } else {
 4500:                     $maxsize = '1.0';
 4501:                 }
 4502:             } else {
 4503:                 if (ref($fields) eq 'ARRAY') {
 4504:                     foreach my $field (@{$fields}) {
 4505:                         $currfield{$field} = 'yes';
 4506:                     }
 4507:                 }
 4508:                 $maxsize = '1.0';
 4509:             }
 4510:         }
 4511:     } else {
 4512:         if ($position eq 'top') {
 4513:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 4514:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 4515:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 4516:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 4517:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4518:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 4519:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 4520:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 4521:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 4522:         } elsif ($position eq 'bottom') {
 4523:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 4524:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 4525:             if (ref($fields) eq 'ARRAY') {
 4526:                 foreach my $field (@{$fields}) {
 4527:                     $currfield{$field} = 'yes';
 4528:                 }
 4529:             }
 4530:             $maxsize = '1.0';
 4531:         }
 4532:     }
 4533:     my ($titles,$short_titles) = &contact_titles();
 4534:     my $rownum = 0;
 4535:     my $css_class;
 4536:     if ($position eq 'top') {
 4537:         foreach my $item (@contacts) {
 4538:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4539:             $datatable .= '<tr'.$css_class.'>'. 
 4540:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4541:                           '</span></td><td class="LC_right_item">'.
 4542:                           '<input type="text" name="'.$item.'" value="'.
 4543:                           $to{$item}.'" /></td></tr>';
 4544:             $rownum ++;
 4545:         }
 4546:     } elsif ($position eq 'bottom') {
 4547:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4548:         $datatable .= '<tr'.$css_class.'>'.
 4549:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4550:                       &mt('(e-mail, subject, and description always shown)').
 4551:                       '</td><td class="LC_left_item">';
 4552:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4553:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4554:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4555:             foreach my $field (@{$fields}) {
 4556:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4557:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4558:                     $datatable .= ' '.&mt('(logged-in users)');
 4559:                 }
 4560:                 $datatable .='</td><td>';
 4561:                 my $clickaction;
 4562:                 if ($field eq 'screenshot') {
 4563:                     $clickaction = ' onclick="screenshotSize(this);"';
 4564:                 }
 4565:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4566:                     foreach my $option (@{$possoptions->{$field}}) {
 4567:                         my $checked;
 4568:                         if ($currfield{$field} eq $option) {
 4569:                             $checked = ' checked="checked"';
 4570:                         }
 4571:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4572:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4573:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4574:                                       '</label></span>'.('&nbsp;'x2);
 4575:                     }
 4576:                 }
 4577:                 if ($field eq 'screenshot') {
 4578:                     my $display;
 4579:                     if ($currfield{$field} eq 'no') {
 4580:                         $display = ' style="display:none"';
 4581:                     }
 4582:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4583:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4584:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4585:                 }
 4586:                 $datatable .= '</td></tr>';
 4587:             }
 4588:             $datatable .= '</table>';
 4589:         }
 4590:         $datatable .= '</td></tr>'."\n";
 4591:         $rownum ++;
 4592:     }
 4593:     unless (($position eq 'top') || ($position eq 'lower')) {
 4594:         foreach my $type (@mailings) {
 4595:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4596:             $datatable .= '<tr'.$css_class.'>'.
 4597:                           '<td><span class="LC_nobreak">'.
 4598:                           $titles->{$type}.': </span></td>'.
 4599:                           '<td class="LC_left_item">';
 4600:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4601:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4602:             }
 4603:             $datatable .= '<span class="LC_nobreak">';
 4604:             foreach my $item (@contacts) {
 4605:                 $datatable .= '<label>'.
 4606:                               '<input type="checkbox" name="'.$type.'"'.
 4607:                               $checked{$type}{$item}.
 4608:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4609:                               '</label>&nbsp;';
 4610:             }
 4611:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4612:                           '<input type="text" name="'.$type.'_others" '.
 4613:                           'value="'.$otheremails{$type}.'"  />';
 4614:             my %locchecked;
 4615:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4616:                 foreach my $loc ('s','b') {
 4617:                     if ($includeloc{$type} eq $loc) {
 4618:                         $locchecked{$loc} = ' checked="checked"';
 4619:                         last;
 4620:                     }
 4621:                 }
 4622:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4623:                               '<input type="text" name="'.$type.'_bcc" '.
 4624:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4625:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4626:                               &mt('Text automatically added to e-mail:').' '.
 4627:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4628:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4629:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4630:                               ('&nbsp;'x2).
 4631:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4632:                               '</span></fieldset>';
 4633:             }
 4634:             $datatable .= '</td></tr>'."\n";
 4635:             $rownum ++;
 4636:         }
 4637:     }
 4638:     if ($position eq 'middle') {
 4639:         my %choices;
 4640:         my $corelink = &core_link_msu();
 4641:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4642:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4643:                                         $corelink);
 4644:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4645:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4646:         my %defaultchecked = ('reporterrors'  => 'on',
 4647:                               'reportupdates' => 'on',
 4648:                               'reportstatus'  => 'on');
 4649:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4650:                                                    \%choices,$rownum);
 4651:         $datatable .= $reports;
 4652:     } elsif ($position eq 'lower') {
 4653:         my (%current,%excluded,%weights);
 4654:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4655:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4656:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4657:         } else {
 4658:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4659:         }
 4660:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4661:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4662:         } else {
 4663:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4664:         }
 4665:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4666:             foreach my $type ('E','W','N','U') {
 4667:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4668:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4669:                 } else {
 4670:                     $weights{$type} = $defaults->{$type};
 4671:                 }
 4672:             }
 4673:         } else {
 4674:             foreach my $type ('E','W','N','U') {
 4675:                 $weights{$type} = $defaults->{$type};
 4676:             }
 4677:         }
 4678:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4679:             if (@{$lonstatus{'excluded'}} > 0) {
 4680:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4681:             }
 4682:         }
 4683:         foreach my $item ('errorthreshold','errorsysmail') { 
 4684:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4685:             $datatable .= '<tr'.$css_class.'>'.
 4686:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4687:                           $titles->{$item}.
 4688:                           '</span></td><td class="LC_left_item">'.
 4689:                           '<input type="text" name="'.$item.'" value="'.
 4690:                           $current{$item}.'" size="5" /></td></tr>';
 4691:             $rownum ++;
 4692:         }
 4693:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4694:         $datatable .= '<tr'.$css_class.'>'.
 4695:                       '<td class="LC_left_item">'.
 4696:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4697:                       '</span></td><td class="LC_left_item"><table><tr>';
 4698:         foreach my $type ('E','W','N','U') {
 4699:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4700:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4701:                           $weights{$type}.'" size="5" /></td>';
 4702:         }
 4703:         $datatable .= '</tr></table></tr>';
 4704:         $rownum ++;
 4705:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4706:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4707:                       $titles->{'errorexcluded'}.'</td>'.
 4708:                       '<td class="LC_left_item"><table>';
 4709:         my $numinrow = 4;
 4710:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4711:         for (my $i=0; $i<@ids; $i++) {
 4712:             my $rem = $i%($numinrow);
 4713:             if ($rem == 0) {
 4714:                 if ($i > 0) {
 4715:                     $datatable .= '</tr>';
 4716:                 }
 4717:                 $datatable .= '<tr>';
 4718:             }
 4719:             my $check;
 4720:             if ($excluded{$ids[$i]}) {
 4721:                 $check = ' checked="checked" ';
 4722:             }
 4723:             $datatable .= '<td class="LC_left_item">'.
 4724:                           '<span class="LC_nobreak"><label>'.
 4725:                           '<input type="checkbox" name="errorexcluded" '.
 4726:                           'value="'.$ids[$i].'"'.$check.' />'.
 4727:                           $ids[$i].'</label></span></td>';
 4728:         }
 4729:         my $colsleft = $numinrow - @ids%($numinrow);
 4730:         if ($colsleft > 1 ) {
 4731:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4732:                           '&nbsp;</td>';
 4733:         } elsif ($colsleft == 1) {
 4734:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4735:         }
 4736:         $datatable .= '</tr></table></td></tr>';
 4737:         $rownum ++;
 4738:     } elsif ($position eq 'bottom') {
 4739:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4740:         my (@posstypes,%usertypeshash);
 4741:         if (ref($types) eq 'ARRAY') {
 4742:             @posstypes = @{$types};
 4743:         }
 4744:         if (@posstypes) {
 4745:             if (ref($usertypes) eq 'HASH') {
 4746:                 %usertypeshash = %{$usertypes};
 4747:             }
 4748:             my @overridden;
 4749:             my $numinrow = 4;
 4750:             if (ref($settings) eq 'HASH') {
 4751:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4752:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4753:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4754:                             push(@overridden,$key);
 4755:                             foreach my $item (@contacts) {
 4756:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4757:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4758:                                 }
 4759:                             }
 4760:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4761:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4762:                             $includeloc{'override_'.$key} = '';
 4763:                             $includestr{'override_'.$key} = '';
 4764:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4765:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 4766:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4767:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4768:                             }
 4769:                         }
 4770:                     }
 4771:                 }
 4772:             }
 4773:             my $customclass = 'LC_helpdesk_override';
 4774:             my $optionsprefix = 'LC_options_helpdesk_';
 4775: 
 4776:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4777:  
 4778:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4779:                                          $numinrow,$othertitle,'overrides',
 4780:                                          \$rownum,$onclicktypes,$customclass);
 4781:             $rownum ++;
 4782:             $usertypeshash{'default'} = $othertitle;
 4783:             foreach my $status (@posstypes) {
 4784:                 my $css_class;
 4785:                 if ($rownum%2) {
 4786:                     $css_class = 'LC_odd_row ';
 4787:                 }
 4788:                 $css_class .= $customclass;
 4789:                 my $rowid = $optionsprefix.$status;
 4790:                 my $hidden = 1;
 4791:                 my $currstyle = 'display:none';
 4792:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4793:                     $currstyle = 'display:table-row';
 4794:                     $hidden = 0;
 4795:                 }
 4796:                 my $key = 'override_'.$status;
 4797:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4798:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4799:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4800:                                                   \@contacts,$short_titles);
 4801:                 unless ($hidden) {
 4802:                     $rownum ++;
 4803:                 }
 4804:             }
 4805:         }
 4806:     }
 4807:     $$rowtotal += $rownum;
 4808:     return $datatable;
 4809: }
 4810: 
 4811: sub core_link_msu {
 4812:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4813:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4814: }
 4815: 
 4816: sub overridden_helpdesk {
 4817:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4818:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4819:     my $class = 'LC_left_item';
 4820:     if ($css_class) {
 4821:         $css_class = ' class="'.$css_class.'"';
 4822:     }
 4823:     if ($rowid) {
 4824:         $rowid = ' id="'.$rowid.'"';
 4825:     }
 4826:     if ($rowstyle) {
 4827:         $rowstyle = ' style="'.$rowstyle.'"';
 4828:     }
 4829:     my ($output,$description);
 4830:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4831:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4832:               "<td>$description</td>\n".
 4833:               '<td class="'.$class.'" colspan="2">'.
 4834:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4835:               '<span class="LC_nobreak">';
 4836:     if (ref($contacts) eq 'ARRAY') {
 4837:         foreach my $item (@{$contacts}) {
 4838:             my $check;
 4839:             if (ref($checked) eq 'HASH') {
 4840:                $check = $checked->{$item};
 4841:             }
 4842:             my $title;
 4843:             if (ref($short_titles) eq 'HASH') {
 4844:                 $title = $short_titles->{$item}; 
 4845:             }
 4846:             $output .= '<label>'.
 4847:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4848:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4849:         }
 4850:     }
 4851:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4852:                '<input type="text" name="override_'.$type.'_others" '.
 4853:                'value="'.$otheremails.'"  />';
 4854:     my %locchecked;
 4855:     foreach my $loc ('s','b') {
 4856:         if ($includeloc eq $loc) {
 4857:             $locchecked{$loc} = ' checked="checked"';
 4858:             last;
 4859:         }
 4860:     }
 4861:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4862:                '<input type="text" name="override_'.$type.'_bcc" '.
 4863:                'value="'.$bccemails.'"  /></fieldset>'.
 4864:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4865:                &mt('Text automatically added to e-mail:').' '.
 4866:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4867:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4868:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4869:                ('&nbsp;'x2).
 4870:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4871:                '</span></fieldset>'.
 4872:                '</td></tr>'."\n";
 4873:     return $output;
 4874: }
 4875: 
 4876: sub contacts_javascript {
 4877:     return <<"ENDSCRIPT";
 4878: 
 4879: <script type="text/javascript">
 4880: // <![CDATA[
 4881: 
 4882: function screenshotSize(field) {
 4883:     if (document.getElementById('help_screenshotsize')) {
 4884:         if (field.value == 'no') {
 4885:             document.getElementById('help_screenshotsize').style.display="none";
 4886:         } else {
 4887:             document.getElementById('help_screenshotsize').style.display="";
 4888:         }
 4889:     }
 4890:     return;
 4891: }
 4892: 
 4893: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4894:     if (form.elements[checkbox].length != undefined) {
 4895:         var count = 0;
 4896:         if (docount) {
 4897:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4898:                 if (form.elements[checkbox][i].checked) {
 4899:                     count ++;
 4900:                 }
 4901:             }
 4902:         }
 4903:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4904:             var type = form.elements[checkbox][i].value;
 4905:             if (document.getElementById(prefix+type)) {
 4906:                 if (form.elements[checkbox][i].checked) {
 4907:                     document.getElementById(prefix+type).style.display = 'table-row';
 4908:                     if (count % 2 == 1) {
 4909:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4910:                     } else {
 4911:                         document.getElementById(prefix+type).className = target;
 4912:                     }
 4913:                     count ++;
 4914:                 } else {
 4915:                     document.getElementById(prefix+type).style.display = 'none';
 4916:                 }
 4917:             }
 4918:         }
 4919:     }
 4920:     return;
 4921: }
 4922: 
 4923: 
 4924: // ]]>
 4925: </script>
 4926: 
 4927: ENDSCRIPT
 4928: }
 4929: 
 4930: sub print_helpsettings {
 4931:     my ($position,$dom,$settings,$rowtotal) = @_;
 4932:     my $confname = $dom.'-domainconfig';
 4933:     my $formname = 'display';
 4934:     my ($datatable,$itemcount);
 4935:     if ($position eq 'top') {
 4936:         $itemcount = 1;
 4937:         my (%choices,%defaultchecked,@toggles);
 4938:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4939:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4940:                                      &mt('LON-CAPA bug tracker'),600,500));
 4941:         %defaultchecked = ('submitbugs' => 'on');
 4942:         @toggles = ('submitbugs');
 4943:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4944:                                                      \%choices,$itemcount);
 4945:         $$rowtotal ++;
 4946:     } else {
 4947:         my $css_class;
 4948:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4949:         my (%customroles,%ordered,%current);
 4950:         if (ref($settings) eq 'HASH') {
 4951:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4952:                 %current = %{$settings->{'adhoc'}};
 4953:             }
 4954:         }
 4955:         my $count = 0;
 4956:         foreach my $key (sort(keys(%existing))) {
 4957:             if ($key=~/^rolesdef\_(\w+)$/) {
 4958:                 my $rolename = $1;
 4959:                 my (%privs,$order);
 4960:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4961:                 $customroles{$rolename} = \%privs;
 4962:                 if (ref($current{$rolename}) eq 'HASH') {
 4963:                     $order = $current{$rolename}{'order'};
 4964:                 }
 4965:                 if ($order eq '') {
 4966:                     $order = $count;
 4967:                 }
 4968:                 $ordered{$order} = $rolename;
 4969:                 $count++;
 4970:             }
 4971:         }
 4972:         my $maxnum = scalar(keys(%ordered));
 4973:         my @roles_by_num = ();
 4974:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4975:             push(@roles_by_num,$item);
 4976:         }
 4977:         my $context = 'domprefs';
 4978:         my $crstype = 'Course';
 4979:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4980:         my @accesstypes = ('all','dh','da','none');
 4981:         my ($numstatustypes,@jsarray);
 4982:         if (ref($types) eq 'ARRAY') {
 4983:             if (@{$types} > 0) {
 4984:                 $numstatustypes = scalar(@{$types});
 4985:                 push(@accesstypes,'status');
 4986:                 @jsarray = ('bystatus');
 4987:             }
 4988:         }
 4989:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4990:         if (keys(%domhelpdesk)) {
 4991:             push(@accesstypes,('inc','exc'));
 4992:             push(@jsarray,('notinc','notexc'));
 4993:         }
 4994:         my $hiddenstr = join("','",@jsarray);
 4995:         my $context = 'domprefs';
 4996:         my $crstype = 'Course';
 4997:         my $prefix = 'helproles_';
 4998:         my $add_class = 'LC_hidden';
 4999:         foreach my $num (@roles_by_num) {
 5000:             my $role = $ordered{$num};
 5001:             my ($desc,$access,@statuses);
 5002:             if (ref($current{$role}) eq 'HASH') {
 5003:                 $desc = $current{$role}{'desc'};
 5004:                 $access = $current{$role}{'access'};
 5005:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 5006:                     @statuses = @{$current{$role}{'insttypes'}};
 5007:                 }
 5008:             }
 5009:             if ($desc eq '') {
 5010:                 $desc = $role;
 5011:             }
 5012:             my $identifier = 'custhelp'.$num;
 5013:             my %full=();
 5014:             my %levels= (
 5015:                          course => {},
 5016:                          domain => {},
 5017:                          system => {},
 5018:                         );
 5019:             my %levelscurrent=(
 5020:                                course => {},
 5021:                                domain => {},
 5022:                                system => {},
 5023:                               );
 5024:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 5025:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5026:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5027:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 5028:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 5029:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 5030:             for (my $k=0; $k<=$maxnum; $k++) {
 5031:                 my $vpos = $k+1;
 5032:                 my $selstr;
 5033:                 if ($k == $num) {
 5034:                     $selstr = ' selected="selected" ';
 5035:                 }
 5036:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5037:             }
 5038:             $datatable .= '</select>'.('&nbsp;'x2).
 5039:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 5040:                           '</td>'.
 5041:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5042:                           &mt('Name shown to users:').
 5043:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 5044:                           '</fieldset>'.
 5045:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 5046:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 5047:                           '<fieldset>'.
 5048:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 5049:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5050:                                                                    \%levelscurrent,$identifier,
 5051:                                                                    'LC_hidden',$prefix.$num.'_privs').
 5052:                           '</fieldset></td>';
 5053:             $itemcount ++;
 5054:         }
 5055:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5056:         my $newcust = 'custhelp'.$count;
 5057:         my (%privs,%levelscurrent);
 5058:         my %full=();
 5059:         my %levels= (
 5060:                      course => {},
 5061:                      domain => {},
 5062:                      system => {},
 5063:                     );
 5064:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5065:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5066:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 5067:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 5068:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 5069:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 5070:         for (my $k=0; $k<$maxnum+1; $k++) {
 5071:             my $vpos = $k+1;
 5072:             my $selstr;
 5073:             if ($k == $maxnum) {
 5074:                 $selstr = ' selected="selected" ';
 5075:             }
 5076:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5077:         }
 5078:         $datatable .= '</select>&nbsp;'."\n".
 5079:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 5080:                       '</label></span></td>'.
 5081:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5082:                       '<span class="LC_nobreak">'.
 5083:                       &mt('Internal name:').
 5084:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 5085:                       '</span>'.('&nbsp;'x4).
 5086:                       '<span class="LC_nobreak">'.
 5087:                       &mt('Name shown to users:').
 5088:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 5089:                       '</span></fieldset>'.
 5090:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 5091:                                              $usertypes,$types,\%domhelpdesk).
 5092:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 5093:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 5094:                                                                 \@templateroles,$newcust).
 5095:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 5096:                                                                \%levelscurrent,$newcust).
 5097:                       '</fieldset>'.
 5098:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 5099:                       '</td></tr>';
 5100:         $count ++;
 5101:         $$rowtotal += $count;
 5102:     }
 5103:     return $datatable;
 5104: }
 5105: 
 5106: sub adhocbutton {
 5107:     my ($prefix,$num,$field,$visibility) = @_;
 5108:     my %lt = &Apache::lonlocal::texthash(
 5109:                                           show => 'Show details',
 5110:                                           hide => 'Hide details',
 5111:                                         );
 5112:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 5113:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 5114:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 5115:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 5116: }
 5117: 
 5118: sub helpsettings_javascript {
 5119:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 5120:     return unless(ref($roles_by_num) eq 'ARRAY');
 5121:     my %html_js_lt = &Apache::lonlocal::texthash(
 5122:                                           show => 'Show details',
 5123:                                           hide => 'Hide details',
 5124:                                         );
 5125:     &html_escape(\%html_js_lt);
 5126:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 5127:     return <<"ENDSCRIPT";
 5128: <script type="text/javascript">
 5129: // <![CDATA[
 5130: 
 5131: function reorderHelpRoles(form,item) {
 5132:     var changedVal;
 5133: $jstext
 5134:     var newpos = 'helproles_${total}_pos';
 5135:     var maxh = 1 + $total;
 5136:     var current = new Array();
 5137:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5138:     if (item == newpos) {
 5139:         changedVal = newitemVal;
 5140:     } else {
 5141:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 5142:         current[newitemVal] = newpos;
 5143:     }
 5144:     for (var i=0; i<helproles.length; i++) {
 5145:         var elementName = 'helproles_'+helproles[i]+'_pos';
 5146:         if (elementName != item) {
 5147:             if (form.elements[elementName]) {
 5148:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 5149:                 current[currVal] = elementName;
 5150:             }
 5151:         }
 5152:     }
 5153:     var oldVal;
 5154:     for (var j=0; j<maxh; j++) {
 5155:         if (current[j] == undefined) {
 5156:             oldVal = j;
 5157:         }
 5158:     }
 5159:     if (oldVal < changedVal) {
 5160:         for (var k=oldVal+1; k<=changedVal ; k++) {
 5161:            var elementName = current[k];
 5162:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 5163:         }
 5164:     } else {
 5165:         for (var k=changedVal; k<oldVal; k++) {
 5166:             var elementName = current[k];
 5167:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 5168:         }
 5169:     }
 5170:     return;
 5171: }
 5172: 
 5173: function helpdeskAccess(num) {
 5174:     var curraccess = null;
 5175:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 5176:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 5177:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 5178:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 5179:             }
 5180:         }
 5181:     }
 5182:     var shown = Array();
 5183:     var hidden = Array();
 5184:     if (curraccess == 'none') {
 5185:         hidden = Array('$hiddenstr');
 5186:     } else {
 5187:         if (curraccess == 'status') {
 5188:             shown = Array('bystatus');
 5189:             hidden = Array('notinc','notexc');
 5190:         } else {
 5191:             if (curraccess == 'exc') {
 5192:                 shown = Array('notexc');
 5193:                 hidden = Array('notinc','bystatus');
 5194:             }
 5195:             if (curraccess == 'inc') {
 5196:                 shown = Array('notinc');
 5197:                 hidden = Array('notexc','bystatus');
 5198:             }
 5199:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 5200:                 hidden = Array('notinc','notexc','bystatus');
 5201:             }
 5202:         }
 5203:     }
 5204:     if (hidden.length > 0) {
 5205:         for (var i=0; i<hidden.length; i++) {
 5206:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 5207:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 5208:             }
 5209:         }
 5210:     }
 5211:     if (shown.length > 0) {
 5212:         for (var i=0; i<shown.length; i++) {
 5213:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 5214:                 if (shown[i] == 'privs') {
 5215:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 5216:                 } else {
 5217:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 5218:                 }
 5219:             }
 5220:         }
 5221:     }
 5222:     return;
 5223: }
 5224: 
 5225: function toggleHelpdeskItem(num,field) {
 5226:     if (document.getElementById('helproles_'+num+'_'+field)) {
 5227:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 5228:             document.getElementById('helproles_'+num+'_'+field).className =
 5229:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 5230:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5231:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 5232:             }
 5233:         } else {
 5234:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 5235:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5236:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 5237:             }
 5238:         }
 5239:     }
 5240:     return;
 5241: }
 5242: 
 5243: // ]]>
 5244: </script>
 5245: 
 5246: ENDSCRIPT
 5247: }
 5248: 
 5249: sub helpdeskroles_access {
 5250:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 5251:         $usertypes,$types,$domhelpdesk) = @_;
 5252:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 5253:     my %lt = &Apache::lonlocal::texthash(
 5254:                     'rou'    => 'Role usage',
 5255:                     'whi'    => 'Which helpdesk personnel may use this role?',
 5256:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 5257:                     'dh'     => 'All with domain helpdesk role',
 5258:                     'da'     => 'All with domain helpdesk assistant role',
 5259:                     'none'   => 'None',
 5260:                     'status' => 'Determined based on institutional status',
 5261:                     'inc'    => 'Include all, but exclude specific personnel',
 5262:                     'exc'    => 'Exclude all, but include specific personnel',
 5263:                   );
 5264:     my %usecheck = (
 5265:                      all => ' checked="checked"',
 5266:                    );
 5267:     my %displaydiv = (
 5268:                       status => 'none',
 5269:                       inc    => 'none',
 5270:                       exc    => 'none',
 5271:                       priv   => 'block',
 5272:                      );
 5273:     my $output;
 5274:     if (ref($current) eq 'HASH') {
 5275:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 5276:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 5277:                 $usecheck{$current->{access}} = $usecheck{'all'};
 5278:                 delete($usecheck{'all'});
 5279:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 5280:                     my $access = $1;
 5281:                     $displaydiv{$access} = 'inline';
 5282:                 } elsif ($current->{access} eq 'none') {
 5283:                     $displaydiv{'priv'} = 'none';
 5284:                 }
 5285:             }
 5286:         }
 5287:     }
 5288:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 5289:               '<p>'.$lt{'whi'}.'</p>';
 5290:     foreach my $access (@{$accesstypes}) {
 5291:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 5292:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 5293:                    $lt{$access}.'</label>';
 5294:         if ($access eq 'status') {
 5295:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 5296:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 5297:                                                                  $othertitle,$usertypes,$types).
 5298:                        '</div>';
 5299:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 5300:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 5301:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5302:                        '</div>';
 5303:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 5304:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 5305:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5306:                        '</div>';
 5307:         }
 5308:         $output .= '</p>';
 5309:     }
 5310:     $output .= '</fieldset>';
 5311:     return $output;
 5312: }
 5313: 
 5314: sub radiobutton_prefs {
 5315:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 5316:         $additional,$align,$firstval) = @_;
 5317:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 5318:                    (ref($choices) eq 'HASH'));
 5319: 
 5320:     my (%checkedon,%checkedoff,$datatable,$css_class);
 5321: 
 5322:     foreach my $item (@{$toggles}) {
 5323:         if ($defaultchecked->{$item} eq 'on') {
 5324:             $checkedon{$item} = ' checked="checked" ';
 5325:             $checkedoff{$item} = ' ';
 5326:         } elsif ($defaultchecked->{$item} eq 'off') {
 5327:             $checkedoff{$item} = ' checked="checked" ';
 5328:             $checkedon{$item} = ' ';
 5329:         }
 5330:     }
 5331:     if (ref($settings) eq 'HASH') {
 5332:         foreach my $item (@{$toggles}) {
 5333:             if ($settings->{$item} eq '1') {
 5334:                 $checkedon{$item} =  ' checked="checked" ';
 5335:                 $checkedoff{$item} = ' ';
 5336:             } elsif ($settings->{$item} eq '0') {
 5337:                 $checkedoff{$item} =  ' checked="checked" ';
 5338:                 $checkedon{$item} = ' ';
 5339:             }
 5340:         }
 5341:     }
 5342:     if ($onclick) {
 5343:         $onclick = ' onclick="'.$onclick.'"';
 5344:     }
 5345:     foreach my $item (@{$toggles}) {
 5346:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5347:         $datatable .=
 5348:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5349:             '<span class="LC_nobreak">'.$choices->{$item}.
 5350:             '</span></td>';
 5351:         if ($align eq 'left') {
 5352:             $datatable .= '<td class="LC_left_item">';
 5353:         } else {
 5354:             $datatable .= '<td class="LC_right_item">';
 5355:         }
 5356:         $datatable .= '<span class="LC_nobreak">';
 5357:         if ($firstval eq 'no') {
 5358:             $datatable .=
 5359:                 '<label><input type="radio" name="'.
 5360:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 5361:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5362:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 5363:         } else {
 5364:             $datatable .=
 5365:                 '<label><input type="radio" name="'.
 5366:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 5367:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5368:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 5369:         }
 5370:         $datatable .= '</span>'.$additional.'</td></tr>';
 5371:         $itemcount ++;
 5372:     }
 5373:     return ($datatable,$itemcount);
 5374: }
 5375: 
 5376: sub print_ltitools {
 5377:     my ($dom,$settings,$rowtotal) = @_;
 5378:     my $rownum = 0;
 5379:     my $css_class;
 5380:     my $itemcount = 1;
 5381:     my $maxnum = 0;
 5382:     my %ordered;
 5383:     if (ref($settings) eq 'HASH') {
 5384:         foreach my $item (keys(%{$settings})) {
 5385:             if (ref($settings->{$item}) eq 'HASH') {
 5386:                 my $num = $settings->{$item}{'order'};
 5387:                 $ordered{$num} = $item;
 5388:             }
 5389:         }
 5390:     }
 5391:     my $confname = $dom.'-domainconfig';
 5392:     my $switchserver = &check_switchserver($dom,$confname);
 5393:     my $maxnum = scalar(keys(%ordered));
 5394:     my $datatable;
 5395:     my %lt = &ltitools_names();
 5396:     my @courseroles = ('cc','in','ta','ep','st');
 5397:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 5398:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 5399:     if (keys(%ordered)) {
 5400:         my @items = sort { $a <=> $b } keys(%ordered);
 5401:         for (my $i=0; $i<@items; $i++) {
 5402:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5403:             my $item = $ordered{$items[$i]};
 5404:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 5405:             if (ref($settings->{$item}) eq 'HASH') {
 5406:                 $title = $settings->{$item}->{'title'};
 5407:                 $url = $settings->{$item}->{'url'};
 5408:                 $key = $settings->{$item}->{'key'};
 5409:                 $secret = $settings->{$item}->{'secret'};
 5410:                 $lifetime = $settings->{$item}->{'lifetime'};
 5411:                 my $image = $settings->{$item}->{'image'};
 5412:                 if ($image ne '') {
 5413:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 5414:                 }
 5415:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 5416:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 5417:                 } else {
 5418:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 5419:                 }
 5420:             }
 5421:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 5422:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5423:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 5424:             for (my $k=0; $k<=$maxnum; $k++) {
 5425:                 my $vpos = $k+1;
 5426:                 my $selstr;
 5427:                 if ($k == $i) {
 5428:                     $selstr = ' selected="selected" ';
 5429:                 }
 5430:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5431:             }
 5432:             $datatable .= '</select>'.('&nbsp;'x2).
 5433:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 5434:                 &mt('Delete?').'</label></span></td>'.
 5435:                 '<td colspan="2">'.
 5436:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5437:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 5438:                 ('&nbsp;'x2).
 5439:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 5440:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5441:                 ('&nbsp;'x2).
 5442:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 5443:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5444:                 ('&nbsp;'x2).
 5445:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 5446:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 5447:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 5448:                 '<br /><br />'.
 5449:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 5450:                 ' value="'.$url.'" /></span>'.
 5451:                 ('&nbsp;'x2).
 5452:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 5453:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 5454:                 ('&nbsp;'x2).
 5455:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 5456:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 5457:                 ('&nbsp;'x2).
 5458:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 5459:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 5460:                 '<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>'.
 5461:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 5462:                 '</fieldset>'.
 5463:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5464:                 '<span class="LC_nobreak">'.&mt('Display target:');
 5465:             my %currdisp;
 5466:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 5467:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 5468:                     $currdisp{'window'} = ' checked="checked"';
 5469:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 5470:                     $currdisp{'tab'} = ' checked="checked"';
 5471:                 } else {
 5472:                     $currdisp{'iframe'} = ' checked="checked"';
 5473:                 }
 5474:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 5475:                     $currdisp{'width'} = $1;
 5476:                 }
 5477:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 5478:                      $currdisp{'height'} = $1;
 5479:                 }
 5480:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 5481:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 5482:             } else {
 5483:                 $currdisp{'iframe'} = ' checked="checked"';
 5484:             }
 5485:             foreach my $disp ('iframe','tab','window') {
 5486:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 5487:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 5488:             }
 5489:             $datatable .= ('&nbsp;'x4);
 5490:             foreach my $dimen ('width','height') {
 5491:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5492:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 5493:                               ('&nbsp;'x2);
 5494:             }
 5495:             $datatable .= '</span><br />'.
 5496:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5497:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 5498:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5499:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 5500:                           '</textarea></div><div style=""></div><br />';
 5501:             my %units = (
 5502:                           'passback' => 'days',
 5503:                           'roster'   => 'seconds',
 5504:                         );
 5505:             foreach my $extra ('passback','roster') {
 5506:                 my $validsty = 'none';
 5507:                 my $currvalid;
 5508:                 my $checkedon = '';
 5509:                 my $checkedoff = ' checked="checked"';
 5510:                 if ($settings->{$item}->{$extra}) {
 5511:                     $checkedon = $checkedoff;
 5512:                     $checkedoff = '';
 5513:                     $validsty = 'inline-block';
 5514:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 5515:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 5516:                     }
 5517:                 }
 5518:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 5519:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5520:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 5521:                               &mt('No').'</label>'.('&nbsp;'x2).
 5522:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 5523:                               &mt('Yes').'</label></span></div>'.
 5524:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 5525:                               '<span class="LC_nobreak">'.
 5526:                               &mt("at least [_1] $units{$extra} after launch",
 5527:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 5528:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5529:             }
 5530:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5531:             if ($imgsrc) {
 5532:                 $datatable .= $imgsrc.
 5533:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 5534:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 5535:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 5536:             } else {
 5537:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5538:             }
 5539:             if ($switchserver) {
 5540:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5541:             } else {
 5542:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 5543:             }
 5544:             $datatable .= '</span></fieldset>';
 5545:             my (%checkedfields,%rolemaps,$userincdom);
 5546:             if (ref($settings->{$item}) eq 'HASH') {
 5547:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 5548:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 5549:                 }
 5550:                 $userincdom = $settings->{$item}->{'incdom'};
 5551:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 5552:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 5553:                     $checkedfields{'roles'} = 1;
 5554:                 }
 5555:             }
 5556:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5557:                           '<span class="LC_nobreak">';
 5558:             my $userfieldstyle = 'display:none;';
 5559:             my $seluserdom = '';
 5560:             my $unseluserdom = ' selected="selected"';
 5561:             foreach my $field (@fields) {
 5562:                 my ($checked,$onclick,$id,$spacer);
 5563:                 if ($checkedfields{$field}) {
 5564:                     $checked = ' checked="checked"';
 5565:                 }
 5566:                 if ($field eq 'user') {
 5567:                     $id = ' id="ltitools_user_field_'.$i.'"';
 5568:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 5569:                     if ($checked) {
 5570:                         $userfieldstyle = 'display:inline-block';
 5571:                         if ($userincdom) {
 5572:                             $seluserdom = $unseluserdom;
 5573:                             $unseluserdom = '';
 5574:                         }
 5575:                     }
 5576:                 } else {
 5577:                     $spacer = ('&nbsp;' x2);
 5578:                 }
 5579:                 $datatable .= '<label>'.
 5580:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 5581:                               $lt{$field}.'</label>'.$spacer;
 5582:             }
 5583:             $datatable .= '</span>';
 5584:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 5585:                           '<span class="LC_nobreak"> : '.
 5586:                           '<select name="ltitools_userincdom_'.$i.'">'.
 5587:                           '<option value="">'.&mt('Select').'</option>'.
 5588:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 5589:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 5590:                           '</select></span></div>';
 5591:             $datatable .= '</fieldset>'.
 5592:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5593:             foreach my $role (@courseroles) {
 5594:                 my ($selected,$selectnone);
 5595:                 if (!$rolemaps{$role}) {
 5596:                     $selectnone = ' selected="selected"';
 5597:                 }
 5598:                 $datatable .= '<td style="text-align: center">'. 
 5599:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5600:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 5601:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5602:                 foreach my $ltirole (@ltiroles) {
 5603:                     unless ($selectnone) {
 5604:                         if ($rolemaps{$role} eq $ltirole) {
 5605:                             $selected = ' selected="selected"';
 5606:                         } else {
 5607:                             $selected = '';
 5608:                         }
 5609:                     }
 5610:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5611:                 }
 5612:                 $datatable .= '</select></td>';
 5613:             }
 5614:             $datatable .= '</tr></table></fieldset>';
 5615:             my %courseconfig;
 5616:             if (ref($settings->{$item}) eq 'HASH') {
 5617:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 5618:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 5619:                 }
 5620:             }
 5621:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5622:             foreach my $item ('label','title','target','linktext','explanation','append') {
 5623:                 my $checked;
 5624:                 if ($courseconfig{$item}) {
 5625:                     $checked = ' checked="checked"';
 5626:                 }
 5627:                 $datatable .= '<label>'.
 5628:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 5629:                        $lt{'crs'.$item}.'</label>&nbsp; '."\n";
 5630:             }
 5631:             $datatable .= '</span></fieldset>'.
 5632:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5633:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 5634:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 5635:                 my %custom = %{$settings->{$item}->{'custom'}};
 5636:                 if (keys(%custom) > 0) {
 5637:                     foreach my $key (sort(keys(%custom))) {
 5638:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 5639:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 5640:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5641:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 5642:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 5643:                     }
 5644:                 }
 5645:             }
 5646:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 5647:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 5648:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 5649:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 5650:             $datatable .= '</table></fieldset></td></tr>'."\n";
 5651:             $itemcount ++;
 5652:         }
 5653:     }
 5654:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5655:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 5656:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5657:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 5658:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 5659:     for (my $k=0; $k<$maxnum+1; $k++) {
 5660:         my $vpos = $k+1;
 5661:         my $selstr;
 5662:         if ($k == $maxnum) {
 5663:             $selstr = ' selected="selected" ';
 5664:         }
 5665:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5666:     }
 5667:     $datatable .= '</select>&nbsp;'."\n".
 5668:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5669:                   '<td colspan="2">'.
 5670:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5671:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 5672:                   ('&nbsp;'x2).
 5673:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 5674:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5675:                   ('&nbsp;'x2).
 5676:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 5677:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5678:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 5679:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5680:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5681:                   '<br />'.
 5682:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 5683:                   ('&nbsp;'x2).
 5684:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 5685:                   ('&nbsp;'x2).
 5686:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 5687:                   ('&nbsp;'x2).
 5688:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 5689:                   '<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".
 5690:                   '</fieldset>'.
 5691:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5692:                   '<span class="LC_nobreak">'.&mt('Display target:');
 5693:     my %defaultdisp;
 5694:     $defaultdisp{'iframe'} = ' checked="checked"';
 5695:     foreach my $disp ('iframe','tab','window') {
 5696:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 5697:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 5698:     }
 5699:     $datatable .= ('&nbsp;'x4);
 5700:     foreach my $dimen ('width','height') {
 5701:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5702:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 5703:                       ('&nbsp;'x2);
 5704:     }
 5705:     $datatable .= '</span><br />'.
 5706:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5707:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 5708:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5709:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 5710:                   '</div><div style=""></div><br />';
 5711:     my %units = (
 5712:                   'passback' => 'days',
 5713:                   'roster'   => 'seconds',
 5714:                 );
 5715:     my %defaulttimes = (
 5716:                      'passback' => '7',
 5717:                      'roster'   => '300',
 5718:                    );
 5719:     foreach my $extra ('passback','roster') {
 5720:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 5721:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5722:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 5723:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 5724:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 5725:                       &mt('Yes').'</label></span></div>'.
 5726:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 5727:                       '<span class="LC_nobreak">'.
 5728:                       &mt("at least [_1] $units{$extra} after launch",
 5729:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 5730:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5731:     }
 5732:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 5733:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5734:     if ($switchserver) {
 5735:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5736:     } else {
 5737:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 5738:     }
 5739:     $datatable .= '</span></fieldset>'.
 5740:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5741:                   '<span class="LC_nobreak">';
 5742:     foreach my $field (@fields) {
 5743:         my ($id,$onclick,$spacer);
 5744:         if ($field eq 'user') {
 5745:             $id = ' id="ltitools_user_field_add"';
 5746:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 5747:         } else {
 5748:             $spacer = ('&nbsp;' x2);
 5749:         }
 5750:         $datatable .= '<label>'.
 5751:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 5752:                       $lt{$field}.'</label>'.$spacer;
 5753:     }
 5754:     $datatable .= '</span>'.
 5755:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 5756:                   '<span class="LC_nobreak"> : '.
 5757:                   '<select name="ltitools_userincdom_add">'.
 5758:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5759:                   '<option value="0">'.&mt('username').'</option>'.
 5760:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5761:                   '</select></span></div></fieldset>';
 5762:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5763:     foreach my $role (@courseroles) {
 5764:         my ($checked,$checkednone);
 5765:         $datatable .= '<td style="text-align: center">'.
 5766:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5767:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5768:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5769:         foreach my $ltirole (@ltiroles) {
 5770:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5771:         }
 5772:         $datatable .= '</select></td>';
 5773:     }
 5774:     $datatable .= '</tr></table></fieldset>'.
 5775:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5776:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5777:         $datatable .= '<label>'.
 5778:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5779:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5780:     }
 5781:     $datatable .= '</span></fieldset>'.
 5782:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5783:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5784:                   '<tr><td><span class="LC_nobreak">'.
 5785:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5786:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5787:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5788:                   '</table></fieldset>'."\n".
 5789:                   '</td>'."\n".
 5790:                   '</tr>'."\n";
 5791:     $itemcount ++;
 5792:     return $datatable;
 5793: }
 5794: 
 5795: sub ltitools_names {
 5796:     my %lt = &Apache::lonlocal::texthash(
 5797:                                           'title'          => 'Title',
 5798:                                           'version'        => 'Version',
 5799:                                           'msgtype'        => 'Message Type',
 5800:                                           'sigmethod'      => 'Signature Method',
 5801:                                           'url'            => 'URL',
 5802:                                           'key'            => 'Key',
 5803:                                           'lifetime'       => 'Nonce lifetime (s)',
 5804:                                           'secret'         => 'Secret',
 5805:                                           'icon'           => 'Icon',   
 5806:                                           'user'           => 'User',
 5807:                                           'fullname'       => 'Full Name',
 5808:                                           'firstname'      => 'First Name',
 5809:                                           'lastname'       => 'Last Name',
 5810:                                           'email'          => 'E-mail',
 5811:                                           'roles'          => 'Role',
 5812:                                           'window'         => 'Window',
 5813:                                           'tab'            => 'Tab',
 5814:                                           'iframe'         => 'iFrame',
 5815:                                           'height'         => 'Height',
 5816:                                           'width'          => 'Width',
 5817:                                           'linktext'       => 'Default Link Text',
 5818:                                           'explanation'    => 'Default Explanation',
 5819:                                           'passback'       => 'Tool can return grades:',
 5820:                                           'roster'         => 'Tool can retrieve roster:',
 5821:                                           'crstarget'      => 'Display target',
 5822:                                           'crslabel'       => 'Course label',
 5823:                                           'crstitle'       => 'Course title', 
 5824:                                           'crslinktext'    => 'Link Text',
 5825:                                           'crsexplanation' => 'Explanation',
 5826:                                           'crsappend'      => 'Provider URL',
 5827:                                         );
 5828:     return %lt;
 5829: }
 5830: 
 5831: sub print_proctoring {
 5832:     my ($dom,$settings,$rowtotal) = @_;
 5833:     my $itemcount = 1;
 5834:     my (%ordered,%providernames,%current,%currentdef);
 5835:     my $confname = $dom.'-domainconfig';
 5836:     my $switchserver = &check_switchserver($dom,$confname);
 5837:     if (ref($settings) eq 'HASH') {
 5838:         foreach my $item (keys(%{$settings})) {
 5839:             if (ref($settings->{$item}) eq 'HASH') {
 5840:                 my $num = $settings->{$item}{'order'};
 5841:                 $ordered{$num} = $item;
 5842:             }
 5843:         }
 5844:     } else {
 5845:         %ordered = (
 5846:                      1 => 'proctorio',
 5847:                      2 => 'examity',
 5848:                    );
 5849:     }
 5850:     %providernames = &proctoring_providernames();
 5851:     my $maxnum = scalar(keys(%ordered));
 5852:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5853:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5854:     if (ref($requref) eq 'HASH') {
 5855:         %requserfields = %{$requref};
 5856:     }
 5857:     if (ref($opturef) eq 'HASH') {
 5858:         %optuserfields = %{$opturef};
 5859:     }
 5860:     if (ref($defref) eq 'HASH') {
 5861:         %defaults = %{$defref};
 5862:     }
 5863:     if (ref($extref) eq 'HASH') {
 5864:         %extended = %{$extref};
 5865:     }
 5866:     if (ref($crsref) eq 'HASH') {
 5867:         %crsconf = %{$crsref};
 5868:     }
 5869:     if (ref($rolesref) eq 'ARRAY') {
 5870:         @courseroles = @{$rolesref};
 5871:     }
 5872:     if (ref($ltiref) eq 'ARRAY') {
 5873:         @ltiroles = @{$ltiref};
 5874:     }
 5875:     my $datatable;
 5876:     my $css_class;
 5877:     if (keys(%ordered)) {
 5878:         my @items = sort { $a <=> $b } keys(%ordered);
 5879:         for (my $i=0; $i<@items; $i++) {
 5880:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5881:             my $provider = $ordered{$items[$i]};
 5882:             my $optionsty = 'none';
 5883:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5884:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5885:             if (ref($settings) eq 'HASH') {
 5886:                 if (ref($settings->{$provider}) eq 'HASH') {
 5887:                     %current = %{$settings->{$provider}};
 5888:                     if ($current{'available'}) {
 5889:                         $optionsty = 'block';
 5890:                         $available = 1;
 5891:                     }
 5892:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5893:                         $lifetime = $current{'lifetime'};
 5894:                     }
 5895:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5896:                         $version = $current{'version'};
 5897:                     }
 5898:                     if ($current{'image'} ne '') {
 5899:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5900:                     }
 5901:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5902:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5903:                     }
 5904:                     $userincdom = $current{'incdom'};
 5905:                     if (ref($current{'roles'}) eq 'HASH') {
 5906:                         %rolemaps = %{$current{'roles'}};
 5907:                         $checkedfields{'roles'} = 1;
 5908:                     }
 5909:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5910:                         foreach my $val (@{$current{'defaults'}}) {
 5911:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5912:                                 $inuse{$val} = 1;
 5913:                             } else {
 5914:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5915:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5916:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5917:                                             $inuse{$poss} = $val;
 5918:                                             last;
 5919:                                         }
 5920:                                     }
 5921:                                 }
 5922:                             }
 5923:                         }
 5924:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5925:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5926:                             my $currval = $current{'defaults'}{$key}; 
 5927:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5928:                                 $inuse{$key} = 1;
 5929:                             } else {
 5930:                                 my $match;
 5931:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5932:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5933:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5934:                                             $inuse{$poss} = $key;
 5935:                                             last;
 5936:                                         }
 5937:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5938:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5939:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5940:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5941:                                                     $currentdef{$inner} = $currval;
 5942:                                                     $match = 1;
 5943:                                                     last;
 5944:                                                 }
 5945:                                             } elsif ($inner eq $key) {
 5946:                                                 $currentdef{$key} = $currval;
 5947:                                                 $match = 1;
 5948:                                                 last;
 5949:                                             }
 5950:                                         }
 5951:                                     }
 5952:                                     last if ($match);
 5953:                                 }
 5954:                             }
 5955:                         }
 5956:                     }
 5957:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5958:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5959:                     }
 5960:                 }
 5961:             }
 5962:             my %lt = &proctoring_titles($provider);
 5963:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5964:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5965:             my %checkedavailable = (
 5966:                                    yes => '',
 5967:                                    no  => ' checked="checked"',
 5968:                                  );
 5969:             if ($available) {
 5970:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5971:                 $checkedavailable{'no'} = '';
 5972:             }
 5973:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5974:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5975:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 5976:             for (my $k=0; $k<$maxnum; $k++) {
 5977:                 my $vpos = $k+1;
 5978:                 my $selstr;
 5979:                 if ($k == $i) {
 5980:                     $selstr = ' selected="selected" ';
 5981:                 }
 5982:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5983:             }
 5984:             if ($version eq '') {
 5985:                 if ($provider eq 'proctorio') {
 5986:                     $version = '1.0';
 5987:                 } elsif ($provider eq 'examity') {
 5988:                     $version = '1.1';
 5989:                 }
 5990:             }
 5991:             if ($lifetime eq '') {
 5992:                 $lifetime = '300';
 5993:             }
 5994:             $datatable .=
 5995:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 5996:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 5997:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5998:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 5999:                 '</td>'.
 6000:                 '<td colspan="2">'.
 6001:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 6002:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 6003:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 6004:                 ('&nbsp;'x2).
 6005:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 6006:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 6007:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 6008:                 ('&nbsp;'x2).
 6009:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 6010:                 '<br />'.
 6011:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 6012:                 '<br />'.
 6013:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 6014:                 ('&nbsp;'x2).
 6015:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 6016:                 '<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";
 6017:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 6018:             if ($imgsrc) {
 6019:                 $datatable .= $imgsrc.
 6020:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 6021:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 6022:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 6023:             }
 6024:             $datatable .= '&nbsp;';
 6025:             if ($switchserver) {
 6026:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 6027:             } else {
 6028:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 6029:             }
 6030:             unless ($imgsrc) {
 6031:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 6032:             }
 6033:             $datatable .= '</fieldset>'."\n";
 6034:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 6035:                 if (@{$requserfields{$provider}} > 0) {
 6036:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 6037:                     foreach my $field (@{$requserfields{$provider}}) {
 6038:                         $datatable .= '<span class="LC_nobreak">'.
 6039:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 6040:                                       $lt{$field}.'</label>';
 6041:                         if ($field eq 'user') {
 6042:                             my $seluserdom = '';
 6043:                             my $unseluserdom = ' selected="selected"';
 6044:                             if ($userincdom) {
 6045:                                 $seluserdom = $unseluserdom;
 6046:                                 $unseluserdom = '';
 6047:                             }
 6048:                             $datatable .= ':&nbsp;'.
 6049:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 6050:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 6051:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 6052:                                 '</select>&nbsp;';
 6053:                         } else {
 6054:                             $datatable .= '&nbsp;';
 6055:                             if ($field eq 'roles') {
 6056:                                 $showroles = 1; 
 6057:                             } 
 6058:                         }
 6059:                         $datatable .= '</span> ';
 6060:                     }
 6061:                 }
 6062:                 $datatable .= '</fieldset>'."\n";
 6063:             }
 6064:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 6065:                 if (@{$optuserfields{$provider}} > 0) {
 6066:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 6067:                     foreach my $field (@{$optuserfields{$provider}}) {
 6068:                         my $checked;
 6069:                         if ($checkedfields{$field}) {
 6070:                             $checked = ' checked="checked"';
 6071:                         }
 6072:                         $datatable .= '<span class="LC_nobreak">'.
 6073:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 6074:                     }
 6075:                     $datatable .= '</fieldset>'."\n";
 6076:                 }
 6077:             }
 6078:             if (ref($defaults{$provider}) eq 'ARRAY') {
 6079:                 if (@{$defaults{$provider}}) {
 6080:                     my (%options,@selectboxes);
 6081:                     if (ref($extended{$provider}) eq 'HASH') {
 6082:                         %options = %{$extended{$provider}};
 6083:                     }
 6084:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 6085:                     my ($rem,$numinrow,$dropdowns);
 6086:                     if ($provider eq 'proctorio') { 
 6087:                         $datatable .= '<table>';
 6088:                         $numinrow = 4;
 6089:                     }
 6090:                     my $i = 0;
 6091:                     foreach my $field (@{$defaults{$provider}}) {
 6092:                         my $checked;
 6093:                         if ($inuse{$field}) {
 6094:                             $checked = ' checked="checked"';
 6095:                         }
 6096:                         if ($provider eq 'examity') {
 6097:                             if ($field eq 'display') {
 6098:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 6099:                                 foreach my $option ('iframe','tab','window') {
 6100:                                     my $checkdisp;
 6101:                                     if ($currentdef{'target'} eq $option) {
 6102:                                         $checkdisp = ' checked="checked"';
 6103:                                     }
 6104:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 6105:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 6106:                                 }
 6107:                                 $datatable .= ('&nbsp;'x4);
 6108:                                 foreach my $dimen ('width','height') {
 6109:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 6110:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 6111:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 6112:                                                   ('&nbsp;'x2);
 6113:                                 }
 6114:                                 $datatable .= '</span><br />'.
 6115:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 6116:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 6117:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 6118:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 6119:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 6120:                                               $currentdef{'explanation'}.
 6121:                                               '</textarea></div><div style=""></div><br />';
 6122:                             }
 6123:                         } else {
 6124:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 6125:                                 my ($output,$selnone);
 6126:                                 unless ($checked) {
 6127:                                     $selnone = ' selected="selected"';
 6128:                                 }
 6129:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 6130:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 6131:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 6132:                                 foreach my $option (@{$options{$field}}) {
 6133:                                     my $sel; 
 6134:                                     if ($inuse{$field} eq $option) {
 6135:                                         $sel = ' selected="selected"';
 6136:                                     }
 6137:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 6138:                                 }
 6139:                                 $output .= '</select></span>';
 6140:                                 push(@selectboxes,$output);
 6141:                             } else {
 6142:                                 $rem = $i%($numinrow);
 6143:                                 if ($rem == 0) {
 6144:                                     if ($i > 0) {
 6145:                                         $datatable .= '</tr>';
 6146:                                     }
 6147:                                     $datatable .= '<tr>';
 6148:                                 }
 6149:                                 $datatable .= '<td class="LC_left_item">'.
 6150:                                               '<span class="LC_nobreak">'.
 6151:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 6152:                                               $fieldtitles{$field}.'</label></span></td>';
 6153:                                 $i++;
 6154:                             }
 6155:                         }
 6156:                     }
 6157:                     if ($provider eq 'proctorio') {
 6158:                         if ($numinrow) {
 6159:                             $rem = $i%$numinrow;
 6160:                         }
 6161:                         my $colsleft = $numinrow - $rem;
 6162:                         if ($colsleft > 1) {
 6163:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6164:                         } else {
 6165:                             $datatable .= '<td class="LC_left_item">';
 6166:                         }
 6167:                         $datatable .= '&nbsp;'.
 6168:                                       '</td></tr></table>';
 6169:                         if (@selectboxes) {
 6170:                             $datatable .= '<hr /><table>';
 6171:                             $numinrow = 2;
 6172:                             for (my $i=0; $i<@selectboxes; $i++) {
 6173:                                 $rem = $i%($numinrow);
 6174:                                 if ($rem == 0) {
 6175:                                     if ($i > 0) {
 6176:                                         $datatable .= '</tr>';
 6177:                                     }
 6178:                                     $datatable .= '<tr>';
 6179:                                 }
 6180:                                 $datatable .= '<td class="LC_left_item">'.
 6181:                                               $selectboxes[$i].'</td>';
 6182:                             }
 6183:                             if ($numinrow) {
 6184:                                 $rem = $i%$numinrow;
 6185:                             }
 6186:                             $colsleft = $numinrow - $rem;
 6187:                             if ($colsleft > 1) {
 6188:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6189:                             } else {
 6190:                                 $datatable .= '<td class="LC_left_item">';
 6191:                             }
 6192:                             $datatable .= '&nbsp;'.
 6193:                                           '</td></tr></table>';
 6194:                         }
 6195:                     }
 6196:                     $datatable .= '</fieldset>';
 6197:                 }
 6198:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 6199:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6200:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 6201:                     my ($rem,$numinrow);
 6202:                     if ($provider eq 'proctorio') {
 6203:                         $datatable .= '<table>';
 6204:                         $numinrow = 4;
 6205:                     }
 6206:                     my $i = 0;
 6207:                     foreach my $item (@{$crsconf{$provider}}) {
 6208:                         my $name;
 6209:                         if ($provider eq 'examity') {
 6210:                             $name = $lt{'crs'.$item};
 6211:                         } elsif ($provider eq 'proctorio') {
 6212:                             $name = $fieldtitles{$item};
 6213:                             $rem = $i%($numinrow);
 6214:                             if ($rem == 0) {
 6215:                                 if ($i > 0) {
 6216:                                     $datatable .= '</tr>';
 6217:                                 }
 6218:                                 $datatable .= '<tr>';
 6219:                             }
 6220:                             $datatable .= '<td class="LC_left_item>';
 6221:                         }
 6222:                         my $checked;
 6223:                         if ($crsconfig{$item}) {
 6224:                             $checked = ' checked="checked"';
 6225:                         }
 6226:                         $datatable .= '<span class="LC_nobreak"><label>'.
 6227:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 6228:                                       $name.'</label></span>';
 6229:                         if ($provider eq 'examity') {
 6230:                             $datatable .= '&nbsp; ';
 6231:                         }
 6232:                         $datatable .= "\n";
 6233:                         $i++;
 6234:                     }
 6235:                     if ($provider eq 'proctorio') {
 6236:                         if ($numinrow) {
 6237:                             $rem = $i%$numinrow;
 6238:                         }
 6239:                         my $colsleft = $numinrow - $rem;
 6240:                         if ($colsleft > 1) {
 6241:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6242:                         } else {
 6243:                             $datatable .= '<td class="LC_left_item">';
 6244:                         }
 6245:                         $datatable .= '&nbsp;'.
 6246:                                       '</td></tr></table>';
 6247:                     }
 6248:                     $datatable .= '</fieldset>';
 6249:                 }
 6250:                 if ($showroles) {
 6251:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6252:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 6253:                     foreach my $role (@courseroles) {
 6254:                         my ($selected,$selectnone);
 6255:                         if (!$rolemaps{$role}) {
 6256:                             $selectnone = ' selected="selected"';
 6257:                         }
 6258:                         $datatable .= '<td style="text-align: center">'.
 6259:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 6260:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 6261:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6262:                         foreach my $ltirole (@ltiroles) {
 6263:                             unless ($selectnone) {
 6264:                                 if ($rolemaps{$role} eq $ltirole) {
 6265:                                     $selected = ' selected="selected"';
 6266:                                 } else {
 6267:                                     $selected = '';
 6268:                                 }
 6269:                             }
 6270:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 6271:                         }
 6272:                         $datatable .= '</select></td>';
 6273:                     }
 6274:                     $datatable .= '</tr></table></fieldset>'.
 6275:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6276:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 6277:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 6278:                                   '<tr><td></td><td>lms</td>'.
 6279:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 6280:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 6281:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 6282:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 6283:                         my %custom = %{$settings->{$provider}->{'custom'}};
 6284:                         if (keys(%custom) > 0) {
 6285:                             foreach my $key (sort(keys(%custom))) {
 6286:                                 next if ($key eq 'lms');
 6287:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 6288:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 6289:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 6290:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 6291:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 6292:                             }
 6293:                         }
 6294:                     }
 6295:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 6296:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 6297:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 6298:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 6299:                                   '</table></fieldset></td></tr>'."\n";
 6300:                 }
 6301:                 $datatable .= '</td></tr>';
 6302:             }
 6303:             $itemcount ++;
 6304:         }
 6305:     }
 6306:     return $datatable;
 6307: }
 6308: 
 6309: sub proctoring_data {
 6310:     my $requserfields = {
 6311:                       proctorio => ['user'],
 6312:                       examity   => ['roles','user'],
 6313:                      };
 6314:     my $optuserfields = {
 6315:                         proctorio => ['fullname'],
 6316:                         examity   => ['fullname','firstname','lastname','email'],
 6317:                      };
 6318:     my $defaults = {
 6319:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6320:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6321:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6322:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 6323:                                 'reentry','calculator','whiteboard'],
 6324:                   examity   => ['display'],
 6325:                 };
 6326:     my $extended = { 
 6327:                   proctorio => {
 6328:                                  verifyid => ['verifyidauto','verifyidlive'],
 6329:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 6330:                                  tabslinks => ['notabs','linksonly'],
 6331:                                  reentry => ['noreentry','agentreentry'],
 6332:                                  calculator => ['calculatorbasic','calculatorsci'],
 6333:                                },
 6334:                   examity => {
 6335:                                display => {
 6336:                                            target      => ['iframe','tab','window'],
 6337:                                            width       => '',
 6338:                                            height      => '',
 6339:                                            linktext    => '',
 6340:                                            explanation => '',
 6341:                                           },
 6342:                              },
 6343:                 };
 6344:     my $crsconf = {
 6345:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6346:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6347:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6348:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 6349:                                'reentry','calculator','whiteboard'],
 6350:                  examity => ['label','title','target','linktext','explanation','append'],
 6351:                };
 6352:     my $courseroles = ['cc','in','ta','ep','st'];
 6353:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 6354:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 6355: }
 6356: 
 6357: sub proctoring_titles {
 6358:     my ($item) = @_;
 6359:     my (%common_lt,%custom_lt);
 6360:     %common_lt = &Apache::lonlocal::texthash (
 6361:                      'avai'      => 'Available?',
 6362:                      'base'      => 'Basic Settings',
 6363:                      'requ'      => 'User data required to be sent on launch',
 6364:                      'optu'      => 'User data optionally sent on launch',
 6365:                      'udsl'      => 'User data sent on launch',
 6366:                      'defa'      => 'Defaults for items configurable in course',
 6367:                      'sigmethod' => 'Signature Method',
 6368:                      'key'       => 'Key',
 6369:                      'lifetime'  => 'Nonce lifetime (s)',
 6370:                      'secret'    => 'Secret',
 6371:                      'icon'      => 'Icon',
 6372:                      'fullname'  => 'Full Name',
 6373:                      'visible'   => 'Visible input',
 6374:                      'username'  => 'username',
 6375:                      'user'      => 'User',
 6376:                  );
 6377:     if ($item eq 'proctorio') {
 6378:         %custom_lt = &Apache::lonlocal::texthash (
 6379:                          'version'        => 'OAuth version',
 6380:                          'url'            => 'API URL',
 6381:                          'uname:dom'      => 'username-domain',
 6382:         );
 6383:     } elsif ($item eq 'examity') {
 6384:         %custom_lt = &Apache::lonlocal::texthash (
 6385:                          'version'        => 'LTI Version',
 6386:                          'url'            => 'URL',
 6387:                          'uname:dom'      => 'username:domain',
 6388:                          'msgtype'        => 'Message Type',
 6389:                          'firstname'      => 'First Name',
 6390:                          'lastname'       => 'Last Name',
 6391:                          'email'          => 'E-mail',
 6392:                          'roles'          => 'Role',
 6393:                          'crstarget'      => 'Display target',
 6394:                          'crslabel'       => 'Course label',
 6395:                          'crstitle'       => 'Course title', 
 6396:                          'crslinktext'    => 'Link Text',
 6397:                          'crsexplanation' => 'Explanation',
 6398:                          'crsappend'      => 'Provider URL',
 6399:         );
 6400:     }
 6401:     my %lt = (%common_lt,%custom_lt);
 6402:     return %lt;
 6403: }
 6404: 
 6405: sub proctoring_fieldtitles {
 6406:     my ($item) = @_;
 6407:     if ($item eq 'proctorio') {
 6408:         return &Apache::lonlocal::texthash (
 6409:                   'recordvideo' => 'Record video',
 6410:                   'recordaudio' => 'Record audio',
 6411:                   'recordscreen' => 'Record screen',
 6412:                   'recordwebtraffic' => 'Record web traffic',
 6413:                   'recordroomstart' => 'Record room scan',
 6414:                   'verifyvideo' => 'Verify webcam',
 6415:                   'verifyaudio' => 'Verify microphone',
 6416:                   'verifydesktop' => 'Verify desktop recording',
 6417:                   'verifyid' => 'Photo ID verification',
 6418:                   'verifysignature' => 'Require signature',
 6419:                   'fullscreen' => 'Fullscreen',
 6420:                   'clipboard' => 'Disable copy/paste',
 6421:                   'tabslinks' => 'New tabs/windows',
 6422:                   'closetabs' => 'Close other tabs',
 6423:                   'onescreen' => 'Limit to single screen',
 6424:                   'print' => 'Disable Printing',
 6425:                   'downloads' => 'Disable Downloads',
 6426:                   'cache' => 'Empty cache after exam',
 6427:                   'rightclick' => 'Disable right click',
 6428:                   'reentry' => 'Re-entry to exam',
 6429:                   'calculator' => 'Onscreen calculator',
 6430:                   'whiteboard' => 'Onscreen whiteboard',
 6431:                   'verifyidauto' => 'Automated verification',
 6432:                   'verifyidlive' => 'Live agent verification',
 6433:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 6434:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 6435:                   'fullscreensever' => 'Forced, navigation away ends exam',
 6436:                   'notabs' => 'Disaallowed',
 6437:                   'linksonly' => 'Allowed from links in exam',
 6438:                   'noreentry' => 'Disallowed',
 6439:                   'agentreentry' => 'Agent required for re-entry',
 6440:                   'calculatorbasic' => 'Basic',
 6441:                   'calculatorsci' => 'Scientific',
 6442:         );
 6443:     } elsif ($item eq 'examity') {
 6444:         return &Apache::lonlocal::texthash (
 6445:                 'target'         => 'Display target',   
 6446:                 'window'         => 'Window',
 6447:                 'tab'            => 'Tab',
 6448:                 'iframe'         => 'iFrame',
 6449:                 'height'         => 'Height (pixels)',
 6450:                 'width'          => 'Width (pixels)',
 6451:                 'linktext'       => 'Default Link Text',
 6452:                 'explanation'    => 'Default Explanation',
 6453:                 'append'         => 'Provider URL',
 6454:         );
 6455:     }
 6456: }
 6457: 
 6458: sub proctoring_providernames {
 6459:     return (
 6460:              proctorio => 'Proctorio',
 6461:              examity   => 'Examity',
 6462:            );
 6463: }
 6464: 
 6465: sub print_lti {
 6466:     my ($position,$dom,$settings,$rowtotal) = @_;
 6467:     my $itemcount = 1;
 6468:     my ($datatable,$css_class);
 6469:     my (%rules,%encrypt,%privkeys,%linkprot);
 6470:     if (ref($settings) eq 'HASH') {
 6471:         if ($position eq 'top') {
 6472:             if (exists($settings->{'encrypt'})) {
 6473:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 6474:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 6475:                         if ($key eq 'consumers') {
 6476:                             $encrypt{'ltisec_'.$key} = $settings->{'encrypt'}{$key};
 6477:                         } else {
 6478:                             $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 6479:                         }
 6480:                     }
 6481:                 }
 6482:             }
 6483:             if (exists($settings->{'private'})) {
 6484:                 if (ref($settings->{'private'}) eq 'HASH') {
 6485:                     if (ref($settings->{'private'}) eq 'HASH') {
 6486:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 6487:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 6488:                         }
 6489:                     }
 6490:                 }
 6491:             }
 6492:         } elsif ($position eq 'middle') {
 6493:             if (exists($settings->{'rules'})) {
 6494:                 if (ref($settings->{'rules'}) eq 'HASH') {
 6495:                     %rules = %{$settings->{'rules'}};
 6496:                 }
 6497:             }
 6498:         } elsif ($position eq 'lower') {
 6499:             if (exists($settings->{'linkprot'})) {
 6500:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 6501:                     %linkprot = %{$settings->{'linkprot'}};
 6502:                     if ($linkprot{'lock'}) {
 6503:                         delete($linkprot{'lock'});
 6504:                     }
 6505:                 }
 6506:             }
 6507:         } else {
 6508:             foreach my $key ('encrypt','private','rules','linkprot') {
 6509:                 if (exists($settings->{$key})) {
 6510:                     delete($settings->{$key});
 6511:                 }
 6512:             }
 6513:         }
 6514:     }
 6515:     if ($position eq 'top') {
 6516:         my @ids=&Apache::lonnet::current_machine_ids();
 6517:         my %servers = &Apache::lonnet::get_servers($dom,'library');
 6518:         my $primary = &Apache::lonnet::domain($dom,'primary');
 6519:         my ($extra,$numshown);
 6520:         foreach my $hostid (sort(keys(%servers))) {
 6521:             my ($showextra,$divsty,$switch);
 6522:             if ($hostid eq $primary) {
 6523:                 if (($encrypt{'ltisec_consumers'}) || ($encrypt{'ltisec_domlinkprot'})) {
 6524:                     $showextra = 1;
 6525:                 }
 6526:             }
 6527:             if ($encrypt{'ltisec_crslinkprot'}) {
 6528:                 $showextra = 1;
 6529:             }
 6530:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 6531:                 $switch = 1;
 6532:             }
 6533:             if ($showextra) {
 6534:                 $numshown ++;
 6535:                 $divsty = 'display:inline-block'; 
 6536:             } else {
 6537:                 $divsty = 'display:none';
 6538:             } 
 6539:             $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
 6540:                       '<legend>'.$hostid.'</legend>';
 6541:             if ($switch) {
 6542:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 6543:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 6544:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 6545:                 if (exists($privkeys{$hostid})) {
 6546:                     $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 6547:                               '<span class="LC_nobreak">'.
 6548:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6549:                               '<span class="LC_nobreak">'.&mt('Change?').
 6550:                               '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6551:                               ('&nbsp;'x2).
 6552:                               '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6553:                               '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6554:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6555:                               '</span></div>';
 6556:                 } else {
 6557:                     $extra .= '<span class="LC_nobreak">'.
 6558:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6559:                               '</span>'."\n";
 6560:                 }
 6561:             } elsif (exists($privkeys{$hostid})) {
 6562:                 $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 6563:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6564:                           '<span class="LC_nobreak">'.&mt('Change?').
 6565:                           '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6566:                           ('&nbsp;'x2).
 6567:                           '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6568:                           '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6569:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 6570:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6571:                           '<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>'.
 6572:                           '</span></div>';
 6573:             } else {
 6574:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 6575:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6576:                           '<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>';
 6577:             }
 6578:             $extra .= '</fieldset>';
 6579:         }
 6580:         my %choices = &Apache::lonlocal::texthash (
 6581:                                                       ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 6582:                                                       ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 6583:                                                       ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
 6584:                                                   );
 6585:         my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
 6586:         my %defaultchecked = (
 6587:                                'ltisec_crslinkprot' => 'off',
 6588:                                'ltisec_domlinkprot' => 'off',
 6589:                                'ltisec_consumers'   => 'off',
 6590:                              );
 6591:         my ($onclick,$itemcount);
 6592:         $onclick = 'javascript:toggleLTIEncKey(this.form);';
 6593:         ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
 6594:                                                      \%choices,$itemcount,$onclick,'','left','no');
 6595: 
 6596:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6597:         my $noprivkeysty = 'display:inline-block';
 6598:         if ($numshown) {
 6599:             $noprivkeysty = 'display:none'; 
 6600:         }
 6601:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 6602:                       '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
 6603:                       '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 6604:                       $extra.
 6605:                       '</td></tr>';
 6606:         $itemcount ++;                
 6607:         $$rowtotal += $itemcount;
 6608:     } elsif ($position eq 'middle') {
 6609:         $datatable = &password_rules('secrets',\$itemcount,\%rules);
 6610:         $$rowtotal += $itemcount;
 6611:     } elsif ($position eq 'lower') {
 6612:          $datatable .= &Apache::courseprefs::print_linkprotection($dom,'',$settings,$rowtotal,'','','domain');
 6613:     } else {
 6614:         my $maxnum = 0;
 6615:         my %ordered;
 6616:         if (ref($settings) eq 'HASH') {
 6617:             foreach my $item (keys(%{$settings})) {
 6618:                 if (ref($settings->{$item}) eq 'HASH') {
 6619:                     my $num = $settings->{$item}{'order'};
 6620:                     if ($num eq '') {
 6621:                         $num = scalar(keys(%{$settings}));
 6622:                     }
 6623:                     $ordered{$num} = $item;
 6624:                 }
 6625:             }
 6626:         }
 6627:         $maxnum = scalar(keys(%ordered));
 6628:         my %lt = &lti_names();
 6629:         if (keys(%ordered)) {
 6630:             my @items = sort { $a <=> $b } keys(%ordered);
 6631:             for (my $i=0; $i<@items; $i++) {
 6632:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6633:                 my $item = $ordered{$items[$i]};
 6634:                 my ($key,$secret,$lifetime,$consumer,$requser,$crsinc,$current);
 6635:                 if (ref($settings->{$item}) eq 'HASH') {
 6636:                     $key = $settings->{$item}->{'key'};
 6637:                     $secret = $settings->{$item}->{'secret'};
 6638:                     $lifetime = $settings->{$item}->{'lifetime'};
 6639:                     $consumer = $settings->{$item}->{'consumer'};
 6640:                     $requser = $settings->{$item}->{'requser'};
 6641:                     $crsinc = $settings->{$item}->{'crsinc'};
 6642:                     $current = $settings->{$item};
 6643:                 }
 6644:                 my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 6645:                 my %checkedrequser = (
 6646:                                        yes => ' checked="checked"',
 6647:                                        no  => '',
 6648:                                      );
 6649:                 if (!$requser) {
 6650:                     $checkedrequser{'no'} = $checkedrequser{'yes'};
 6651:                     $checkedrequser{'yes'} = '';
 6652:                 }
 6653:                 my $onclickcrsinc = ' onclick="toggleLTI(this.form,'."'crsinc','$i'".');"';
 6654:                 my %checkedcrsinc = (
 6655:                                       yes => ' checked="checked"',
 6656:                                       no  => '',
 6657:                                     );
 6658:                 if (!$crsinc) {
 6659:                     $checkedcrsinc{'no'} = $checkedcrsinc{'yes'};
 6660:                     $checkedcrsinc{'yes'} = '';
 6661:                 }
 6662:                 my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 6663:                 $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6664:                              .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 6665:                 for (my $k=0; $k<=$maxnum; $k++) {
 6666:                     my $vpos = $k+1;
 6667:                     my $selstr;
 6668:                     if ($k == $i) {
 6669:                         $selstr = ' selected="selected" ';
 6670:                     }
 6671:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6672:                 }
 6673:                 $datatable .= '</select>'.('&nbsp;'x2).
 6674:                     '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 6675:                     &mt('Delete?').'</label></span></td>'.
 6676:                     '<td colspan="2">'.
 6677:                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6678:                     '<span class="LC_nobreak">'.$lt{'consumer'}.
 6679:                     ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 6680:                     ('&nbsp;'x2).
 6681:                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 6682:                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 6683:                     ('&nbsp;'x2).
 6684:                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 6685:                     'value="'.$lifetime.'" size="3" /></span>'.
 6686:                     ('&nbsp;'x2).
 6687:                     '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6688:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6689:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 6690:                     '<br /><br />'.
 6691:                     '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6692:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="1"'.$onclickcrsinc.$checkedcrsinc{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6693:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="0"'.$onclickcrsinc.$checkedcrsinc{no}.' />'.&mt('No').'</label></span>'."\n".
 6694:                     ('&nbsp;'x4).
 6695:                     '<span class="LC_nobreak">'.$lt{'key'}.
 6696:                     ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 6697:                     ('&nbsp;'x2).
 6698:                     '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 6699:                     '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 6700:                     '<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>'.
 6701:                     '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 6702:                     '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 6703:                 $itemcount ++;
 6704:             }
 6705:         }
 6706:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6707:         my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 6708:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 6709:                       '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 6710:                       '<select name="lti_pos_add"'.$chgstr.'>';
 6711:         for (my $k=0; $k<$maxnum+1; $k++) {
 6712:             my $vpos = $k+1;
 6713:             my $selstr;
 6714:             if ($k == $maxnum) {
 6715:                 $selstr = ' selected="selected" ';
 6716:             }
 6717:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6718:         }
 6719:         $datatable .= '</select>&nbsp;'."\n".
 6720:                       '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 6721:                       '<td colspan="2">'.
 6722:                       '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6723:                       '<span class="LC_nobreak">'.$lt{'consumer'}.
 6724:                       ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 6725:                       ('&nbsp;'x2).
 6726:                       '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 6727:                       '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 6728:                       ('&nbsp;'x2).
 6729:                       '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 6730:                       ('&nbsp;'x2).
 6731:                       '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6732:                       '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6733:                       '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 6734:                       '<br /><br />'.
 6735:                       '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6736:                       '<label><input type="radio" name="lti_crsinc_add" value="1" onclick="toggleLTI(this.form,'."'crsinc','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6737:                       '<label><input type="radio" name="lti_crsinc_add" value="0" onclick="toggleLTI(this.form,'."'crsinc','add'".');" />'.&mt('No').'</label></span>'."\n".
 6738:                       ('&nbsp;'x4).
 6739:                       '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 6740:                       ('&nbsp;'x2).
 6741:                       '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 6742:                       '<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".
 6743:                       '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 6744:                       '</td>'."\n".
 6745:                       '</tr>'."\n";
 6746:         $itemcount ++;
 6747:     }
 6748:     $$rowtotal += $itemcount;
 6749:     return $datatable;
 6750: }
 6751: 
 6752: sub lti_names {
 6753:     my %lt = &Apache::lonlocal::texthash(
 6754:                                           'version'   => 'LTI Version',
 6755:                                           'url'       => 'URL',
 6756:                                           'key'       => 'Key',
 6757:                                           'lifetime'  => 'Nonce lifetime (s)',
 6758:                                           'consumer'  => 'Consumer',
 6759:                                           'secret'    => 'Secret',
 6760:                                           'requser'   => "User's identity sent",
 6761:                                           'crsinc'    => "Course's identity sent",
 6762:                                           'email'     => 'Email address',
 6763:                                           'sourcedid' => 'User ID',
 6764:                                           'other'     => 'Other',
 6765:                                           'passback'  => 'Can return grades to Consumer:',
 6766:                                           'roster'    => 'Can retrieve roster from Consumer:',
 6767:                                           'topmenu'   => 'Display LON-CAPA page header',
 6768:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 6769:                                         );
 6770:     return %lt;
 6771: }
 6772: 
 6773: sub lti_options {
 6774:     my ($num,$current,$itemcount,%lt) = @_;
 6775:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 6776:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 6777:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 6778:     $checked{'storecrs'}{'Y'} = ' checked="checked"';
 6779:     $checked{'makecrs'}{'N'} = ' checked="checked"';
 6780:     $checked{'mapcrstype'} = {};
 6781:     $checked{'makeuser'} = {};
 6782:     $checked{'selfenroll'} = {};
 6783:     $checked{'crssec'} = {};
 6784:     $checked{'crssecsrc'} = {};
 6785:     $checked{'lcauth'} = {};
 6786:     $checked{'menuitem'} = {};
 6787:     if ($num eq 'add') {
 6788:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 6789:     }
 6790:     my $userfieldsty = 'none';
 6791:     my $crsfieldsty = 'none';
 6792:     my $crssecfieldsty = 'none';
 6793:     my $secsrcfieldsty = 'none';
 6794:     my $callbacksty = 'none';
 6795:     my $passbacksty = 'none';
 6796:     my $optionsty = 'block';
 6797:     my $crssty = 'block';
 6798:     my $lcauthparm;
 6799:     my $lcauthparmstyle = 'display:none';
 6800:     my $lcauthparmtext;
 6801:     my $menusty;
 6802:     my $numinrow = 4;
 6803:     my %menutitles = &ltimenu_titles();
 6804: 
 6805:     if (ref($current) eq 'HASH') {
 6806:         if (!$current->{'requser'}) {
 6807:             $optionsty = 'none';
 6808:             $crssty = 'none';
 6809:         } elsif (!$current->{'crsinc'}) {
 6810:             $crssty = 'none';
 6811:         }
 6812:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 6813:             $checked{'mapuser'}{'sourcedid'} = '';
 6814:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 6815:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 6816:             } else {
 6817:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 6818:                 $userfield = $current->{'mapuser'};
 6819:                 $userfieldsty = 'inline-block';
 6820:             }
 6821:         }
 6822:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 6823:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 6824:             if ($current->{'mapcrs'} eq 'context_id') {
 6825:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 6826:             } else {
 6827:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 6828:                 $cidfield = $current->{'mapcrs'};
 6829:                 $crsfieldsty = 'inline-block';
 6830:             }
 6831:         }
 6832:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 6833:             foreach my $type (@{$current->{'mapcrstype'}}) {
 6834:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 6835:             }
 6836:         }
 6837:         if (!$current->{'storecrs'}) {
 6838:             $checked{'storecrs'}{'N'} = $checked{'storecrs'}{'Y'};
 6839:             $checked{'storecrs'}{'Y'} = '';
 6840:         }
 6841:         if ($current->{'makecrs'}) {
 6842:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 6843:         }
 6844:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 6845:             foreach my $role (@{$current->{'makeuser'}}) {
 6846:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 6847:             }
 6848:         }
 6849:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 6850:             $checked{'lcauth'}{$1} = ' checked="checked"';
 6851:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 6852:                 $lcauthparm = $current->{'lcauthparm'};
 6853:                 $lcauthparmstyle = 'display:table-row'; 
 6854:                 if ($current->{'lcauth'} eq 'localauth') {
 6855:                     $lcauthparmtext = &mt('Local auth argument');
 6856:                 } else {
 6857:                     $lcauthparmtext = &mt('Kerberos domain');
 6858:                 }
 6859:             }
 6860:         }
 6861:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 6862:             foreach my $role (@{$current->{'selfenroll'}}) {
 6863:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 6864:             }
 6865:         }
 6866:         if (ref($current->{'maproles'}) eq 'HASH') {
 6867:             %rolemaps = %{$current->{'maproles'}};
 6868:         }
 6869:         if ($current->{'section'} ne '') {
 6870:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 6871:             $crssecfieldsty = 'inline-block';
 6872:             if ($current->{'section'} eq 'course_section_sourcedid') {
 6873:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 6874:             } else {
 6875:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 6876:                 $crssecsrc = $current->{'section'};
 6877:                 $secsrcfieldsty = 'inline-block';
 6878:             }
 6879:         } else {
 6880:             $checked{'crssec'}{'N'} = ' checked="checked"';
 6881:         }
 6882:         if ($current->{'callback'} ne '') {
 6883:             $callback = $current->{'callback'};
 6884:             $checked{'callback'}{'Y'} = ' checked="checked"';
 6885:             $callbacksty = 'inline-block';
 6886:         } else {
 6887:             $checked{'callback'}{'N'} = ' checked="checked"';
 6888:         }
 6889:         if ($current->{'topmenu'}) {
 6890:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 6891:         } else {
 6892:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 6893:         }
 6894:         if ($current->{'inlinemenu'}) {
 6895:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6896:         } else {
 6897:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 6898:         }
 6899:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 6900:             $menusty = 'inline-block';
 6901:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 6902:                 foreach my $item (@{$current->{'lcmenu'}}) {
 6903:                     if (exists($menutitles{$item})) {
 6904:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 6905:                     }
 6906:                 }
 6907:             }
 6908:         } else {
 6909:             $menusty = 'none';
 6910:         }
 6911:     } else {
 6912:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 6913:         $checked{'crssec'}{'N'} = ' checked="checked"';
 6914:         $checked{'callback'}{'N'} = ' checked="checked"';
 6915:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 6916:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 6917:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 6918:         $menusty = 'inline-block'; 
 6919:     }
 6920:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 6921:     my %coursetypetitles = &Apache::lonlocal::texthash (
 6922:                                official   => 'Official',
 6923:                                unofficial => 'Unofficial',
 6924:                                community  => 'Community',
 6925:                                textbook   => 'Textbook',
 6926:                                placement  => 'Placement Test',
 6927:                                lti        => 'LTI Provider',
 6928:     );
 6929:     my @authtypes = ('internal','krb4','krb5','localauth');
 6930:     my %shortauth = (
 6931:                      internal => 'int',
 6932:                      krb4 => 'krb4',
 6933:                      krb5 => 'krb5',
 6934:                      localauth  => 'loc'
 6935:                     );
 6936:     my %authnames = &authtype_names();
 6937:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6938:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6939:     my @courseroles = ('cc','in','ta','ep','st');
 6940:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6941:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6942:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6943:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6944:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6945:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6946:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6947:     my $output = '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Logout options').'</legend>'.
 6948:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback to logout LON-CAPA on log out from Consumer').':&nbsp;'.
 6949:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6950:                  $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6951:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6952:                  $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6953:                  '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6954:                  '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6955:                  '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6956:                  '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6957:                  '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6958:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6959:     foreach my $option ('sourcedid','email','other') {
 6960:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6961:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6962:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6963:     }
 6964:     $output .= '</span></div>'.
 6965:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6966:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6967:                'value="'.$userfield.'" /></div></fieldset>'.
 6968:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6969:     foreach my $ltirole (@ltiroles) {
 6970:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6971:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 6972:     }
 6973:     $output .= '</fieldset>'.
 6974:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 6975:                '<table>'.
 6976:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 6977:                '</table>'.
 6978:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 6979:                '<td class="LC_left_item">';
 6980:     foreach my $auth ('lti',@authtypes) {
 6981:         my $authtext;
 6982:         if ($auth eq 'lti') {
 6983:             $authtext = &mt('None');
 6984:         } else {
 6985:             $authtext = $authnames{$shortauth{$auth}};
 6986:         }
 6987:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 6988:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 6989:                    $authtext.'</label></span> &nbsp;';
 6990:     }
 6991:     $output .= '</td></tr>'.
 6992:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 6993:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 6994:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 6995:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 6996:                '</table></fieldset>'.
 6997:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.
 6998:                &mt('LON-CAPA menu items (Course Coordinator can override)').'</legend>'.
 6999:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 7000:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 7001:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7002:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 7003:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 7004:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7005:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 7006:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 7007:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7008:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 7009:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 7010:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7011:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 7012:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 7013:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 7014:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 7015:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 7016:                    ('&nbsp;'x2);
 7017:     }
 7018:     $output .= '</span></div></fieldset>'.
 7019:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 7020:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 7021:                &mt('Unique course identifier').':&nbsp;';
 7022:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 7023:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 7024:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 7025:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 7026:     }
 7027:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 7028:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 7029:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7030:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 7031:     foreach my $type (@coursetypes) {
 7032:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 7033:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 7034:                    ('&nbsp;'x2);
 7035:     }
 7036:     $output .= '</span><br /><br />'.
 7037:                '<span class="LC_nobreak">'.&mt('Store mapping of course identifier to LON-CAPA CourseID').':&nbsp;'.
 7038:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="0"'.
 7039:                $checked{'storecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7040:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="1"'.
 7041:                $checked{'storecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7042:                '</fieldset>'.
 7043:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 7044:     foreach my $ltirole (@lticourseroles) {
 7045:         my ($selected,$selectnone);
 7046:         if ($rolemaps{$ltirole} eq '') {
 7047:             $selectnone = ' selected="selected"';
 7048:         }
 7049:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 7050:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 7051:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 7052:         foreach my $role (@courseroles) {
 7053:             unless ($selectnone) {
 7054:                 if ($rolemaps{$ltirole} eq $role) {
 7055:                     $selected = ' selected="selected"';
 7056:                 } else {
 7057:                     $selected = '';
 7058:                 }
 7059:             }
 7060:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 7061:                        &Apache::lonnet::plaintext($role,'Course').
 7062:                        '</option>';
 7063:         }
 7064:         $output .= '</select></td>';
 7065:     }
 7066:     $output .= '</tr></table></fieldset>'.
 7067:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Creating courses').'</legend>'.
 7068:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 7069:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 7070:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7071:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 7072:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7073:                '</fieldset>'.
 7074:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 7075:     foreach my $lticrsrole (@lticourseroles) {
 7076:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 7077:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 7078:     }
 7079:     $output .= '</fieldset>'.
 7080:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Course options').'</legend>'.
 7081:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 7082:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 7083:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7084:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 7085:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 7086:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 7087:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 7088:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 7089:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 7090:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 7091:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 7092:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 7093:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 7094:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 7095:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 7096:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 7097:     foreach my $extra ('roster','passback') {
 7098:         my $checkedon = '';
 7099:         my $checkedoff = ' checked="checked"';
 7100:         if ($extra eq 'passback') {
 7101:             $pb1p1chk = ' checked="checked"';
 7102:             $pb1p0chk = '';
 7103:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 7104:         } else {
 7105:             $onclickpb = ''; 
 7106:         }
 7107:         if (ref($current) eq 'HASH') {
 7108:             if (($current->{$extra})) {
 7109:                 $checkedon = $checkedoff;
 7110:                 $checkedoff = '';
 7111:                 if ($extra eq 'passback') {
 7112:                     $passbacksty = 'inline-block';
 7113:                 }
 7114:                 if ($current->{'passbackformat'} eq '1.0') {
 7115:                     $pb1p0chk =  ' checked="checked"';
 7116:                     $pb1p1chk = '';
 7117:                 }
 7118:             }
 7119:         }
 7120:         $output .= $lt{$extra}.'&nbsp;'.
 7121:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 7122:                    &mt('No').'</label>'.('&nbsp;'x2).
 7123:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 7124:                    &mt('Yes').'</label><br />';
 7125:     }
 7126:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 7127:                '<span class="LC_nobreak">'.&mt('Grade format').
 7128:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 7129:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 7130:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 7131:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 7132:                '<div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>';
 7133:     $output .= '</span></div></fieldset>';
 7134: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 7135: #
 7136: #    $output .= '</fieldset>'.
 7137: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 7138:     return $output;
 7139: }
 7140: 
 7141: sub ltimenu_titles {
 7142:     return &Apache::lonlocal::texthash(
 7143:                                         fullname    => 'Full name',
 7144:                                         coursetitle => 'Course title',
 7145:                                         role        => 'Role',
 7146:                                         logout      => 'Logout',
 7147:                                         grades      => 'Grades',
 7148:     );
 7149: }
 7150: 
 7151: sub check_switchserver {
 7152:     my ($home) = @_;
 7153:     my $switchserver;
 7154:     if ($home ne '') {
 7155:         my $allowed;
 7156:         my @ids=&Apache::lonnet::current_machine_ids();
 7157:         foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 7158:         if (!$allowed) {
 7159:             $switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role='.
 7160:                           &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 7161:                           '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 7162:         }
 7163:     }
 7164:     return $switchserver;
 7165: }
 7166: 
 7167: sub print_coursedefaults {
 7168:     my ($position,$dom,$settings,$rowtotal) = @_;
 7169:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 7170:     my $itemcount = 1;
 7171:     my %choices =  &Apache::lonlocal::texthash (
 7172:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 7173:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 7174:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 7175:         coursecredits        => 'Credits can be specified for courses',
 7176:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 7177:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 7178:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 7179:         texengine            => 'Default method to display mathematics',
 7180:         postsubmit           => 'Disable submit button/keypress following student submission',
 7181:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 7182:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 7183:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 7184:     );
 7185:     my %staticdefaults = (
 7186:                            anonsurvey_threshold => 10,
 7187:                            uploadquota          => 500,
 7188:                            postsubmit           => 60,
 7189:                            mysqltables          => 172800,
 7190:                          );
 7191:     if ($position eq 'top') {
 7192:         %defaultchecked = (
 7193:                             'canuse_pdfforms' => 'off',
 7194:                             'uselcmath'       => 'on',
 7195:                             'usejsme'         => 'on',
 7196:                             'inline_chem'     => 'on',
 7197:                             'canclone'        => 'none',
 7198:                           );
 7199:         @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem');
 7200:         my $deftex = $Apache::lonnet::deftex;
 7201:         if (ref($settings) eq 'HASH') {
 7202:             if ($settings->{'texengine'}) {
 7203:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 7204:                     $deftex = $settings->{'texengine'};
 7205:                 }
 7206:             }
 7207:         }
 7208:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7209:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 7210:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 7211:                        '</span></td><td class="LC_right_item">'.
 7212:                        '<select name="texengine">'."\n";
 7213:         my %texoptions = (
 7214:                             MathJax  => 'MathJax',
 7215:                             mimetex  => &mt('Convert to Images'),
 7216:                             tth      => &mt('TeX to HTML'),
 7217:                          );
 7218:         foreach my $renderer ('MathJax','mimetex','tth') {
 7219:             my $selected = '';
 7220:             if ($renderer eq $deftex) {
 7221:                 $selected = ' selected="selected"';
 7222:             }
 7223:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 7224:         }
 7225:         $mathdisp .= '</select></td></tr>'."\n";
 7226:         $itemcount ++;
 7227:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 7228:                                                      \%choices,$itemcount);
 7229:         $datatable = $mathdisp.$datatable;
 7230:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7231:         $datatable .=
 7232:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 7233:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 7234:             '</span></td><td class="LC_left_item">';
 7235:         my $currcanclone = 'none';
 7236:         my $onclick;
 7237:         my @cloneoptions = ('none','domain');
 7238:         my %clonetitles = &Apache::lonlocal::texthash (
 7239:                              none     => 'No additional course requesters',
 7240:                              domain   => "Any course requester in course's domain",
 7241:                              instcode => 'Course requests for official courses ...',
 7242:                           );
 7243:         my (%codedefaults,@code_order,@posscodes);
 7244:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 7245:                                                     \@code_order) eq 'ok') {
 7246:             if (@code_order > 0) {
 7247:                 push(@cloneoptions,'instcode');
 7248:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 7249:             }
 7250:         }
 7251:         if (ref($settings) eq 'HASH') {
 7252:             if ($settings->{'canclone'}) {
 7253:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 7254:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 7255:                         if (@code_order > 0) {
 7256:                             $currcanclone = 'instcode';
 7257:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 7258:                         }
 7259:                     }
 7260:                 } elsif ($settings->{'canclone'} eq 'domain') {
 7261:                     $currcanclone = $settings->{'canclone'};
 7262:                 }
 7263:             }
 7264:         }
 7265:         foreach my $option (@cloneoptions) {
 7266:             my ($checked,$additional);
 7267:             if ($currcanclone eq $option) {
 7268:                 $checked = ' checked="checked"';
 7269:             }
 7270:             if ($option eq 'instcode') {
 7271:                 if (@code_order) {
 7272:                     my $show = 'none';
 7273:                     if ($checked) {
 7274:                         $show = 'block';
 7275:                     }
 7276:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 7277:                                   &mt('Institutional codes for new and cloned course have identical:').
 7278:                                   '<br />';
 7279:                     foreach my $item (@code_order) {
 7280:                         my $codechk;
 7281:                         if ($checked) {
 7282:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 7283:                                 $codechk = ' checked="checked"';
 7284:                             }
 7285:                         }
 7286:                         $additional .= '<label>'.
 7287:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 7288:                                        $item.'</label>';
 7289:                     }
 7290:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 7291:                 }
 7292:             }
 7293:             $datatable .=
 7294:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 7295:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 7296:                 '</label>&nbsp;'.$additional.'</span><br />';
 7297:         }
 7298:         $datatable .= '</td>'.
 7299:                       '</tr>';
 7300:         $itemcount ++;
 7301:     } else {
 7302:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7303:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 7304:         my $currusecredits = 0;
 7305:         my $postsubmitclient = 1;
 7306:         my $ltiauth = 0;
 7307:         my @types = ('official','unofficial','community','textbook','placement');
 7308:         if (ref($settings) eq 'HASH') {
 7309:             if ($settings->{'ltiauth'}) {
 7310:                 $ltiauth = 1;
 7311:             }
 7312:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 7313:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 7314:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 7315:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 7316:                 }
 7317:             }
 7318:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 7319:                 foreach my $type (@types) {
 7320:                     next if ($type eq 'community');
 7321:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 7322:                     if ($defcredits{$type} ne '') {
 7323:                         $currusecredits = 1;
 7324:                     }
 7325:                 }
 7326:             }
 7327:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 7328:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 7329:                     $postsubmitclient = 0;
 7330:                     foreach my $type (@types) {
 7331:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7332:                     }
 7333:                 } else {
 7334:                     foreach my $type (@types) {
 7335:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 7336:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 7337:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 7338:                             } else {
 7339:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7340:                             }
 7341:                         } else {
 7342:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7343:                         }
 7344:                     }
 7345:                 }
 7346:             } else {
 7347:                 foreach my $type (@types) {
 7348:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7349:                 }
 7350:             }
 7351:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 7352:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 7353:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 7354:                 }
 7355:             } else {
 7356:                 foreach my $type (@types) {
 7357:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 7358:                 }
 7359:             }
 7360:         } else {
 7361:             foreach my $type (@types) {
 7362:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7363:             }
 7364:         }
 7365:         if (!$currdefresponder) {
 7366:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 7367:         } elsif ($currdefresponder < 1) {
 7368:             $currdefresponder = 1;
 7369:         }
 7370:         foreach my $type (@types) {
 7371:             if ($curruploadquota{$type} eq '') {
 7372:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 7373:             }
 7374:         }
 7375:         $datatable .=
 7376:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7377:                 $choices{'anonsurvey_threshold'}.
 7378:                 '</span></td>'.
 7379:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 7380:                 '<input type="text" name="anonsurvey_threshold"'.
 7381:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 7382:                 '</td></tr>'."\n";
 7383:         $itemcount ++;
 7384:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7385:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7386:                       $choices{'uploadquota'}.
 7387:                       '</span></td>'.
 7388:                       '<td style="text-align: right" class="LC_right_item">'.
 7389:                       '<table><tr>';
 7390:         foreach my $type (@types) {
 7391:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7392:                            '<input type="text" name="uploadquota_'.$type.'"'.
 7393:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 7394:         }
 7395:         $datatable .= '</tr></table></td></tr>'."\n";
 7396:         $itemcount ++;
 7397:         my $onclick = "toggleDisplay(this.form,'credits');";
 7398:         my $display = 'none';
 7399:         if ($currusecredits) {
 7400:             $display = 'block';
 7401:         }
 7402:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 7403:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 7404:         foreach my $type (@types) {
 7405:             next if ($type eq 'community');
 7406:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7407:                            '<input type="text" name="'.$type.'_credits"'.
 7408:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 7409:         }
 7410:         $additional .= '</tr></table></div>'."\n";
 7411:         %defaultchecked = ('coursecredits' => 'off');
 7412:         @toggles = ('coursecredits');
 7413:         my $current = {
 7414:                         'coursecredits' => $currusecredits,
 7415:                       };
 7416:         (my $table,$itemcount) =
 7417:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7418:                                \%choices,$itemcount,$onclick,$additional,'left');
 7419:         $datatable .= $table;
 7420:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 7421:         my $display = 'none';
 7422:         if ($postsubmitclient) {
 7423:             $display = 'block';
 7424:         }
 7425:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 7426:                       &mt('Number of seconds submit is disabled').'<br />'.
 7427:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 7428:                       '<table><tr>';
 7429:         foreach my $type (@types) {
 7430:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7431:                            '<input type="text" name="'.$type.'_timeout" value="'.
 7432:                            $deftimeout{$type}.'" size="5" /></td>';
 7433:         }
 7434:         $additional .= '</tr></table></div>'."\n";
 7435:         %defaultchecked = ('postsubmit' => 'on');
 7436:         @toggles = ('postsubmit');
 7437:         $current = {
 7438:                        'postsubmit' => $postsubmitclient,
 7439:                    };
 7440:         ($table,$itemcount) =
 7441:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7442:                                \%choices,$itemcount,$onclick,$additional,'left');
 7443:         $datatable .= $table;
 7444:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7445:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7446:                       $choices{'mysqltables'}.
 7447:                       '</span></td>'.
 7448:                       '<td style="text-align: right" class="LC_right_item">'.
 7449:                       '<table><tr>';
 7450:         foreach my $type (@types) {
 7451:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7452:                            '<input type="text" name="mysqltables_'.$type.'"'.
 7453:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 7454:         }
 7455:         $datatable .= '</tr></table></td></tr>'."\n";
 7456:         $itemcount ++;
 7457:         %defaultchecked = ('ltiauth' => 'off');
 7458:         @toggles = ('ltiauth');
 7459:         $current = {
 7460:                        'ltiauth' => $ltiauth,
 7461:                    };
 7462:         ($table,$itemcount) =
 7463:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7464:                                \%choices,$itemcount,undef,undef,'left');
 7465:         $datatable .= $table;
 7466:         $itemcount ++;
 7467:     }
 7468:     $$rowtotal += $itemcount;
 7469:     return $datatable;
 7470: }
 7471: 
 7472: sub print_selfenrollment {
 7473:     my ($position,$dom,$settings,$rowtotal) = @_;
 7474:     my ($css_class,$datatable);
 7475:     my $itemcount = 1;
 7476:     my @types = ('official','unofficial','community','textbook','placement');
 7477:     if (($position eq 'top') || ($position eq 'middle')) {
 7478:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 7479:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 7480:         my @rows;
 7481:         my $key;
 7482:         if ($position eq 'top') {
 7483:             $key = 'admin'; 
 7484:             if (ref($rowsref) eq 'ARRAY') {
 7485:                 @rows = @{$rowsref};
 7486:             }
 7487:         } elsif ($position eq 'middle') {
 7488:             $key = 'default';
 7489:             @rows = ('types','registered','approval','limit');
 7490:         }
 7491:         foreach my $row (@rows) {
 7492:             if (defined($titlesref->{$row})) {
 7493:                 $itemcount ++;
 7494:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7495:                 $datatable .= '<tr'.$css_class.'>'.
 7496:                               '<td>'.$titlesref->{$row}.'</td>'.
 7497:                               '<td class="LC_left_item">'.
 7498:                               '<table><tr>';
 7499:                 my (%current,%currentcap);
 7500:                 if (ref($settings) eq 'HASH') {
 7501:                     if (ref($settings->{$key}) eq 'HASH') {
 7502:                         foreach my $type (@types) {
 7503:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7504:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 7505:                             }
 7506:                             if (($row eq 'limit') && ($key eq 'default')) {
 7507:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7508:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 7509:                                 }
 7510:                             }
 7511:                         }
 7512:                     }
 7513:                 }
 7514:                 my %roles = (
 7515:                              '0' => &Apache::lonnet::plaintext('dc'),
 7516:                             ); 
 7517:             
 7518:                 foreach my $type (@types) {
 7519:                     unless (($row eq 'registered') && ($key eq 'default')) {
 7520:                         $datatable .= '<th>'.&mt($type).'</th>';
 7521:                     }
 7522:                 }
 7523:                 unless (($row eq 'registered') && ($key eq 'default')) {
 7524:                     $datatable .= '</tr><tr>';
 7525:                 }
 7526:                 foreach my $type (@types) {
 7527:                     if ($type eq 'community') {
 7528:                         $roles{'1'} = &mt('Community personnel');
 7529:                     } else {
 7530:                         $roles{'1'} = &mt('Course personnel');
 7531:                     }
 7532:                     $datatable .= '<td style="vertical-align: top">';
 7533:                     if ($position eq 'top') {
 7534:                         my %checked;
 7535:                         if ($current{$type} eq '0') {
 7536:                             $checked{'0'} = ' checked="checked"';
 7537:                         } else {
 7538:                             $checked{'1'} = ' checked="checked"';
 7539:                         }
 7540:                         foreach my $role ('1','0') {
 7541:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7542:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 7543:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 7544:                                           $roles{$role}.'</label></span> ';
 7545:                         }
 7546:                     } else {
 7547:                         if ($row eq 'types') {
 7548:                             my %checked;
 7549:                             if ($current{$type} =~ /^(all|dom)$/) {
 7550:                                 $checked{$1} = ' checked="checked"';
 7551:                             } else {
 7552:                                 $checked{''} = ' checked="checked"';
 7553:                             }
 7554:                             foreach my $val ('','dom','all') {
 7555:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7556:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7557:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7558:                             }
 7559:                         } elsif ($row eq 'registered') {
 7560:                             my %checked;
 7561:                             if ($current{$type} eq '1') {
 7562:                                 $checked{'1'} = ' checked="checked"';
 7563:                             } else {
 7564:                                 $checked{'0'} = ' checked="checked"';
 7565:                             }
 7566:                             foreach my $val ('0','1') {
 7567:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7568:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7569:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7570:                             }
 7571:                         } elsif ($row eq 'approval') {
 7572:                             my %checked;
 7573:                             if ($current{$type} =~ /^([12])$/) {
 7574:                                 $checked{$1} = ' checked="checked"';
 7575:                             } else {
 7576:                                 $checked{'0'} = ' checked="checked"';
 7577:                             }
 7578:                             for my $val (0..2) {
 7579:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7580:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7581:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7582:                             }
 7583:                         } elsif ($row eq 'limit') {
 7584:                             my %checked;
 7585:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 7586:                                 $checked{$1} = ' checked="checked"';
 7587:                             } else {
 7588:                                 $checked{'none'} = ' checked="checked"';
 7589:                             }
 7590:                             my $cap;
 7591:                             if ($currentcap{$type} =~ /^\d+$/) {
 7592:                                 $cap = $currentcap{$type};
 7593:                             }
 7594:                             foreach my $val ('none','allstudents','selfenrolled') {
 7595:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7596:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7597:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7598:                             }
 7599:                             $datatable .= '<br />'.
 7600:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 7601:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 7602:                                           '</span>'; 
 7603:                         }
 7604:                     }
 7605:                     $datatable .= '</td>';
 7606:                 }
 7607:                 $datatable .= '</tr>';
 7608:             }
 7609:             $datatable .= '</table></td></tr>';
 7610:         }
 7611:     } elsif ($position eq 'bottom') {
 7612:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 7613:     }
 7614:     $$rowtotal += $itemcount;
 7615:     return $datatable;
 7616: }
 7617: 
 7618: sub print_validation_rows {
 7619:     my ($caller,$dom,$settings,$rowtotal) = @_;
 7620:     my ($itemsref,$namesref,$fieldsref);
 7621:     if ($caller eq 'selfenroll') { 
 7622:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 7623:     } elsif ($caller eq 'requestcourses') {
 7624:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7625:     }
 7626:     my %currvalidation;
 7627:     if (ref($settings) eq 'HASH') {
 7628:         if (ref($settings->{'validation'}) eq 'HASH') {
 7629:             %currvalidation = %{$settings->{'validation'}};
 7630:         }
 7631:     }
 7632:     my $datatable;
 7633:     my $itemcount = 0;
 7634:     foreach my $item (@{$itemsref}) {
 7635:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7636:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7637:                       $namesref->{$item}.
 7638:                       '</span></td>'.
 7639:                       '<td class="LC_left_item">';
 7640:         if (($item eq 'url') || ($item eq 'button')) {
 7641:             $datatable .= '<span class="LC_nobreak">'.
 7642:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 7643:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 7644:         } elsif ($item eq 'fields') {
 7645:             my @currfields;
 7646:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 7647:                 @currfields = @{$currvalidation{$item}};
 7648:             }
 7649:             foreach my $field (@{$fieldsref}) {
 7650:                 my $check = '';
 7651:                 if (grep(/^\Q$field\E$/,@currfields)) {
 7652:                     $check = ' checked="checked"';
 7653:                 }
 7654:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7655:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 7656:                               ' value="'.$field.'"'.$check.' />'.$field.
 7657:                               '</label></span> ';
 7658:             }
 7659:         } elsif ($item eq 'markup') {
 7660:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 7661:                            $currvalidation{$item}.
 7662:                               '</textarea>';
 7663:         }
 7664:         $datatable .= '</td></tr>'."\n";
 7665:         if (ref($rowtotal)) {
 7666:             $itemcount ++;
 7667:         }
 7668:     }
 7669:     if ($caller eq 'requestcourses') {
 7670:         my %currhash;
 7671:         if (ref($settings) eq 'HASH') {
 7672:             if (ref($settings->{'validation'}) eq 'HASH') {
 7673:                 if ($settings->{'validation'}{'dc'} ne '') {
 7674:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 7675:                 }
 7676:             }
 7677:         }
 7678:         my $numinrow = 2;
 7679:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 7680:                                                        'validationdc',%currhash);
 7681:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7682:         $datatable .= '<tr'.$css_class.'><td>';
 7683:         if ($numdc > 1) {
 7684:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 7685:         } else {
 7686:             $datatable .=  &mt('Course creation processed as: ');
 7687:         }
 7688:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 7689:         $itemcount ++;
 7690:     }
 7691:     if (ref($rowtotal)) {
 7692:         $$rowtotal += $itemcount;
 7693:     }
 7694:     return $datatable;
 7695: }
 7696: 
 7697: sub print_privacy {
 7698:     my ($position,$dom,$settings,$rowtotal) = @_;
 7699:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 7700:     my $itemcount = 0;
 7701:     unless ($position eq 'top') {
 7702:         @items = ('domain','author','course','community');
 7703:         %names = &Apache::lonlocal::texthash (
 7704:                      domain => 'Assigned domain role(s)',
 7705:                      author => 'Assigned co-author role(s)',
 7706:                      course => 'Assigned course role(s)',
 7707:                      community => 'Assigned community role',
 7708:                  );
 7709:         $numinrow = 4;
 7710:         ($othertitle,$usertypes,$types) =
 7711:             &Apache::loncommon::sorted_inst_types($dom);
 7712:     }
 7713:     if (($position eq 'top') || ($position eq 'middle')) {
 7714:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7715:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7716:         if ($position eq 'top') {
 7717:             my %curr;
 7718:             my @options = ('none','user','domain','auto');
 7719:             my %titles = &Apache::lonlocal::texthash (
 7720:                 none   => 'Not allowed',
 7721:                 user   => 'User authorizes',
 7722:                 domain => 'DC authorizes',
 7723:                 auto   => 'Unrestricted',
 7724:                 instdom => 'Other domain shares institution/provider',
 7725:                 extdom => 'Other domain has different institution/provider',
 7726:             );
 7727:             my %names = &Apache::lonlocal::texthash (
 7728:                 domain => 'Domain role',
 7729:                 author => 'Co-author role',
 7730:                 course => 'Course role',
 7731:                 community => 'Community role',
 7732:             );
 7733:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7734:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7735:             foreach my $domtype ('instdom','extdom') {
 7736:                 my (%checked,$skip);
 7737:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7738:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 7739:                               '<td class="LC_left_item">';
 7740:                 if ($domtype eq 'instdom') {
 7741:                     unless (@instdoms > 1) {
 7742:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 7743:                         $skip = 1;
 7744:                     }
 7745:                 } elsif ($domtype eq 'extdom') {
 7746:                     if (keys(%by_location) == 0) {
 7747:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 7748:                         $skip = 1;
 7749:                     }
 7750:                 }
 7751:                 unless ($skip) {
 7752:                     foreach my $roletype ('domain','author','course','community') {
 7753:                         $checked{'auto'} = ' checked="checked"';
 7754:                         if (ref($settings) eq 'HASH') {
 7755:                             if (ref($settings->{approval}) eq 'HASH') {
 7756:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 7757:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 7758:                                         $checked{$1} = ' checked="checked"';
 7759:                                         $checked{'auto'} = '';
 7760:                                     }
 7761:                                 }
 7762:                             }
 7763:                         }
 7764:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 7765:                         foreach my $option (@options) {
 7766:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7767:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 7768:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7769:                                           '</label></span>&nbsp; ';
 7770:                         }
 7771:                         $datatable .= '</fieldset>';
 7772:                     }
 7773:                 }
 7774:                 $datatable .= '</td></tr>';
 7775:                 $itemcount ++;
 7776:             }
 7777:         } elsif ($position eq 'middle') {
 7778:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7779:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7780:                     foreach my $item (@{$types}) {
 7781:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 7782:                                                                $numinrow,$itemcount,'','','','','',
 7783:                                                                '',$usertypes->{$item});
 7784:                         $itemcount ++;
 7785:                     }
 7786:                 }
 7787:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 7788:                                                        $numinrow,$itemcount,'','','','','',
 7789:                                                        '',$othertitle);
 7790:                 $itemcount ++;
 7791:             } else {
 7792:                 my (@insttypes,%insttitles);
 7793:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7794:                     @insttypes = @{$types};
 7795:                     %insttitles = %{$usertypes};
 7796:                 }
 7797:                 foreach my $item (@insttypes,'default') {
 7798:                     my $title;
 7799:                     if ($item eq 'default') {
 7800:                         $title = $othertitle;
 7801:                     } else {
 7802:                         $title = $insttitles{$item};
 7803:                     }
 7804:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7805:                     $datatable .= '<tr'.$css_class.'>'.
 7806:                                   '<td class="LC_left_item">'.$title.'</td>'.
 7807:                                   '<td class="LC_left_item">'.
 7808:                                   &mt('Nothing to set here, as there are no other domains').
 7809:                                   '</td></tr>';
 7810:                     $itemcount ++;
 7811:                 }
 7812:             }
 7813:         }
 7814:     } else {
 7815:         my $prefix;
 7816:         if ($position eq 'lower') {
 7817:             $prefix = 'priv';
 7818:         } else {
 7819:             $prefix = 'unpriv';
 7820:         }
 7821:         foreach my $item (@items) {
 7822:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 7823:                                                    $numinrow,$itemcount,'','','','','',
 7824:                                                    '',$names{$item});
 7825:             $itemcount ++;
 7826:         }
 7827:     }
 7828:     if (ref($rowtotal)) {
 7829:         $$rowtotal += $itemcount;
 7830:     }
 7831:     return $datatable;
 7832: }
 7833: 
 7834: sub print_passwords {
 7835:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 7836:     my ($datatable,$css_class);
 7837:     my $itemcount = 0;
 7838:     my %titles = &Apache::lonlocal::texthash (
 7839:         captcha        => '"Forgot Password" CAPTCHA validation',
 7840:         link           => 'Reset link expiration (hours)',
 7841:         case           => 'Case-sensitive usernames/e-mail',
 7842:         prelink        => 'Information required (form 1)',
 7843:         postlink       => 'Information required (form 2)',
 7844:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 7845:         customtext     => 'Domain specific text (HTML)',
 7846:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 7847:         intauth_check  => 'Check bcrypt cost if authenticated',
 7848:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 7849:         permanent      => 'Permanent e-mail address',
 7850:         critical       => 'Critical notification address',
 7851:         notify         => 'Notification address',
 7852:         min            => 'Minimum password length',
 7853:         max            => 'Maximum password length',
 7854:         chars          => 'Required characters',
 7855:         expire         => 'Password expiration (days)',
 7856:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 7857:     );
 7858:     if ($position eq 'top') {
 7859:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7860:         my $shownlinklife = 2;
 7861:         my $prelink = 'both';
 7862:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 7863:         if (ref($settings) eq 'HASH') {
 7864:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 7865:                 $shownlinklife = $settings->{resetlink};
 7866:             }
 7867:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 7868:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 7869:             }
 7870:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 7871:                 $prelink = $settings->{resetprelink};
 7872:             }
 7873:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 7874:                 %postlink = %{$settings->{resetpostlink}};
 7875:             }
 7876:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 7877:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 7878:             }
 7879:             if ($settings->{resetremove}) {
 7880:                 $nostdtext = 1;
 7881:             }
 7882:             if ($settings->{resetcustom}) {
 7883:                 $customurl = $settings->{resetcustom};
 7884:             }
 7885:         } else {
 7886:             if (ref($types) eq 'ARRAY') {
 7887:                 foreach my $item (@{$types}) {
 7888:                     $casesens{$item} = 1;
 7889:                     $postlink{$item} = ['username','email'];
 7890:                 }
 7891:             }
 7892:             $casesens{'default'} = 1;
 7893:             $postlink{'default'} = ['username','email'];
 7894:             $prelink = 'both';
 7895:             %emailsrc = (
 7896:                           permanent => 1,
 7897:                           critical  => 1,
 7898:                           notify    => 1,
 7899:             );
 7900:         }
 7901:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 7902:         $itemcount ++;
 7903:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7904:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 7905:                       '<td class="LC_left_item">'.
 7906:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 7907:                       'name="passwords_link" size="3" /></td></tr>';
 7908:         $itemcount ++;
 7909:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7910:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 7911:                       '<td class="LC_left_item">';
 7912:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7913:             foreach my $item (@{$types}) {
 7914:                 my $checkedcase;
 7915:                 if ($casesens{$item}) {
 7916:                     $checkedcase = ' checked="checked"';
 7917:                 }
 7918:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7919:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 7920:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 7921:                               '</span>&nbsp;&nbsp; ';
 7922:             }
 7923:         }
 7924:         my $checkedcase;
 7925:         if ($casesens{'default'}) {
 7926:             $checkedcase = ' checked="checked"';
 7927:         }
 7928:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7929:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 7930:                       $othertitle.'</label></span></td>';
 7931:         $itemcount ++;
 7932:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7933:         my %checkedpre = (
 7934:                              both => ' checked="checked"',
 7935:                              either => '',
 7936:                          );
 7937:         if ($prelink eq 'either') {
 7938:             $checkedpre{either} = ' checked="checked"';
 7939:             $checkedpre{both} = '';
 7940:         }
 7941:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 7942:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7943:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 7944:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 7945:                       '<span class="LC_nobreak"><label>'.
 7946:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 7947:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 7948:         $itemcount ++;
 7949:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7950:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 7951:                       '<td class="LC_left_item">';
 7952:         my %postlinked;
 7953:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7954:             foreach my $item (@{$types}) {
 7955:                 undef(%postlinked);
 7956:                 $datatable .= '<fieldset style="display: inline-block;">'.
 7957:                               '<legend>'.$usertypes->{$item}.'</legend>';
 7958:                 if (ref($postlink{$item}) eq 'ARRAY') {
 7959:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 7960:                 }
 7961:                 foreach my $field ('email','username') {
 7962:                     my $checked;
 7963:                     if ($postlinked{$field}) {
 7964:                         $checked = ' checked="checked"';
 7965:                     }
 7966:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7967:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 7968:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 7969:                                   '<span>&nbsp;&nbsp; ';
 7970:                 }
 7971:                 $datatable .= '</fieldset>';
 7972:             }
 7973:         }
 7974:         if (ref($postlink{'default'}) eq 'ARRAY') {
 7975:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 7976:         }
 7977:         $datatable .= '<fieldset style="display: inline-block;">'.
 7978:                       '<legend>'.$othertitle.'</legend>';
 7979:         foreach my $field ('email','username') {
 7980:             my $checked;
 7981:             if ($postlinked{$field}) {
 7982:                 $checked = ' checked="checked"';
 7983:             }
 7984:             $datatable .= '<span class="LC_nobreak"><label>'.
 7985:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 7986:                           $field.'"'.$checked.' />'.$field.'</label>'.
 7987:                           '<span>&nbsp;&nbsp; ';
 7988:         }
 7989:         $datatable .= '</fieldset></td></tr>';
 7990:         $itemcount ++;
 7991:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7992:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 7993:                       '<td class="LC_left_item">';
 7994:         foreach my $type ('permanent','critical','notify') {
 7995:             my $checkedemail;
 7996:             if ($emailsrc{$type}) {
 7997:                 $checkedemail = ' checked="checked"';
 7998:             }
 7999:             $datatable .= '<span class="LC_nobreak"><label>'.
 8000:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 8001:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 8002:                           '<span>&nbsp;&nbsp; ';
 8003:         }
 8004:         $datatable .= '</td></tr>';
 8005:         $itemcount ++;
 8006:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8007:         my $switchserver = &check_switchserver($dom,$confname);
 8008:         my ($showstd,$noshowstd);
 8009:         if ($nostdtext) {
 8010:             $noshowstd = ' checked="checked"';
 8011:         } else {
 8012:             $showstd = ' checked="checked"';
 8013:         }
 8014:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 8015:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8016:                       &mt('Retain standard text:').
 8017:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 8018:                       &mt('Yes').'</label>'.'&nbsp;'.
 8019:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 8020:                       &mt('No').'</label></span><br />'.
 8021:                       '<span class="LC_fontsize_small">'.
 8022:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 8023:                       &mt('Include custom text:');
 8024:         if ($customurl) {
 8025:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 8026:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8027:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 8028:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 8029:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 8030:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 8031:         }
 8032:         if ($switchserver) {
 8033:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 8034:         } else {
 8035:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8036:                          '<input type="file" name="passwords_customfile" /></span>';
 8037:         }
 8038:         $datatable .= '</td></tr>';
 8039:     } elsif ($position eq 'middle') {
 8040:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 8041:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 8042:         my %defaults;
 8043:         if (ref($domconf{'defaults'}) eq 'HASH') {
 8044:             %defaults = %{$domconf{'defaults'}};
 8045:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 8046:                 $defaults{'intauth_cost'} = 10;
 8047:             }
 8048:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 8049:                 $defaults{'intauth_check'} = 0;
 8050:             }
 8051:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 8052:                 $defaults{'intauth_switch'} = 0;
 8053:             }
 8054:         } else {
 8055:             %defaults = (
 8056:                           'intauth_cost'   => 10,
 8057:                           'intauth_check'  => 0,
 8058:                           'intauth_switch' => 0,
 8059:                         );
 8060:         }
 8061:         foreach my $item (@items) {
 8062:             if ($itemcount%2) {
 8063:                 $css_class = '';
 8064:             } else {
 8065:                 $css_class = ' class="LC_odd_row" ';
 8066:             }
 8067:             $datatable .= '<tr'.$css_class.'>'.
 8068:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 8069:                           '</span></td><td class="LC_left_item" colspan="3">';
 8070:             if ($item eq 'intauth_switch') {
 8071:                 my @options = (0,1,2);
 8072:                 my %optiondesc = &Apache::lonlocal::texthash (
 8073:                                    0 => 'No',
 8074:                                    1 => 'Yes',
 8075:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 8076:                                  );
 8077:                 $datatable .= '<table width="100%">';
 8078:                 foreach my $option (@options) {
 8079:                     my $checked = ' ';
 8080:                     if ($defaults{$item} eq $option) {
 8081:                         $checked = ' checked="checked"';
 8082:                     }
 8083:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8084:                                   '<label><input type="radio" name="'.$item.
 8085:                                   '" value="'.$option.'"'.$checked.' />'.
 8086:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8087:                 }
 8088:                 $datatable .= '</table>';
 8089:             } elsif ($item eq 'intauth_check') {
 8090:                 my @options = (0,1,2);
 8091:                 my %optiondesc = &Apache::lonlocal::texthash (
 8092:                                    0 => 'No',
 8093:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 8094:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 8095:                                  );
 8096:                 $datatable .= '<table width="100%">';
 8097:                 foreach my $option (@options) {
 8098:                     my $checked = ' ';
 8099:                     my $onclick;
 8100:                     if ($defaults{$item} eq $option) {
 8101:                         $checked = ' checked="checked"';
 8102:                     }
 8103:                     if ($option == 2) {
 8104:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 8105:                     }
 8106:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8107:                                   '<label><input type="radio" name="'.$item.
 8108:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 8109:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8110:                 }
 8111:                 $datatable .= '</table>';
 8112:             } else {
 8113:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8114:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 8115:             }
 8116:             $datatable .= '</td></tr>';
 8117:             $itemcount ++;
 8118:         }
 8119:     } elsif ($position eq 'lower') {
 8120:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 8121:     } else {
 8122:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8123:         my %ownerchg = (
 8124:                           by  => {},
 8125:                           for => {},
 8126:                        );
 8127:         my %ownertitles = &Apache::lonlocal::texthash (
 8128:                             by  => 'Course owner status(es) allowed',
 8129:                             for => 'Student status(es) allowed',
 8130:                           );
 8131:         if (ref($settings) eq 'HASH') {
 8132:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 8133:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 8134:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 8135:                 }
 8136:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 8137:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 8138:                 }
 8139:             }
 8140:         }
 8141:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8142:         $datatable .= '<tr '.$css_class.'>'.
 8143:                       '<td>'.
 8144:                       &mt('Requirements').'<ul>'.
 8145:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 8146:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 8147:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 8148:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 8149:                       '</ul>'.
 8150:                       '</td>'.
 8151:                       '<td class="LC_left_item">';
 8152:         foreach my $item ('by','for') {
 8153:             $datatable .= '<fieldset style="display: inline-block;">'.
 8154:                           '<legend>'.$ownertitles{$item}.'</legend>';
 8155:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8156:                 foreach my $type (@{$types}) {
 8157:                     my $checked;
 8158:                     if ($ownerchg{$item}{$type}) {
 8159:                         $checked = ' checked="checked"';
 8160:                     }
 8161:                     $datatable .= '<span class="LC_nobreak"><label>'.
 8162:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 8163:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 8164:                                   '</span>&nbsp;&nbsp; ';
 8165:                 }
 8166:             }
 8167:             my $checked;
 8168:             if ($ownerchg{$item}{'default'}) {
 8169:                 $checked = ' checked="checked"';
 8170:             }
 8171:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 8172:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 8173:                           $othertitle.'</label></span></fieldset>';
 8174:         }
 8175:         $datatable .= '</td></tr>';
 8176:     }
 8177:     return $datatable;
 8178: }
 8179: 
 8180: sub password_rules {
 8181:     my ($prefix,$itemcountref,$settings) = @_;
 8182:     my ($min,$max,%chars,$expire,$numsaved,$numinrow);
 8183:     my %titles;
 8184:     if ($prefix eq 'passwords') {
 8185:         %titles = &Apache::lonlocal::texthash (
 8186:             min            => 'Minimum password length',
 8187:             max            => 'Maximum password length',
 8188:             chars          => 'Required characters',
 8189:         );
 8190:     } elsif ($prefix eq 'secrets') {
 8191:         %titles = &Apache::lonlocal::texthash (
 8192:             min            => 'Minimum secret length',
 8193:             max            => 'Maximum secret length',
 8194:             chars          => 'Required characters',
 8195:         );
 8196:     }
 8197:     $min = $Apache::lonnet::passwdmin;
 8198:     my $datatable;
 8199:     my $itemcount;
 8200:     if (ref($itemcountref)) {
 8201:         $itemcount = $$itemcountref;
 8202:     }
 8203:     if (ref($settings) eq 'HASH') {
 8204:         if ($settings->{min}) {
 8205:             $min = $settings->{min};
 8206:         }
 8207:         if ($settings->{max}) {
 8208:             $max = $settings->{max};
 8209:         }
 8210:         if (ref($settings->{chars}) eq 'ARRAY') {
 8211:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 8212:         }
 8213:         if ($prefix eq 'passwords') { 
 8214:             if ($settings->{expire}) {
 8215:                 $expire = $settings->{expire};
 8216:             }
 8217:             if ($settings->{numsaved}) {
 8218:                 $numsaved = $settings->{numsaved};
 8219:             }
 8220:         }
 8221:     }
 8222:     my %rulenames = &Apache::lonlocal::texthash(
 8223:                                                  uc => 'At least one upper case letter',
 8224:                                                  lc => 'At least one lower case letter',
 8225:                                                  num => 'At least one number',
 8226:                                                  spec => 'At least one non-alphanumeric',
 8227:                                                );
 8228:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8229:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 8230:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8231:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 8232:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8233:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 8234:                   '</span></td></tr>';
 8235:     $itemcount ++;
 8236:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8237:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 8238:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8239:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 8240:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8241:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 8242:                   '</span></td></tr>';
 8243:     $itemcount ++;
 8244:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8245:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 8246:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 8247:                   '</span></td>';
 8248:     my $numinrow = 2;
 8249:     my @possrules = ('uc','lc','num','spec');
 8250:     $datatable .= '<td class="LC_left_item"><table>';
 8251:     for (my $i=0; $i<@possrules; $i++) {
 8252:         my ($rem,$checked);
 8253:         if ($chars{$possrules[$i]}) {
 8254:             $checked = ' checked="checked"';
 8255:         }
 8256:         $rem = $i%($numinrow);
 8257:         if ($rem == 0) {
 8258:             if ($i > 0) {
 8259:                 $datatable .= '</tr>';
 8260:             }
 8261:             $datatable .= '<tr>';
 8262:         }
 8263:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 8264:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 8265:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 8266:     }
 8267:     my $rem = @possrules%($numinrow);
 8268:     my $colsleft = $numinrow - $rem;
 8269:     if ($colsleft > 1 ) {
 8270:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8271:                       '&nbsp;</td>';
 8272:     } elsif ($colsleft == 1) {
 8273:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8274:     }
 8275:     $datatable .='</table></td></tr>';
 8276:     $itemcount ++;
 8277:     if ($prefix eq 'passwords') {
 8278:         $titles{'expire'} = &mt('Password expiration (days)');
 8279:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 8280:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8281:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 8282:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8283:                       '<input type="text" name="'.$prefix.'_expire" value="'.$expire.'" size="4" '.
 8284:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8285:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 8286:                       '</span></td></tr>';
 8287:         $itemcount ++;
 8288:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8289:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 8290:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8291:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 8292:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8293:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 8294:                       '</span></td></tr>';
 8295:         $itemcount ++;
 8296:     }
 8297:     if (ref($itemcountref)) {
 8298:         $$itemcountref += $itemcount;
 8299:     }
 8300:     return $datatable;
 8301: }
 8302: 
 8303: sub print_wafproxy {
 8304:     my ($position,$dom,$settings,$rowtotal) = @_;
 8305:     my $css_class;
 8306:     my $itemcount = 0;
 8307:     my $datatable;
 8308:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8309:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 8310:     my %lt = &wafproxy_titles();
 8311:     foreach my $server (sort(keys(%servers))) {
 8312:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 8313:         next if ($serverhome eq '');
 8314:         my $serverdom;
 8315:         if ($serverhome ne $server) {
 8316:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 8317:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 8318:                 $othercontrol{$server} = $serverdom;
 8319:             }
 8320:         } else {
 8321:             $serverdom = &Apache::lonnet::host_domain($server);
 8322:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 8323:             if ($serverdom ne $dom) {
 8324:                 $othercontrol{$server} = $serverdom;
 8325:             } else {
 8326:                 $setdom = 1;
 8327:                 if (ref($settings) eq 'HASH') {
 8328:                     if (ref($settings->{'alias'}) eq 'HASH') {
 8329:                         $aliases{$dom} = $settings->{'alias'};
 8330:                         if ($aliases{$dom} ne '') {
 8331:                             $showdom = 1;
 8332:                         }
 8333:                     }
 8334:                     if (ref($settings->{'saml'}) eq 'HASH') {
 8335:                         $saml{$dom} = $settings->{'saml'};
 8336:                     }
 8337:                 }
 8338:             }
 8339:         }
 8340:     }
 8341:     if ($setdom) {
 8342:         %{$values{$dom}} = ();
 8343:         if (ref($settings) eq 'HASH') {
 8344:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8345:                 $values{$dom}{$item} = $settings->{$item};
 8346:             }
 8347:         }
 8348:     }
 8349:     if (keys(%othercontrol)) {
 8350:         %otherdoms = reverse(%othercontrol);
 8351:         foreach my $domain (keys(%otherdoms)) {
 8352:             %{$values{$domain}} = ();
 8353:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 8354:             if (ref($config{'wafproxy'}) eq 'HASH') {
 8355:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 8356:                 if (exists($config{'wafproxy'}{'saml'})) { 
 8357:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 8358:                 }
 8359:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8360:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 8361:                 }
 8362:             }
 8363:         }
 8364:     }
 8365:     if ($position eq 'top') {
 8366:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8367:         my %aliasinfo;
 8368:         foreach my $server (sort(keys(%servers))) {
 8369:             $itemcount ++;
 8370:             my $dom_in_effect;
 8371:             my $aliasrows = '<tr>'.
 8372:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8373:                             &mt('Hostname').':&nbsp;'.
 8374:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 8375:             if ($othercontrol{$server}) {
 8376:                 $dom_in_effect = $othercontrol{$server};
 8377:                 my ($current,$forsaml);
 8378:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 8379:                     $current = $aliases{$dom_in_effect}{$server};
 8380:                 }
 8381:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 8382:                     if ($saml{$dom_in_effect}{$server}) {
 8383:                         $forsaml = 1;
 8384:                     }
 8385:                 }
 8386:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8387:                               &mt('Alias').':&nbsp';
 8388:                 if ($current) {
 8389:                     $aliasrows .= $current;
 8390:                     if ($forsaml) {
 8391:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 8392:                     }
 8393:                 } else {
 8394:                     $aliasrows .= &mt('None');
 8395:                 }
 8396:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 8397:                               &mt('controlled by domain: [_1]',
 8398:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 8399:             } else {
 8400:                 $dom_in_effect = $dom;
 8401:                 my ($current,$samlon,$samloff);
 8402:                 $samloff = ' checked="checked"';
 8403:                 if (ref($aliases{$dom}) eq 'HASH') {
 8404:                     if ($aliases{$dom}{$server}) {
 8405:                         $current = $aliases{$dom}{$server};
 8406:                     }
 8407:                 }
 8408:                 if (ref($saml{$dom}) eq 'HASH') {
 8409:                     if ($saml{$dom}{$server}) {
 8410:                         $samlon = $samloff;
 8411:                         undef($samloff);
 8412:                     }
 8413:                 }
 8414:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8415:                               &mt('Alias').':&nbsp;'.
 8416:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 8417:                               'value="'.$current.'" size="30" />'.
 8418:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 8419:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 8420:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 8421:                               &mt('No').'</label>&nbsp;<label>'. 
 8422:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 8423:                               &mt('Yes').'</label></span>'.
 8424:                               '</td>'; 
 8425:             }
 8426:             $aliasrows .= '</tr>';
 8427:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 8428:         }
 8429:         if ($aliasinfo{$dom}) {
 8430:             my ($onclick,$wafon,$wafoff,$showtable);
 8431:             $onclick = ' onclick="javascript:toggleWAF();"';
 8432:             $wafoff = ' checked="checked"';
 8433:             $showtable = ' style="display:none";';
 8434:             if ($showdom) {
 8435:                 $wafon = $wafoff;
 8436:                 $wafoff = '';
 8437:                 $showtable = ' style="display:inline;"';
 8438:             }
 8439:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8440:             $datatable = '<tr'.$css_class.'>'.
 8441:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 8442:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 8443:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 8444:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 8445:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 8446:                          &mt('No').'</label></span></td>'.
 8447:                          '<td class="LC_left_item">'.
 8448:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 8449:                          '</table></td></tr>';
 8450:             $itemcount++;
 8451:         }
 8452:         if (keys(%otherdoms)) {
 8453:             foreach my $key (sort(keys(%otherdoms))) {
 8454:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8455:                 $datatable .= '<tr'.$css_class.'>'.
 8456:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 8457:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 8458:                               '</table></td></tr>';
 8459:                 $itemcount++;
 8460:             }
 8461:         }
 8462:     } else {
 8463:         my %ip_methods = &remoteip_methods();
 8464:         if ($setdom) {
 8465:             $itemcount ++;
 8466:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8467:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 8468:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 8469:             $wafstyle = ' style="display:none;"';
 8470:             $nowafstyle = ' style="display:table-row;"';
 8471:             $currwafdisplay = ' style="display: none"';
 8472:             $wafrangestyle = ' style="display: none"';
 8473:             $curr_remotip = 'n';
 8474:             $ssltossl = ' checked="checked"';
 8475:             if ($showdom) {
 8476:                 $wafstyle = ' style="display:table-row;"';
 8477:                 $nowafstyle =  ' style="display:none;"';
 8478:                 if (keys(%{$values{$dom}})) {
 8479:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 8480:                         $curr_remotip = $values{$dom}{remoteip};
 8481:                     }
 8482:                     if ($curr_remotip eq 'h') {
 8483:                         $currwafdisplay = ' style="display:table-row"';
 8484:                         $wafrangestyle = ' style="display:inline-block;"';
 8485:                     }
 8486:                     if ($values{$dom}{'sslopt'}) {
 8487:                         $alltossl = ' checked="checked"';
 8488:                         $ssltossl = '';
 8489:                     }
 8490:                 }
 8491:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 8492:                     $vpndircheck = ' checked="checked"';
 8493:                     $currwafvpn = ' style="display:table-row;"';
 8494:                     $wafrangestyle = ' style="display:inline-block;"';
 8495:                 } else {
 8496:                     $vpnaliascheck = ' checked="checked"';
 8497:                     $currwafvpn = ' style="display:none;"';
 8498:                 }
 8499:             }
 8500:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8501:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 8502:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 8503:                           '</tr>'.
 8504:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8505:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 8506:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 8507:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 8508:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 8509:                           '<td class="LC_left_item"><table>'.
 8510:                           '<tr>'.
 8511:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 8512:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 8513:             foreach my $option ('m','h','n') {
 8514:                 my $sel;
 8515:                 if ($option eq $curr_remotip) {
 8516:                    $sel = ' selected="selected"';
 8517:                 }
 8518:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 8519:                               $ip_methods{$option}.'</option>';
 8520:             }
 8521:             $datatable .= '</select></td></tr>'."\n".
 8522:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 8523:                           $lt{'ipheader'}.':&nbsp;'.
 8524:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 8525:                           'name="wafproxy_ipheader" />'.
 8526:                           '</td></tr>'."\n".
 8527:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 8528:                           $lt{'trusted'}.':<br />'.
 8529:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 8530:                           $values{$dom}{'trusted'}.'</textarea>'.
 8531:                           '</td></tr>'."\n".
 8532:                           '<tr><td><hr /></td></tr>'."\n".
 8533:                           '<tr>'.
 8534:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 8535:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 8536:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 8537:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 8538:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 8539:             foreach my $item ('vpnint','vpnext') {
 8540:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 8541:                               '<td valign="top">'.$lt{$item}.':<br />'.
 8542:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 8543:                               $values{$dom}{$item}.'</textarea>'.
 8544:                               '</td></tr>'."\n";
 8545:             }
 8546:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 8547:                           '<tr>'.
 8548:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 8549:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 8550:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 8551:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 8552:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 8553:                           '</table></td></tr>';
 8554:         }
 8555:         if (keys(%otherdoms)) {
 8556:             foreach my $domain (sort(keys(%otherdoms))) {
 8557:                 $itemcount ++;
 8558:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8559:                 $datatable .= '<tr'.$css_class.'>'.
 8560:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 8561:                               '<td class="LC_left_item"><table>';
 8562:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 8563:                     my $showval = &mt('None');
 8564:                     if ($item eq 'ssl') {
 8565:                         $showval = $lt{'ssltossl'};
 8566:                     }
 8567:                     if ($values{$domain}{$item}) {
 8568:                         $showval = $values{$domain}{$item};
 8569:                         if ($item eq 'ssl') {
 8570:                             $showval = $lt{'alltossl'};
 8571:                         } elsif ($item eq 'remoteip') {
 8572:                             $showval = $ip_methods{$values{$domain}{$item}};
 8573:                         }
 8574:                     }
 8575:                     $datatable .= '<tr>'.
 8576:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 8577:                 }
 8578:                 $datatable .= '</table></td></tr>';
 8579:             }
 8580:         }
 8581:     }
 8582:     $$rowtotal += $itemcount;
 8583:     return $datatable;
 8584: }
 8585: 
 8586: sub wafproxy_titles {
 8587:     return &Apache::lonlocal::texthash(
 8588:                remoteip   => "Method for determining user's IP",
 8589:                ipheader   => 'Request header containing remote IP',
 8590:                trusted    => 'Trusted IP range(s)',
 8591:                vpnaccess  => 'Access from institutional VPN',
 8592:                vpndirect  => 'via regular hostname (no WAF)',
 8593:                vpnaliased => 'via aliased hostname (WAF)',
 8594:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 8595:                vpnext     => 'IP Range(s) for backend WAF connections',
 8596:                sslopt     => 'Forwarding http/https',
 8597:                alltossl   => 'WAF forwards both http and https requests to https',
 8598:                ssltossl   => 'WAF forwards http requests to http and https to https',
 8599:            );
 8600: }
 8601: 
 8602: sub remoteip_methods {
 8603:     return &Apache::lonlocal::texthash(
 8604:               m => 'Use Apache mod_remoteip',
 8605:               h => 'Use headers parsed by LON-CAPA',
 8606:               n => 'Not in use',
 8607:            );
 8608: }
 8609: 
 8610: sub print_usersessions {
 8611:     my ($position,$dom,$settings,$rowtotal) = @_;
 8612:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 8613:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8614:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8615: 
 8616:     my @alldoms = &Apache::lonnet::all_domains();
 8617:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8618:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8619:     my %altids = &id_for_thisdom(%servers);
 8620:     if ($position eq 'top') {
 8621:         if (keys(%serverhomes) > 1) {
 8622:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 8623:             my ($curroffloadnow,$curroffloadoth);
 8624:             if (ref($settings) eq 'HASH') {
 8625:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 8626:                     $curroffloadnow = $settings->{'offloadnow'};
 8627:                 }
 8628:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 8629:                     $curroffloadoth = $settings->{'offloadoth'};
 8630:                 }
 8631:             }
 8632:             my $other_insts = scalar(keys(%by_location));
 8633:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 8634:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 8635:         } else {
 8636:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 8637:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 8638:                           '</td></tr>';
 8639:         }
 8640:     } else {
 8641:         my %titles = &usersession_titles();
 8642:         my ($prefix,@types);
 8643:         if ($position eq 'bottom') {
 8644:             $prefix = 'remote';
 8645:             @types = ('version','excludedomain','includedomain');
 8646:         } else {
 8647:             $prefix = 'hosted';
 8648:             @types = ('excludedomain','includedomain');
 8649:         }
 8650:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8651:     }
 8652:     $$rowtotal += $itemcount;
 8653:     return $datatable;
 8654: }
 8655: 
 8656: sub rules_by_location {
 8657:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 8658:     my ($datatable,$itemcount,$css_class);
 8659:     if (keys(%{$by_location}) == 0) {
 8660:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8661:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 8662:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 8663:                      '</td></tr>';
 8664:         $itemcount = 1;
 8665:     } else {
 8666:         $itemcount = 0;
 8667:         my $numinrow = 5;
 8668:         my (%current,%checkedon,%checkedoff);
 8669:         my @locations = sort(keys(%{$by_location}));
 8670:         foreach my $type (@{$types}) {
 8671:             $checkedon{$type} = '';
 8672:             $checkedoff{$type} = ' checked="checked"';
 8673:         }
 8674:         if (ref($settings) eq 'HASH') {
 8675:             if (ref($settings->{$prefix}) eq 'HASH') {
 8676:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 8677:                     $current{$key} = $settings->{$prefix}{$key};
 8678:                     if ($key eq 'version') {
 8679:                         if ($current{$key} ne '') {
 8680:                             $checkedon{$key} = ' checked="checked"';
 8681:                             $checkedoff{$key} = '';
 8682:                         }
 8683:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 8684:                         $checkedon{$key} = ' checked="checked"';
 8685:                         $checkedoff{$key} = '';
 8686:                     }
 8687:                 }
 8688:             }
 8689:         }
 8690:         foreach my $type (@{$types}) {
 8691:             next if ($type ne 'version' && !@locations);
 8692:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8693:             $datatable .= '<tr'.$css_class.'>
 8694:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 8695:                            <span class="LC_nobreak">&nbsp;
 8696:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 8697:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 8698:             if ($type eq 'version') {
 8699:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 8700:                 my $selector = '<select name="'.$prefix.'_version">';
 8701:                 foreach my $version (@lcversions) {
 8702:                     my $selected = '';
 8703:                     if ($current{'version'} eq $version) {
 8704:                         $selected = ' selected="selected"';
 8705:                     }
 8706:                     $selector .= ' <option value="'.$version.'"'.
 8707:                                  $selected.'>'.$version.'</option>';
 8708:                 }
 8709:                 $selector .= '</select> ';
 8710:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 8711:             } else {
 8712:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 8713:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 8714:                              ' />'.('&nbsp;'x2).
 8715:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 8716:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 8717:                              "\n".
 8718:                              '</div><div><table>';
 8719:                 my $rem;
 8720:                 for (my $i=0; $i<@locations; $i++) {
 8721:                     my ($showloc,$value,$checkedtype);
 8722:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 8723:                         my $ip = $by_location->{$locations[$i]}->[0];
 8724:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8725:                             $value = join(':',@{$by_ip->{$ip}});
 8726:                             $showloc = join(', ',@{$by_ip->{$ip}});
 8727:                             if (ref($current{$type}) eq 'ARRAY') {
 8728:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 8729:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 8730:                                         $checkedtype = ' checked="checked"';
 8731:                                         last;
 8732:                                     }
 8733:                                 }
 8734:                             }
 8735:                         }
 8736:                     }
 8737:                     $rem = $i%($numinrow);
 8738:                     if ($rem == 0) {
 8739:                         if ($i > 0) {
 8740:                             $datatable .= '</tr>';
 8741:                         }
 8742:                         $datatable .= '<tr>';
 8743:                     }
 8744:                     $datatable .= '<td class="LC_left_item">'.
 8745:                                   '<span class="LC_nobreak"><label>'.
 8746:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 8747:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 8748:                                   '</label></span></td>';
 8749:                 }
 8750:                 $rem = @locations%($numinrow);
 8751:                 my $colsleft = $numinrow - $rem;
 8752:                 if ($colsleft > 1 ) {
 8753:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8754:                                   '&nbsp;</td>';
 8755:                 } elsif ($colsleft == 1) {
 8756:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8757:                 }
 8758:                 $datatable .= '</tr></table>';
 8759:             }
 8760:             $datatable .= '</td></tr>';
 8761:             $itemcount ++;
 8762:         }
 8763:     }
 8764:     return ($datatable,$itemcount);
 8765: }
 8766: 
 8767: sub print_ssl {
 8768:     my ($position,$dom,$settings,$rowtotal) = @_;
 8769:     my ($css_class,$datatable);
 8770:     my $itemcount = 1;
 8771:     if ($position eq 'top') {
 8772:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8773:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8774:         my $same_institution;
 8775:         if ($intdom ne '') {
 8776:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 8777:             if (ref($internet_names) eq 'ARRAY') {
 8778:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8779:                     $same_institution = 1;
 8780:                 }
 8781:             }
 8782:         }
 8783:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8784:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 8785:         if ($same_institution) {
 8786:             my %domservers = &Apache::lonnet::get_servers($dom);
 8787:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 8788:         } else {
 8789:             $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.");
 8790:         }
 8791:         $datatable .= '</td></tr>';
 8792:         $itemcount ++;
 8793:     } else {
 8794:         my %titles = &ssl_titles();
 8795:         my (%by_ip,%by_location,@intdoms,@instdoms);
 8796:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8797:         my @alldoms = &Apache::lonnet::all_domains();
 8798:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8799:         my @domservers = &Apache::lonnet::get_servers($dom);
 8800:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8801:         my %altids = &id_for_thisdom(%servers);
 8802:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 8803:             my $legacy;
 8804:             unless (ref($settings) eq 'HASH') {
 8805:                 my $name;
 8806:                 if ($position eq 'connto') {
 8807:                     $name = 'loncAllowInsecure';
 8808:                 } else {
 8809:                     $name = 'londAllowInsecure';
 8810:                 }
 8811:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 8812:                 my @ids=&Apache::lonnet::current_machine_ids();
 8813:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 8814:                     my %what = (
 8815:                                    $name => 1,
 8816:                                );
 8817:                     my ($result,$returnhash) =
 8818:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8819:                     if ($result eq 'ok') {
 8820:                         if (ref($returnhash) eq 'HASH') {
 8821:                             $legacy = $returnhash->{$name};
 8822:                         }
 8823:                     }
 8824:                 } else {
 8825:                     $legacy = $Apache::lonnet::perlvar{$name};
 8826:                 }
 8827:             }
 8828:             foreach my $type ('dom','intdom','other') {
 8829:                 my %checked;
 8830:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8831:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8832:                               '<td class="LC_right_item">';
 8833:                 my $skip; 
 8834:                 if ($type eq 'dom') {
 8835:                     unless (keys(%servers) > 1) {
 8836:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8837:                         $skip = 1;
 8838:                     }
 8839:                 }
 8840:                 if ($type eq 'intdom') {
 8841:                     unless (@instdoms > 1) {
 8842:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8843:                         $skip = 1;
 8844:                     } 
 8845:                 } elsif ($type eq 'other') {
 8846:                     if (keys(%by_location) == 0) {
 8847:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8848:                         $skip = 1;
 8849:                     }
 8850:                 }
 8851:                 unless ($skip) {
 8852:                     $checked{'yes'} = ' checked="checked"'; 
 8853:                     if (ref($settings) eq 'HASH') {
 8854:                         if (ref($settings->{$position}) eq 'HASH') {
 8855:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8856:                                 $checked{$1} = $checked{'yes'};
 8857:                                 delete($checked{'yes'}); 
 8858:                             }
 8859:                         }
 8860:                     } else {
 8861:                         if ($legacy == 0) {
 8862:                             $checked{'req'} = $checked{'yes'};
 8863:                             delete($checked{'yes'});    
 8864:                         }
 8865:                     }
 8866:                     foreach my $option ('no','yes','req') {
 8867:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8868:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8869:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8870:                                       '</label></span>'.('&nbsp;'x2);
 8871:                     }
 8872:                 }
 8873:                 $datatable .= '</td></tr>';
 8874:                 $itemcount ++; 
 8875:             }
 8876:         } else {
 8877:             my $prefix = 'replication';
 8878:             my @types = ('certreq','nocertreq');
 8879:             if (keys(%by_location) == 0) {
 8880:                 $datatable .= '<tr'.$css_class.'><td>'.
 8881:                               &mt('Nothing to set here, as there are no other institutions').
 8882:                               '</td></tr>';
 8883:                 $itemcount ++;
 8884:             } else {
 8885:                 ($datatable,$itemcount) = 
 8886:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8887:             }
 8888:         }
 8889:     }
 8890:     $$rowtotal += $itemcount;
 8891:     return $datatable;
 8892: }
 8893: 
 8894: sub ssl_titles {
 8895:     return &Apache::lonlocal::texthash (
 8896:                dom           => 'LON-CAPA servers/VMs from same domain',
 8897:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8898:                other         => 'External LON-CAPA servers/VMs',
 8899:                connto        => 'Connections to other servers',
 8900:                connfrom      => 'Connections from other servers',
 8901:                replication   => 'Replicating content to other institutions',
 8902:                certreq       => 'Client certificate required, but specific domains exempt',
 8903:                nocertreq     => 'No client certificate required, except for specific domains',
 8904:                no            => 'SSL not used',
 8905:                yes           => 'SSL Optional (used if available)',
 8906:                req           => 'SSL Required',
 8907:     );
 8908: }
 8909: 
 8910: sub print_trust {
 8911:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8912:     my ($css_class,$datatable,%checked,%choices);
 8913:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8914:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8915:     my $itemcount = 1;
 8916:     my %titles = &trust_titles();
 8917:     my @types = ('exc','inc');
 8918:     if ($prefix eq 'top') {
 8919:         $prefix = 'content';
 8920:     } elsif ($prefix eq 'bottom') {
 8921:         $prefix = 'msg';
 8922:     }
 8923:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8924:     $$rowtotal += $itemcount;
 8925:     return $datatable;
 8926: }
 8927: 
 8928: sub trust_titles {
 8929:     return &Apache::lonlocal::texthash(
 8930:                content  => "Access to this domain's content by others",
 8931:                shared   => "Access to other domain's content by this domain",
 8932:                enroll   => "Enrollment in this domain's courses by others", 
 8933:                othcoau  => "Co-author roles in this domain for others",
 8934:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8935:                domroles => "Domain roles in this domain assignable to others",
 8936:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8937:                reqcrs   => "Requests for creation of courses in this domain by others",
 8938:                msg      => "Users in other domains can send messages to this domain",
 8939:                exc      => "Allow all, but exclude specific domains",
 8940:                inc      => "Deny all, but include specific domains",
 8941:            );
 8942: } 
 8943: 
 8944: sub build_location_hashes {
 8945:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8946:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8947:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8948:     my %iphost = &Apache::lonnet::get_iphost();
 8949:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 8950:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 8951:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 8952:         foreach my $id (@{$iphost{$primary_ip}}) {
 8953:             my $intdom = &Apache::lonnet::internet_dom($id);
 8954:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 8955:                 push(@{$intdoms},$intdom);
 8956:             }
 8957:         }
 8958:     }
 8959:     foreach my $ip (keys(%iphost)) {
 8960:         if (ref($iphost{$ip}) eq 'ARRAY') {
 8961:             foreach my $id (@{$iphost{$ip}}) {
 8962:                 my $location = &Apache::lonnet::internet_dom($id);
 8963:                 if ($location) {
 8964:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 8965:                         my $dom = &Apache::lonnet::host_domain($id);
 8966:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 8967:                             push(@{$instdoms},$dom);
 8968:                         }
 8969:                         next;
 8970:                     }
 8971:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8972:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 8973:                             push(@{$by_ip->{$ip}},$location);
 8974:                         }
 8975:                     } else {
 8976:                         $by_ip->{$ip} = [$location];
 8977:                     }
 8978:                 }
 8979:             }
 8980:         }
 8981:     }
 8982:     foreach my $ip (sort(keys(%{$by_ip}))) {
 8983:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8984:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 8985:             my $first = $by_ip->{$ip}->[0];
 8986:             if (ref($by_location->{$first}) eq 'ARRAY') {
 8987:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 8988:                     push(@{$by_location->{$first}},$ip);
 8989:                 }
 8990:             } else {
 8991:                 $by_location->{$first} = [$ip];
 8992:             }
 8993:         }
 8994:     }
 8995:     return;
 8996: }
 8997: 
 8998: sub current_offloads_to {
 8999:     my ($dom,$settings,$servers) = @_;
 9000:     my (%spareid,%otherdomconfigs);
 9001:     if (ref($servers) eq 'HASH') {
 9002:         foreach my $lonhost (sort(keys(%{$servers}))) {
 9003:             my $gotspares;
 9004:             if (ref($settings) eq 'HASH') {
 9005:                 if (ref($settings->{'spares'}) eq 'HASH') {
 9006:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 9007:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 9008:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 9009:                         $gotspares = 1;
 9010:                     }
 9011:                 }
 9012:             }
 9013:             unless ($gotspares) {
 9014:                 my $gotspares;
 9015:                 my $serverhomeID =
 9016:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 9017:                 my $serverhomedom =
 9018:                     &Apache::lonnet::host_domain($serverhomeID);
 9019:                 if ($serverhomedom ne $dom) {
 9020:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 9021:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9022:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9023:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9024:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9025:                                 $gotspares = 1;
 9026:                             }
 9027:                         }
 9028:                     } else {
 9029:                         $otherdomconfigs{$serverhomedom} =
 9030:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 9031:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 9032:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9033:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9034:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 9035:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9036:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9037:                                         $gotspares = 1;
 9038:                                     }
 9039:                                 }
 9040:                             }
 9041:                         }
 9042:                     }
 9043:                 }
 9044:             }
 9045:             unless ($gotspares) {
 9046:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9047:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9048:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9049:                } else {
 9050:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 9051:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 9052:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9053:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9054:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9055:                     } else {
 9056:                         my %what = (
 9057:                              spareid => 1,
 9058:                         );
 9059:                         my ($result,$returnhash) = 
 9060:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 9061:                         if ($result eq 'ok') { 
 9062:                             if (ref($returnhash) eq 'HASH') {
 9063:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 9064:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 9065:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 9066:                                 }
 9067:                             }
 9068:                         }
 9069:                     }
 9070:                 }
 9071:             }
 9072:         }
 9073:     }
 9074:     return %spareid;
 9075: }
 9076: 
 9077: sub spares_row {
 9078:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 9079:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 9080:     my $css_class;
 9081:     my $numinrow = 4;
 9082:     my $itemcount = 1;
 9083:     my $datatable;
 9084:     my %typetitles = &sparestype_titles();
 9085:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9086:         foreach my $server (sort(keys(%{$servers}))) {
 9087:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 9088:             my ($othercontrol,$serverdom);
 9089:             if ($serverhome ne $server) {
 9090:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 9091:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9092:             } else {
 9093:                 $serverdom = &Apache::lonnet::host_domain($server);
 9094:                 if ($serverdom ne $dom) {
 9095:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9096:                 }
 9097:             }
 9098:             next unless (ref($spareid->{$server}) eq 'HASH');
 9099:             my ($checkednow,$checkedoth);
 9100:             if (ref($curroffloadnow) eq 'HASH') {
 9101:                 if ($curroffloadnow->{$server}) {
 9102:                     $checkednow = ' checked="checked"';
 9103:                 }
 9104:             }
 9105:             if (ref($curroffloadoth) eq 'HASH') {
 9106:                 if ($curroffloadoth->{$server}) {
 9107:                     $checkedoth = ' checked="checked"';
 9108:                 }
 9109:             }
 9110:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 9111:             $datatable .= '<tr'.$css_class.'>
 9112:                            <td rowspan="2">
 9113:                             <span class="LC_nobreak">'.
 9114:                           &mt('[_1] when busy, offloads to:'
 9115:                               ,'<b>'.$server.'</b>').'</span><br />'.
 9116:                           '<span class="LC_nobreak">'."\n".
 9117:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 9118:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 9119:                           "\n";
 9120:             if ($other_insts) {
 9121:                 $datatable .= '<br />'.
 9122:                               '<span class="LC_nobreak">'."\n".
 9123:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 9124:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 9125:                           "\n";
 9126:             }
 9127:             my (%current,%canselect);
 9128:             my @choices = 
 9129:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 9130:             foreach my $type ('primary','default') {
 9131:                 if (ref($spareid->{$server}) eq 'HASH') {
 9132:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 9133:                         my @spares = @{$spareid->{$server}{$type}};
 9134:                         if (@spares > 0) {
 9135:                             if ($othercontrol) {
 9136:                                 $current{$type} = join(', ',@spares);
 9137:                             } else {
 9138:                                 $current{$type} .= '<table>';
 9139:                                 my $numspares = scalar(@spares);
 9140:                                 for (my $i=0;  $i<@spares; $i++) {
 9141:                                     my $rem = $i%($numinrow);
 9142:                                     if ($rem == 0) {
 9143:                                         if ($i > 0) {
 9144:                                             $current{$type} .= '</tr>';
 9145:                                         }
 9146:                                         $current{$type} .= '<tr>';
 9147:                                     }
 9148:                                     $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;'.
 9149:                                                        $spareid->{$server}{$type}[$i].
 9150:                                                        '</label></td>'."\n";
 9151:                                 }
 9152:                                 my $rem = @spares%($numinrow);
 9153:                                 my $colsleft = $numinrow - $rem;
 9154:                                 if ($colsleft > 1 ) {
 9155:                                     $current{$type} .= '<td colspan="'.$colsleft.
 9156:                                                        '" class="LC_left_item">'.
 9157:                                                        '&nbsp;</td>';
 9158:                                 } elsif ($colsleft == 1) {
 9159:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 9160:                                 }
 9161:                                 $current{$type} .= '</tr></table>';
 9162:                             }
 9163:                         }
 9164:                     }
 9165:                     if ($current{$type} eq '') {
 9166:                         $current{$type} = &mt('None specified');
 9167:                     }
 9168:                     if ($othercontrol) {
 9169:                         if ($type eq 'primary') {
 9170:                             $canselect{$type} = $othercontrol;
 9171:                         }
 9172:                     } else {
 9173:                         $canselect{$type} = 
 9174:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 9175:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 9176:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 9177:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 9178:                         if (@choices > 0) {
 9179:                             foreach my $lonhost (@choices) {
 9180:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 9181:                             }
 9182:                         }
 9183:                         $canselect{$type} .= '</select>'."\n";
 9184:                     }
 9185:                 } else {
 9186:                     $current{$type} = &mt('Could not be determined');
 9187:                     if ($type eq 'primary') {
 9188:                         $canselect{$type} =  $othercontrol;
 9189:                     }
 9190:                 }
 9191:                 if ($type eq 'default') {
 9192:                     $datatable .= '<tr'.$css_class.'>';
 9193:                 }
 9194:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 9195:                               '<td>'.$current{$type}.'</td>'."\n".
 9196:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 9197:             }
 9198:             $itemcount ++;
 9199:         }
 9200:     }
 9201:     $$rowtotal += $itemcount;
 9202:     return $datatable;
 9203: }
 9204: 
 9205: sub possible_newspares {
 9206:     my ($server,$currspares,$serverhomes,$altids) = @_;
 9207:     my $serverhostname = &Apache::lonnet::hostname($server);
 9208:     my %excluded;
 9209:     if ($serverhostname ne '') {
 9210:         %excluded = (
 9211:                        $serverhostname => 1,
 9212:                     );
 9213:     }
 9214:     if (ref($currspares) eq 'HASH') {
 9215:         foreach my $type (keys(%{$currspares})) {
 9216:             if (ref($currspares->{$type}) eq 'ARRAY') {
 9217:                 if (@{$currspares->{$type}} > 0) {
 9218:                     foreach my $curr (@{$currspares->{$type}}) {
 9219:                         my $hostname = &Apache::lonnet::hostname($curr);
 9220:                         $excluded{$hostname} = 1;
 9221:                     }
 9222:                 }
 9223:             }
 9224:         }
 9225:     }
 9226:     my @choices;
 9227:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9228:         if (keys(%{$serverhomes}) > 1) {
 9229:             foreach my $name (sort(keys(%{$serverhomes}))) {
 9230:                 unless ($excluded{$name}) {
 9231:                     if (exists($altids->{$serverhomes->{$name}})) {
 9232:                         push(@choices,$altids->{$serverhomes->{$name}});
 9233:                     } else {
 9234:                         push(@choices,$serverhomes->{$name});
 9235:                     }
 9236:                 }
 9237:             }
 9238:         }
 9239:     }
 9240:     return sort(@choices);
 9241: }
 9242: 
 9243: sub print_loadbalancing {
 9244:     my ($dom,$settings,$rowtotal) = @_;
 9245:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9246:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9247:     my $numinrow = 1;
 9248:     my $datatable;
 9249:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9250:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 9251:     if (ref($settings) eq 'HASH') {
 9252:         %existing = %{$settings};
 9253:     }
 9254:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 9255:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 9256:                                   \%currtargets,\%currrules,\%currcookies);
 9257:     } else {
 9258:         return;
 9259:     }
 9260:     my ($othertitle,$usertypes,$types) =
 9261:         &Apache::loncommon::sorted_inst_types($dom);
 9262:     my $rownum = 8;
 9263:     if (ref($types) eq 'ARRAY') {
 9264:         $rownum += scalar(@{$types});
 9265:     }
 9266:     my @css_class = ('LC_odd_row','LC_even_row');
 9267:     my $balnum = 0;
 9268:     my $islast;
 9269:     my (@toshow,$disabledtext);
 9270:     if (keys(%currbalancer) > 0) {
 9271:         @toshow = sort(keys(%currbalancer));
 9272:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 9273:             push(@toshow,'');
 9274:         }
 9275:     } else {
 9276:         @toshow = ('');
 9277:         $disabledtext = &mt('No existing load balancer');
 9278:     }
 9279:     foreach my $lonhost (@toshow) {
 9280:         if ($balnum == scalar(@toshow)-1) {
 9281:             $islast = 1;
 9282:         } else {
 9283:             $islast = 0;
 9284:         }
 9285:         my $cssidx = $balnum%2;
 9286:         my $targets_div_style = 'display: none';
 9287:         my $disabled_div_style = 'display: block';
 9288:         my $homedom_div_style = 'display: none';
 9289:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 9290:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9291:                       '<p>';
 9292:         if ($lonhost eq '') {
 9293:             $datatable .= '<span class="LC_nobreak">';
 9294:             if (keys(%currbalancer) > 0) {
 9295:                 $datatable .= &mt('Add balancer:');
 9296:             } else {
 9297:                 $datatable .= &mt('Enable balancer:');
 9298:             }
 9299:             $datatable .= '&nbsp;'.
 9300:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 9301:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 9302:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 9303:                           '<option value="" selected="selected">'.&mt('None').
 9304:                           '</option>'."\n";
 9305:             foreach my $server (sort(keys(%servers))) {
 9306:                 next if ($currbalancer{$server});
 9307:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 9308:             }
 9309:             $datatable .=
 9310:                 '</select>'."\n".
 9311:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 9312:         } else {
 9313:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 9314:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 9315:                            &mt('Stop balancing').'</label>'.
 9316:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 9317:             $targets_div_style = 'display: block';
 9318:             $disabled_div_style = 'display: none';
 9319:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 9320:                 $homedom_div_style = 'display: block';
 9321:             }
 9322:         }
 9323:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9324:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 9325:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 9326:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 9327:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 9328:         my @sparestypes = ('primary','default');
 9329:         my %typetitles = &sparestype_titles();
 9330:         my %hostherechecked = (
 9331:                                   no => ' checked="checked"',
 9332:                               );
 9333:         my %balcookiechecked = (
 9334:                                   no => ' checked="checked"', 
 9335:                                );
 9336:         foreach my $sparetype (@sparestypes) {
 9337:             my $targettable;
 9338:             for (my $i=0; $i<$numspares; $i++) {
 9339:                 my $checked;
 9340:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 9341:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9342:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9343:                             $checked = ' checked="checked"';
 9344:                         }
 9345:                     }
 9346:                 }
 9347:                 my ($chkboxval,$disabled);
 9348:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 9349:                     $chkboxval = $spares[$i];
 9350:                 }
 9351:                 if (exists($currbalancer{$spares[$i]})) {
 9352:                     $disabled = ' disabled="disabled"';
 9353:                 }
 9354:                 $targettable .=
 9355:                     '<td><span class="LC_nobreak"><label>'.
 9356:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 9357:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 9358:                     '</span></label></span></td>';
 9359:                 my $rem = $i%($numinrow);
 9360:                 if ($rem == 0) {
 9361:                     if (($i > 0) && ($i < $numspares-1)) {
 9362:                         $targettable .= '</tr>';
 9363:                     }
 9364:                     if ($i < $numspares-1) {
 9365:                         $targettable .= '<tr>';
 9366:                     }
 9367:                 }
 9368:             }
 9369:             if ($targettable ne '') {
 9370:                 my $rem = $numspares%($numinrow);
 9371:                 my $colsleft = $numinrow - $rem;
 9372:                 if ($colsleft > 1 ) {
 9373:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9374:                                     '&nbsp;</td>';
 9375:                 } elsif ($colsleft == 1) {
 9376:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 9377:                 }
 9378:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 9379:                                '<table><tr>'.$targettable.'</tr></table><br />';
 9380:             }
 9381:             $hostherechecked{$sparetype} = '';
 9382:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 9383:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9384:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9385:                         $hostherechecked{$sparetype} = ' checked="checked"';
 9386:                         $hostherechecked{'no'} = '';
 9387:                     }
 9388:                 }
 9389:             }
 9390:         }
 9391:         if ($currcookies{$lonhost}) {
 9392:             %balcookiechecked = (
 9393:                                     yes => ' checked="checked"',
 9394:                                 );
 9395:         }
 9396:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 9397:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 9398:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 9399:         foreach my $sparetype (@sparestypes) {
 9400:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 9401:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 9402:                           '</i></label><br />';
 9403:         }
 9404:         $datatable .= &mt('Use balancer cookie').'<br />'.
 9405:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 9406:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 9407:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 9408:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 9409:                       '</div></td></tr>'.
 9410:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 9411:                                            $othertitle,$usertypes,$types,\%servers,
 9412:                                            \%currbalancer,$lonhost,
 9413:                                            $targets_div_style,$homedom_div_style,
 9414:                                            $css_class[$cssidx],$balnum,$islast);
 9415:         $$rowtotal += $rownum;
 9416:         $balnum ++;
 9417:     }
 9418:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 9419:     return $datatable;
 9420: }
 9421: 
 9422: sub get_loadbalancers_config {
 9423:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 9424:     return unless ((ref($servers) eq 'HASH') &&
 9425:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 9426:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 9427:                    (ref($currcookies) eq 'HASH'));
 9428:     if (keys(%{$existing}) > 0) {
 9429:         my $oldlonhost;
 9430:         foreach my $key (sort(keys(%{$existing}))) {
 9431:             if ($key eq 'lonhost') {
 9432:                 $oldlonhost = $existing->{'lonhost'};
 9433:                 $currbalancer->{$oldlonhost} = 1;
 9434:             } elsif ($key eq 'targets') {
 9435:                 if ($oldlonhost) {
 9436:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 9437:                 }
 9438:             } elsif ($key eq 'rules') {
 9439:                 if ($oldlonhost) {
 9440:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 9441:                 }
 9442:             } elsif (ref($existing->{$key}) eq 'HASH') {
 9443:                 $currbalancer->{$key} = 1;
 9444:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 9445:                 $currrules->{$key} = $existing->{$key}{'rules'};
 9446:                 if ($existing->{$key}{'cookie'}) {
 9447:                     $currcookies->{$key} = 1;
 9448:                 }
 9449:             }
 9450:         }
 9451:     } else {
 9452:         my ($balancerref,$targetsref) =
 9453:                 &Apache::lonnet::get_lonbalancer_config($servers);
 9454:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 9455:             foreach my $server (sort(keys(%{$balancerref}))) {
 9456:                 $currbalancer->{$server} = 1;
 9457:                 $currtargets->{$server} = $targetsref->{$server};
 9458:             }
 9459:         }
 9460:     }
 9461:     return;
 9462: }
 9463: 
 9464: sub loadbalancing_rules {
 9465:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 9466:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 9467:         $css_class,$balnum,$islast) = @_;
 9468:     my $output;
 9469:     my $num = 0;
 9470:     my ($alltypes,$othertypes,$titles) =
 9471:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 9472:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 9473:         foreach my $type (@{$alltypes}) {
 9474:             $num ++;
 9475:             my $current;
 9476:             if (ref($currrules) eq 'HASH') {
 9477:                 $current = $currrules->{$type};
 9478:             }
 9479:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9480:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 9481:                     $current = '';
 9482:                 }
 9483:             }
 9484:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 9485:                                              $servers,$currbalancer,$lonhost,$dom,
 9486:                                              $targets_div_style,$homedom_div_style,
 9487:                                              $css_class,$balnum,$num,$islast);
 9488:         }
 9489:     }
 9490:     return $output;
 9491: }
 9492: 
 9493: sub loadbalancing_titles {
 9494:     my ($dom,$intdom,$usertypes,$types) = @_;
 9495:     my %othertypes = (
 9496:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 9497:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 9498:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 9499:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 9500:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 9501:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 9502:                      );
 9503:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 9504:     my @available;
 9505:     if (ref($types) eq 'ARRAY') {
 9506:         @available = @{$types};
 9507:     }
 9508:     unless (grep(/^default$/,@available)) {
 9509:         push(@available,'default');
 9510:     }
 9511:     unshift(@alltypes,@available);
 9512:     my %titles;
 9513:     foreach my $type (@alltypes) {
 9514:         if ($type =~ /^_LC_/) {
 9515:             $titles{$type} = $othertypes{$type};
 9516:         } elsif ($type eq 'default') {
 9517:             $titles{$type} = &mt('All users from [_1]',$dom);
 9518:             if (ref($types) eq 'ARRAY') {
 9519:                 if (@{$types} > 0) {
 9520:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 9521:                 }
 9522:             }
 9523:         } elsif (ref($usertypes) eq 'HASH') {
 9524:             $titles{$type} = $usertypes->{$type};
 9525:         }
 9526:     }
 9527:     return (\@alltypes,\%othertypes,\%titles);
 9528: }
 9529: 
 9530: sub loadbalance_rule_row {
 9531:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 9532:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 9533:     my @rulenames;
 9534:     my %ruletitles = &offloadtype_text();
 9535:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 9536:         @rulenames = ('balancer','offloadedto','specific');
 9537:     } else {
 9538:         @rulenames = ('default','homeserver');
 9539:         if ($type eq '_LC_external') {
 9540:             push(@rulenames,'externalbalancer');
 9541:         } else {
 9542:             push(@rulenames,'specific');
 9543:         }
 9544:         push(@rulenames,'none');
 9545:     }
 9546:     my $style = $targets_div_style;
 9547:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9548:         $style = $homedom_div_style;
 9549:     }
 9550:     my $space;
 9551:     if ($islast && $num == 1) {
 9552:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 9553:     }
 9554:     my $output =
 9555:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 9556:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 9557:         '<td valaign="top">'.$space.
 9558:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 9559:     for (my $i=0; $i<@rulenames; $i++) {
 9560:         my $rule = $rulenames[$i];
 9561:         my ($checked,$extra);
 9562:         if ($rulenames[$i] eq 'default') {
 9563:             $rule = '';
 9564:         }
 9565:         if ($rulenames[$i] eq 'specific') {
 9566:             if (ref($servers) eq 'HASH') {
 9567:                 my $default;
 9568:                 if (($current ne '') && (exists($servers->{$current}))) {
 9569:                     $checked = ' checked="checked"';
 9570:                 }
 9571:                 unless ($checked) {
 9572:                     $default = ' selected="selected"';
 9573:                 }
 9574:                 $extra =
 9575:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9576:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9577:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 9578:                     '<option value=""'.$default.'></option>'."\n";
 9579:                 foreach my $server (sort(keys(%{$servers}))) {
 9580:                     if (ref($currbalancer) eq 'HASH') {
 9581:                         next if (exists($currbalancer->{$server}));
 9582:                     }
 9583:                     my $selected;
 9584:                     if ($server eq $current) {
 9585:                         $selected = ' selected="selected"';
 9586:                     }
 9587:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 9588:                 }
 9589:                 $extra .= '</select>';
 9590:             }
 9591:         } elsif ($rule eq $current) {
 9592:             $checked = ' checked="checked"';
 9593:         }
 9594:         $output .= '<span class="LC_nobreak"><label>'.
 9595:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 9596:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 9597:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 9598:                    ')"'.$checked.' />&nbsp;';
 9599:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 9600:             $output .= $ruletitles{'particular'};
 9601:         } else {
 9602:             $output .= $ruletitles{$rulenames[$i]};
 9603:         }
 9604:         $output .= '</label>'.$extra.'</span><br />'."\n";
 9605:     }
 9606:     $output .= '</div></td></tr>'."\n";
 9607:     return $output;
 9608: }
 9609: 
 9610: sub offloadtype_text {
 9611:     my %ruletitles = &Apache::lonlocal::texthash (
 9612:            'default'          => 'Offloads to default destinations',
 9613:            'homeserver'       => "Offloads to user's home server",
 9614:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 9615:            'specific'         => 'Offloads to specific server',
 9616:            'none'             => 'No offload',
 9617:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 9618:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 9619:            'particular'       => 'Session hosted (after re-auth) on server:',
 9620:     );
 9621:     return %ruletitles;
 9622: }
 9623: 
 9624: sub sparestype_titles {
 9625:     my %typestitles = &Apache::lonlocal::texthash (
 9626:                           'primary' => 'primary',
 9627:                           'default' => 'default',
 9628:                       );
 9629:     return %typestitles;
 9630: }
 9631: 
 9632: sub contact_titles {
 9633:     my %titles = &Apache::lonlocal::texthash (
 9634:                    'supportemail'    => 'Support E-mail address',
 9635:                    'adminemail'      => 'Default Server Admin E-mail address',
 9636:                    'errormail'       => 'Error reports to be e-mailed to',
 9637:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 9638:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 9639:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 9640:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 9641:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 9642:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 9643:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 9644:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 9645:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 9646:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 9647:                    'errorweights'    => 'Weights used to compute error count',
 9648:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 9649:                  );
 9650:     my %short_titles = &Apache::lonlocal::texthash (
 9651:                            adminemail   => 'Admin E-mail address',
 9652:                            supportemail => 'Support E-mail',
 9653:                        );   
 9654:     return (\%titles,\%short_titles);
 9655: }
 9656: 
 9657: sub helpform_fields {
 9658:     my %titles =  &Apache::lonlocal::texthash (
 9659:                        'username'   => 'Name',
 9660:                        'user'       => 'Username/domain',
 9661:                        'phone'      => 'Phone',
 9662:                        'cc'         => 'Cc e-mail',
 9663:                        'course'     => 'Course Details',
 9664:                        'section'    => 'Sections',
 9665:                        'screenshot' => 'File upload',
 9666:     );
 9667:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 9668:     my %possoptions = (
 9669:                         username     => ['yes','no','req'],
 9670:                         phone        => ['yes','no','req'],
 9671:                         user         => ['yes','no'],
 9672:                         cc           => ['yes','no'],
 9673:                         course       => ['yes','no'],
 9674:                         section      => ['yes','no'],
 9675:                         screenshot   => ['yes','no'],
 9676:                       );
 9677:     my %fieldoptions = &Apache::lonlocal::texthash (
 9678:                          'yes'  => 'Optional',
 9679:                          'req'  => 'Required',
 9680:                          'no'   => "Not shown",
 9681:     );
 9682:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 9683: }
 9684: 
 9685: sub tool_titles {
 9686:     my %titles = &Apache::lonlocal::texthash (
 9687:                      aboutme    => 'Personal web page',
 9688:                      blog       => 'Blog',
 9689:                      webdav     => 'WebDAV',
 9690:                      portfolio  => 'Portfolio',
 9691:                      official   => 'Official courses (with institutional codes)',
 9692:                      unofficial => 'Unofficial courses',
 9693:                      community  => 'Communities',
 9694:                      textbook   => 'Textbook courses',
 9695:                      placement  => 'Placement tests',
 9696:                  );
 9697:     return %titles;
 9698: }
 9699: 
 9700: sub courserequest_titles {
 9701:     my %titles = &Apache::lonlocal::texthash (
 9702:                                    official   => 'Official',
 9703:                                    unofficial => 'Unofficial',
 9704:                                    community  => 'Communities',
 9705:                                    textbook   => 'Textbook',
 9706:                                    placement  => 'Placement tests',
 9707:                                    lti        => 'LTI Provider',
 9708:                                    norequest  => 'Not allowed',
 9709:                                    approval   => 'Approval by DC',
 9710:                                    validate   => 'With validation',
 9711:                                    autolimit  => 'Numerical limit',
 9712:                                    unlimited  => '(blank for unlimited)',
 9713:                  );
 9714:     return %titles;
 9715: }
 9716: 
 9717: sub authorrequest_titles {
 9718:     my %titles = &Apache::lonlocal::texthash (
 9719:                                    norequest  => 'Not allowed',
 9720:                                    approval   => 'Approval by Dom. Coord.',
 9721:                                    automatic  => 'Automatic approval',
 9722:                  );
 9723:     return %titles;
 9724: }
 9725: 
 9726: sub courserequest_conditions {
 9727:     my %conditions = &Apache::lonlocal::texthash (
 9728:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 9729:        validate   => '(Processing of request subject to institutional validation).',
 9730:                  );
 9731:     return %conditions;
 9732: }
 9733: 
 9734: 
 9735: sub print_usercreation {
 9736:     my ($position,$dom,$settings,$rowtotal) = @_;
 9737:     my $numinrow = 4;
 9738:     my $datatable;
 9739:     if ($position eq 'top') {
 9740:         $$rowtotal ++;
 9741:         my $rowcount = 0;
 9742:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 9743:         if (ref($rules) eq 'HASH') {
 9744:             if (keys(%{$rules}) > 0) {
 9745:                 $datatable .= &user_formats_row('username',$settings,$rules,
 9746:                                                 $ruleorder,$numinrow,$rowcount);
 9747:                 $$rowtotal ++;
 9748:                 $rowcount ++;
 9749:             }
 9750:         }
 9751:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 9752:         if (ref($idrules) eq 'HASH') {
 9753:             if (keys(%{$idrules}) > 0) {
 9754:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 9755:                                                 $idruleorder,$numinrow,$rowcount);
 9756:                 $$rowtotal ++;
 9757:                 $rowcount ++;
 9758:             }
 9759:         }
 9760:         if ($rowcount == 0) {
 9761:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 9762:             $$rowtotal ++;
 9763:             $rowcount ++;
 9764:         }
 9765:     } elsif ($position eq 'middle') {
 9766:         my @creators = ('author','course','requestcrs');
 9767:         my ($rules,$ruleorder) =
 9768:             &Apache::lonnet::inst_userrules($dom,'username');
 9769:         my %lt = &usercreation_types();
 9770:         my %checked;
 9771:         if (ref($settings) eq 'HASH') {
 9772:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 9773:                 foreach my $item (@creators) {
 9774:                     $checked{$item} = $settings->{'cancreate'}{$item};
 9775:                 }
 9776:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 9777:                 foreach my $item (@creators) {
 9778:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 9779:                         $checked{$item} = 'none';
 9780:                     }
 9781:                 }
 9782:             }
 9783:         }
 9784:         my $rownum = 0;
 9785:         foreach my $item (@creators) {
 9786:             $rownum ++;
 9787:             if ($checked{$item} eq '') {
 9788:                 $checked{$item} = 'any';
 9789:             }
 9790:             my $css_class;
 9791:             if ($rownum%2) {
 9792:                 $css_class = '';
 9793:             } else {
 9794:                 $css_class = ' class="LC_odd_row" ';
 9795:             }
 9796:             $datatable .= '<tr'.$css_class.'>'.
 9797:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 9798:                          '</span></td><td style="text-align: right">';
 9799:             my @options = ('any');
 9800:             if (ref($rules) eq 'HASH') {
 9801:                 if (keys(%{$rules}) > 0) {
 9802:                     push(@options,('official','unofficial'));
 9803:                 }
 9804:             }
 9805:             push(@options,'none');
 9806:             foreach my $option (@options) {
 9807:                 my $type = 'radio';
 9808:                 my $check = ' ';
 9809:                 if ($checked{$item} eq $option) {
 9810:                     $check = ' checked="checked" ';
 9811:                 } 
 9812:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9813:                               '<input type="'.$type.'" name="can_createuser_'.
 9814:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 9815:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 9816:             }
 9817:             $datatable .= '</td></tr>';
 9818:         }
 9819:     } else {
 9820:         my @contexts = ('author','course','domain');
 9821:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9822:         my %checked;
 9823:         if (ref($settings) eq 'HASH') {
 9824:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9825:                 foreach my $item (@contexts) {
 9826:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9827:                         foreach my $auth (@authtypes) {
 9828:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9829:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9830:                             }
 9831:                         }
 9832:                     }
 9833:                 }
 9834:             }
 9835:         } else {
 9836:             foreach my $item (@contexts) {
 9837:                 foreach my $auth (@authtypes) {
 9838:                     $checked{$item}{$auth} = ' checked="checked" ';
 9839:                 }
 9840:             }
 9841:         }
 9842:         my %title = &context_names();
 9843:         my %authname = &authtype_names();
 9844:         my $rownum = 0;
 9845:         my $css_class; 
 9846:         foreach my $item (@contexts) {
 9847:             if ($rownum%2) {
 9848:                 $css_class = '';
 9849:             } else {
 9850:                 $css_class = ' class="LC_odd_row" ';
 9851:             }
 9852:             $datatable .=   '<tr'.$css_class.'>'.
 9853:                             '<td>'.$title{$item}.
 9854:                             '</td><td class="LC_left_item">'.
 9855:                             '<span class="LC_nobreak">';
 9856:             foreach my $auth (@authtypes) {
 9857:                 $datatable .= '<label>'. 
 9858:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9859:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9860:                               $authname{$auth}.'</label>&nbsp;';
 9861:             }
 9862:             $datatable .= '</span></td></tr>';
 9863:             $rownum ++;
 9864:         }
 9865:         $$rowtotal += $rownum;
 9866:     }
 9867:     return $datatable;
 9868: }
 9869: 
 9870: sub print_selfcreation {
 9871:     my ($position,$dom,$settings,$rowtotal) = @_;
 9872:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9873:         $emaildomain,$datatable);
 9874:     if (ref($settings) eq 'HASH') {
 9875:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9876:             $createsettings = $settings->{'cancreate'};
 9877:             if (ref($createsettings) eq 'HASH') {
 9878:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9879:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9880:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9881:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9882:                         @selfcreate = ('email','login','sso');
 9883:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9884:                         @selfcreate = ($createsettings->{'selfcreate'});
 9885:                     }
 9886:                 }
 9887:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9888:                     $processing = $createsettings->{'selfcreateprocessing'};
 9889:                 }
 9890:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9891:                     $emailoptions = $createsettings->{'emailoptions'};
 9892:                 }
 9893:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9894:                     $emailverified = $createsettings->{'emailverified'};
 9895:                 }
 9896:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9897:                     $emaildomain = $createsettings->{'emaildomain'};
 9898:                 }
 9899:             }
 9900:         }
 9901:     }
 9902:     my %radiohash;
 9903:     my $numinrow = 4;
 9904:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9905:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9906:     if ($position eq 'top') {
 9907:         my %choices = &Apache::lonlocal::texthash (
 9908:                                                       cancreate_login      => 'Institutional Login',
 9909:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9910:                                                   );
 9911:         my @toggles = sort(keys(%choices));
 9912:         my %defaultchecked = (
 9913:                                'cancreate_login' => 'off',
 9914:                                'cancreate_sso'   => 'off',
 9915:                              );
 9916:         my ($onclick,$itemcount);
 9917:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9918:                                                      \%choices,$itemcount,$onclick);
 9919:         $$rowtotal += $itemcount;
 9920:         
 9921:         if (ref($usertypes) eq 'HASH') {
 9922:             if (keys(%{$usertypes}) > 0) {
 9923:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9924:                                              $dom,$numinrow,$othertitle,
 9925:                                              'statustocreate',$rowtotal);
 9926:                 $$rowtotal ++;
 9927:             }
 9928:         }
 9929:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9930:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9931:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9932:         my $rem;
 9933:         my $numperrow = 2;
 9934:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9935:         $datatable .= '<tr'.$css_class.'>'.
 9936:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9937:                      '<td class="LC_left_item">'."\n".
 9938:                      '<table>'."\n";
 9939:         for (my $i=0; $i<@fields; $i++) {
 9940:             $rem = $i%($numperrow);
 9941:             if ($rem == 0) {
 9942:                 if ($i > 0) {
 9943:                     $datatable .= '</tr>';
 9944:                 }
 9945:                 $datatable .= '<tr>';
 9946:             }
 9947:             my $currval;
 9948:             if (ref($createsettings) eq 'HASH') {
 9949:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 9950:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 9951:                 }
 9952:             }
 9953:             $datatable .= '<td class="LC_left_item">'.
 9954:                           '<span class="LC_nobreak">'.
 9955:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 9956:                           'value="'.$currval.'" size="10" />&nbsp;'.
 9957:                           $fieldtitles{$fields[$i]}.'</span></td>';
 9958:         }
 9959:         my $colsleft = $numperrow - $rem;
 9960:         if ($colsleft > 1 ) {
 9961:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9962:                          '&nbsp;</td>';
 9963:         } elsif ($colsleft == 1) {
 9964:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 9965:         }
 9966:         $datatable .= '</tr></table></td></tr>';
 9967:         $$rowtotal ++;
 9968:     } elsif ($position eq 'middle') {
 9969:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 9970:         my @posstypes;
 9971:         if (ref($types) eq 'ARRAY') {
 9972:             @posstypes = @{$types};
 9973:         }
 9974:         unless (grep(/^default$/,@posstypes)) {
 9975:             push(@posstypes,'default');
 9976:         }
 9977:         my %usertypeshash;
 9978:         if (ref($usertypes) eq 'HASH') {
 9979:             %usertypeshash = %{$usertypes};
 9980:         }
 9981:         $usertypeshash{'default'} = $othertitle;
 9982:         foreach my $status (@posstypes) {
 9983:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 9984:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 9985:             $$rowtotal ++;
 9986:         }
 9987:     } else {
 9988:         my %choices = &Apache::lonlocal::texthash (
 9989:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 9990:                                                   );
 9991:         my @toggles = sort(keys(%choices));
 9992:         my %defaultchecked = (
 9993:                                'cancreate_email' => 'off',
 9994:                              );
 9995:         my $customclass = 'LC_selfcreate_email';
 9996:         my $classprefix = 'LC_canmodify_emailusername_';
 9997:         my $optionsprefix = 'LC_options_emailusername_';
 9998:         my $display = 'none';
 9999:         my $rowstyle = 'display:none';
10000:         if (grep(/^\Qemail\E$/,@selfcreate)) {
10001:             $display = 'block';
10002:             $rowstyle = 'display:table-row';
10003:         }
10004:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
10005:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
10006:                                                      \%choices,$$rowtotal,$onclick);
10007:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
10008:                                          $rowstyle);
10009:         $$rowtotal ++;
10010:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
10011:                                       $rowstyle);
10012:         $$rowtotal ++;
10013:         my (@ordered,@posstypes,%usertypeshash);
10014:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10015:         my ($emailrules,$emailruleorder) =
10016:             &Apache::lonnet::inst_userrules($dom,'email');
10017:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
10018:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
10019:         if (ref($types) eq 'ARRAY') {
10020:             @posstypes = @{$types};
10021:         }
10022:         if (@posstypes) {
10023:             unless (grep(/^default$/,@posstypes)) {
10024:                 push(@posstypes,'default');
10025:             }
10026:             if (ref($usertypes) eq 'HASH') {
10027:                 %usertypeshash = %{$usertypes};
10028:             }
10029:             my $currassign;
10030:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
10031:                 $currassign = {
10032:                                   selfassign => $domdefaults{'inststatusguest'},
10033:                               };
10034:                 @ordered = @{$domdefaults{'inststatusguest'}};
10035:             } else {
10036:                 $currassign = { selfassign => [] };
10037:             }
10038:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
10039:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
10040:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
10041:                                          $numinrow,$othertitle,'selfassign',
10042:                                          $rowtotal,$onclicktypes,$customclass,
10043:                                          $rowstyle);
10044:             $$rowtotal ++;
10045:             $usertypeshash{'default'} = $othertitle;
10046:             foreach my $status (@posstypes) {
10047:                 my $css_class;
10048:                 if ($$rowtotal%2) {
10049:                     $css_class = 'LC_odd_row ';
10050:                 }
10051:                 $css_class .= $customclass;
10052:                 my $rowid = $optionsprefix.$status;
10053:                 my $hidden = 1;
10054:                 my $currstyle = 'display:none';
10055:                 if (grep(/^\Q$status\E$/,@ordered)) {
10056:                     $currstyle = $rowstyle;
10057:                     $hidden = 0; 
10058:                 }
10059:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10060:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
10061:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
10062:                 unless ($hidden) {
10063:                     $$rowtotal ++;
10064:                 }
10065:             }
10066:         } else {
10067:             my $css_class;
10068:             if ($$rowtotal%2) {
10069:                 $css_class = 'LC_odd_row ';
10070:             }
10071:             $css_class .= $customclass;
10072:             $usertypeshash{'default'} = $othertitle;
10073:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10074:                                          $emailrules,$emailruleorder,$settings,'default','',
10075:                                          $othertitle,$css_class,$rowstyle,$intdom);
10076:             $$rowtotal ++;
10077:         }
10078:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
10079:         $numinrow = 1;
10080:         if (@posstypes) {
10081:             foreach my $status (@posstypes) {
10082:                 my $rowid = $classprefix.$status;
10083:                 my $datarowstyle = 'display:none';
10084:                 if (grep(/^\Q$status\E$/,@ordered)) { 
10085:                     $datarowstyle = $rowstyle; 
10086:                 }
10087:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
10088:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10089:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
10090:                 unless ($datarowstyle eq 'display:none') {
10091:                     $$rowtotal ++;
10092:                 }
10093:             }
10094:         } else {
10095:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
10096:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10097:                                                    $infotitles,'',$customclass,$rowstyle);
10098:         }
10099:     }
10100:     return $datatable;
10101: }
10102: 
10103: sub selfcreate_javascript {
10104:     return <<"ENDSCRIPT";
10105: 
10106: <script type="text/javascript">
10107: // <![CDATA[
10108: 
10109: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
10110:     var x = document.getElementsByClassName(target);
10111:     var insttypes = 0;
10112:     var insttypeRegExp = new RegExp(prefix);
10113:     if ((x.length != undefined) && (x.length > 0)) {
10114:         if (form.elements[radio].length != undefined) {
10115:             for (var i=0; i<form.elements[radio].length; i++) {
10116:                 if (form.elements[radio][i].checked) {
10117:                     if (form.elements[radio][i].value == 1) {
10118:                         for (var j=0; j<x.length; j++) {
10119:                             if (x[j].id == 'undefined') {
10120:                                 x[j].style.display = 'table-row';
10121:                             } else if (insttypeRegExp.test(x[j].id)) {
10122:                                 insttypes ++;
10123:                             } else {
10124:                                 x[j].style.display = 'table-row';
10125:                             }
10126:                         }
10127:                     } else {
10128:                         for (var j=0; j<x.length; j++) {
10129:                             x[j].style.display = 'none';
10130:                         }
10131:                     }
10132:                     break;
10133:                 }
10134:             }
10135:             if (insttypes > 0) {
10136:                 toggleDataRow(form,checkbox,target,altprefix);
10137:                 toggleDataRow(form,checkbox,target,prefix,1);
10138:             }
10139:         }
10140:     }
10141:     return;
10142: }
10143: 
10144: function toggleDataRow(form,checkbox,target,prefix,docount) {
10145:     if (form.elements[checkbox].length != undefined) {
10146:         var count = 0;
10147:         if (docount) {
10148:             for (var i=0; i<form.elements[checkbox].length; i++) {
10149:                 if (form.elements[checkbox][i].checked) {
10150:                     count ++;
10151:                 }
10152:             }
10153:         }
10154:         for (var i=0; i<form.elements[checkbox].length; i++) {
10155:             var type = form.elements[checkbox][i].value;
10156:             if (document.getElementById(prefix+type)) {
10157:                 if (form.elements[checkbox][i].checked) {
10158:                     document.getElementById(prefix+type).style.display = 'table-row';
10159:                     if (count % 2 == 1) {
10160:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
10161:                     } else {
10162:                         document.getElementById(prefix+type).className = target;
10163:                     }
10164:                     count ++;
10165:                 } else {
10166:                     document.getElementById(prefix+type).style.display = 'none';
10167:                 }
10168:             }
10169:         }
10170:     }
10171:     return;
10172: }
10173: 
10174: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
10175:     var caller = radio+'_'+status;
10176:     if (form.elements[caller].length != undefined) {
10177:         for (var i=0; i<form.elements[caller].length; i++) {
10178:             if (form.elements[caller][i].checked) {
10179:                 if (document.getElementById(altprefix+'_inst_'+status)) {
10180:                     var curr = form.elements[caller][i].value;
10181:                     if (prefix) {
10182:                         document.getElementById(prefix+'_'+status).style.display = 'none';
10183:                     }
10184:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
10185:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
10186:                     if (curr == 'custom') {
10187:                         if (prefix) { 
10188:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
10189:                         }
10190:                     } else if (curr == 'inst') {
10191:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
10192:                     } else if (curr == 'noninst') {
10193:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
10194:                     }
10195:                     break;
10196:                 }
10197:             }
10198:         }
10199:     }
10200: }
10201: 
10202: // ]]>
10203: </script>
10204: 
10205: ENDSCRIPT
10206: }
10207: 
10208: sub noninst_users {
10209:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
10210:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
10211:     my $class = 'LC_left_item';
10212:     if ($css_class) {
10213:         $css_class = ' class="'.$css_class.'"'; 
10214:     }
10215:     if ($rowid) {
10216:         $rowid = ' id="'.$rowid.'"';
10217:     }
10218:     if ($rowstyle) {
10219:         $rowstyle = ' style="'.$rowstyle.'"';
10220:     }
10221:     my ($output,$description);
10222:     if ($type eq 'default') {
10223:         $description = &mt('Requests for: [_1]',$typetitle);
10224:     } else {
10225:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
10226:     }
10227:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
10228:               "<td>$description</td>\n".           
10229:               '<td class="'.$class.'" colspan="2">'.
10230:               '<table><tr>';
10231:     my %headers = &Apache::lonlocal::texthash( 
10232:               approve  => 'Processing',
10233:               email    => 'E-mail',
10234:               username => 'Username',
10235:     );
10236:     foreach my $item ('approve','email','username') {
10237:         $output .= '<th>'.$headers{$item}.'</th>';
10238:     }
10239:     $output .= '</tr><tr>';
10240:     foreach my $item ('approve','email','username') {
10241:         $output .= '<td style="vertical-align: top">';
10242:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
10243:         if ($item eq 'approve') {
10244:             %choices = &Apache::lonlocal::texthash (
10245:                                                      automatic => 'Automatically approved',
10246:                                                      approval  => 'Queued for approval',
10247:                                                    );
10248:             @options = ('automatic','approval');
10249:             $hashref = $processing;
10250:             $defoption = 'automatic';
10251:             $name = 'cancreate_emailprocess_'.$type;
10252:         } elsif ($item eq 'email') {
10253:             %choices = &Apache::lonlocal::texthash (
10254:                                                      any     => 'Any e-mail',
10255:                                                      inst    => 'Institutional only',
10256:                                                      noninst => 'Non-institutional only',
10257:                                                      custom  => 'Custom restrictions',
10258:                                                    );
10259:             @options = ('any','inst','noninst');
10260:             my $showcustom;
10261:             if (ref($emailrules) eq 'HASH') {
10262:                 if (keys(%{$emailrules}) > 0) {
10263:                     push(@options,'custom');
10264:                     $showcustom = 'cancreate_emailrule';
10265:                     if (ref($settings) eq 'HASH') {
10266:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
10267:                             foreach my $rule (@{$settings->{'email_rule'}}) {
10268:                                 if (exists($emailrules->{$rule})) {
10269:                                     $hascustom ++;
10270:                                 }
10271:                             }
10272:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
10273:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
10274:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
10275:                                     if (exists($emailrules->{$rule})) {
10276:                                         $hascustom ++;
10277:                                     }
10278:                                 }
10279:                             }
10280:                         }
10281:                     }
10282:                 }
10283:             }
10284:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
10285:                                                      "'cancreate_emaildomain','$type'".');"';
10286:             $hashref = $emailoptions;
10287:             $defoption = 'any';
10288:             $name = 'cancreate_emailoptions_'.$type;
10289:         } elsif ($item eq 'username') {
10290:             %choices = &Apache::lonlocal::texthash (
10291:                                                      all    => 'Same as e-mail',
10292:                                                      first  => 'Omit @domain',
10293:                                                      free   => 'Free to choose',
10294:                                                    );
10295:             @options = ('all','first','free');
10296:             $hashref = $emailverified;
10297:             $defoption = 'all';
10298:             $name = 'cancreate_usernameoptions_'.$type;
10299:         }
10300:         foreach my $option (@options) {
10301:             my $checked;
10302:             if (ref($hashref) eq 'HASH') {
10303:                 if ($type eq '') {
10304:                     if (!exists($hashref->{'default'})) {
10305:                         if ($option eq $defoption) {
10306:                             $checked = ' checked="checked"';
10307:                         }
10308:                     } else {
10309:                         if ($hashref->{'default'} eq $option) {
10310:                             $checked = ' checked="checked"';
10311:                         }
10312:                     }
10313:                 } else {
10314:                     if (!exists($hashref->{$type})) {
10315:                         if ($option eq $defoption) {
10316:                             $checked = ' checked="checked"';
10317:                         }
10318:                     } else {
10319:                         if ($hashref->{$type} eq $option) {
10320:                             $checked = ' checked="checked"';
10321:                         }
10322:                     }
10323:                 }
10324:             } elsif (($item eq 'email') && ($hascustom)) {
10325:                 if ($option eq 'custom') {
10326:                     $checked = ' checked="checked"';
10327:                 }
10328:             } elsif ($option eq $defoption) {
10329:                 $checked = ' checked="checked"';
10330:             }
10331:             $output .= '<span class="LC_nobreak"><label>'.
10332:                        '<input type="radio" name="'.$name.'"'.
10333:                        $checked.' value="'.$option.'"'.$onclick.' />'.
10334:                        $choices{$option}.'</label></span><br />';
10335:             if ($item eq 'email') {
10336:                 if ($option eq 'custom') {
10337:                     my $id = 'cancreate_emailrule_'.$type;
10338:                     my $display = 'none';
10339:                     if ($checked) {
10340:                         $display = 'inline';
10341:                     }
10342:                     my $numinrow = 2;
10343:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
10344:                                '<legend>'.&mt('Disallow').'</legend><table>'.
10345:                                &user_formats_row('email',$settings,$emailrules,
10346:                                                  $emailruleorder,$numinrow,'',$type);
10347:                               '</table></fieldset>';
10348:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
10349:                     my %text = &Apache::lonlocal::texthash (
10350:                                                              inst    => 'must end:',
10351:                                                              noninst => 'cannot end:',
10352:                                                            );
10353:                     my $value;
10354:                     if (ref($emaildomain) eq 'HASH') {
10355:                         if (ref($emaildomain->{$type}) eq 'HASH') {
10356:                             $value = $emaildomain->{$type}->{$option}; 
10357:                         }
10358:                     }
10359:                     if ($value eq '') {
10360:                         $value = '@'.$intdom;
10361:                     }
10362:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
10363:                     my $display = 'none';
10364:                     if ($checked) {
10365:                         $display = 'inline';
10366:                     }
10367:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
10368:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
10369:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
10370:                                '</div>';
10371:                 }
10372:             }
10373:         }
10374:         $output .= '</td>'."\n";
10375:     }
10376:     $output .= "</tr></table></td></tr>\n";
10377:     return $output;
10378: }
10379: 
10380: sub captcha_choice {
10381:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
10382:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
10383:         $vertext,$currver);
10384:     my %lt = &captcha_phrases();
10385:     $keyentry = 'hidden';
10386:     my $colspan=2;
10387:     if ($context eq 'cancreate') {
10388:         $rowname = &mt('CAPTCHA validation');
10389:     } elsif ($context eq 'login') {
10390:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
10391:     } elsif ($context eq 'passwords') {
10392:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
10393:         $colspan=1;
10394:     }
10395:     if (ref($settings) eq 'HASH') {
10396:         if ($settings->{'captcha'}) {
10397:             $checked{$settings->{'captcha'}} = ' checked="checked"';
10398:         } else {
10399:             $checked{'original'} = ' checked="checked"';
10400:         }
10401:         if ($settings->{'captcha'} eq 'recaptcha') {
10402:             $pubtext = $lt{'pub'};
10403:             $privtext = $lt{'priv'};
10404:             $keyentry = 'text';
10405:             $vertext = $lt{'ver'};
10406:             $currver = $settings->{'recaptchaversion'};
10407:             if ($currver ne '2') {
10408:                 $currver = 1;
10409:             }
10410:         }
10411:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
10412:             $currpub = $settings->{'recaptchakeys'}{'public'};
10413:             $currpriv = $settings->{'recaptchakeys'}{'private'};
10414:         }
10415:     } else {
10416:         $checked{'original'} = ' checked="checked"';
10417:     }
10418:     my $css_class;
10419:     if ($itemcount%2) {
10420:         $css_class = 'LC_odd_row';
10421:     }
10422:     if ($customcss) {
10423:         $css_class .= " $customcss";
10424:     }
10425:     $css_class =~ s/^\s+//;
10426:     if ($css_class) {
10427:         $css_class = ' class="'.$css_class.'"';
10428:     }
10429:     if ($rowstyle) {
10430:         $css_class .= ' style="'.$rowstyle.'"';
10431:     }
10432:     my $output = '<tr'.$css_class.'>'.
10433:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
10434:                  '<table><tr><td>'."\n";
10435:     foreach my $option ('original','recaptcha','notused') {
10436:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
10437:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
10438:                    $lt{$option}.'</label></span>';
10439:         unless ($option eq 'notused') {
10440:             $output .= ('&nbsp;'x2)."\n";
10441:         }
10442:     }
10443: #
10444: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
10445: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
10446: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
10447: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
10448: #
10449:     $output .= '</td></tr>'."\n".
10450:                '<tr><td class="LC_zero_height">'."\n".
10451:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
10452:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
10453:                $currpub.'" size="40" /></span><br />'."\n".
10454:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
10455:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
10456:                $currpriv.'" size="40" /></span><br />'.
10457:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
10458:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
10459:                $currver.'" size="3" /></span><br />'.
10460:                '</td></tr></table>'."\n".
10461:                '</td></tr>';
10462:     return $output;
10463: }
10464: 
10465: sub user_formats_row {
10466:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
10467:     my $output;
10468:     my %text = (
10469:                    'username' => 'new usernames',
10470:                    'id'       => 'IDs',
10471:                );
10472:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10473:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
10474:         $output = '<tr '.$css_class.'>'.
10475:                   '<td><span class="LC_nobreak">'.
10476:                   &mt("Format rules to check for $text{$type}: ").
10477:                   '</td><td class="LC_left_item" colspan="2"><table>';
10478:     }
10479:     my $rem;
10480:     if (ref($ruleorder) eq 'ARRAY') {
10481:         for (my $i=0; $i<@{$ruleorder}; $i++) {
10482:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
10483:                 my $rem = $i%($numinrow);
10484:                 if ($rem == 0) {
10485:                     if ($i > 0) {
10486:                         $output .= '</tr>';
10487:                     }
10488:                     $output .= '<tr>';
10489:                 }
10490:                 my $check = ' ';
10491:                 if (ref($settings) eq 'HASH') {
10492:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
10493:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
10494:                             $check = ' checked="checked" ';
10495:                         }
10496:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
10497:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
10498:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
10499:                                 $check = ' checked="checked" ';
10500:                             }
10501:                         }
10502:                     }
10503:                 }
10504:                 my $name = $type.'_rule';
10505:                 if ($type eq 'email') {
10506:                     $name .= '_'.$status;
10507:                 }
10508:                 $output .= '<td class="LC_left_item">'.
10509:                            '<span class="LC_nobreak"><label>'.
10510:                            '<input type="checkbox" name="'.$name.'" '.
10511:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
10512:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
10513:             }
10514:         }
10515:         $rem = @{$ruleorder}%($numinrow);
10516:     }
10517:     my $colsleft;
10518:     if ($rem) {
10519:         $colsleft = $numinrow - $rem;
10520:     }
10521:     if ($colsleft > 1 ) {
10522:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10523:                    '&nbsp;</td>';
10524:     } elsif ($colsleft == 1) {
10525:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10526:     }
10527:     $output .= '</tr>';
10528:     unless (($type eq 'email') || ($type eq 'unamemap')) {
10529:         $output .= '</table></td></tr>';
10530:     }
10531:     return $output;
10532: }
10533: 
10534: sub usercreation_types {
10535:     my %lt = &Apache::lonlocal::texthash (
10536:                     author     => 'When adding a co-author',
10537:                     course     => 'When adding a user to a course',
10538:                     requestcrs => 'When requesting a course',
10539:                     any        => 'Any',
10540:                     official   => 'Institutional only ',
10541:                     unofficial => 'Non-institutional only',
10542:                     none       => 'None',
10543:     );
10544:     return %lt;
10545: }
10546: 
10547: sub selfcreation_types {
10548:     my %lt = &Apache::lonlocal::texthash (
10549:                     selfcreate => 'User creates own account',
10550:                     any        => 'Any',
10551:                     official   => 'Institutional only ',
10552:                     unofficial => 'Non-institutional only',
10553:                     email      => 'E-mail address',
10554:                     login      => 'Institutional Login',
10555:                     sso        => 'SSO',
10556:              );
10557: }
10558: 
10559: sub authtype_names {
10560:     my %lt = &Apache::lonlocal::texthash(
10561:                       int    => 'Internal',
10562:                       krb4   => 'Kerberos 4',
10563:                       krb5   => 'Kerberos 5',
10564:                       loc    => 'Local',
10565:                       lti    => 'LTI',
10566:                   );
10567:     return %lt;
10568: }
10569: 
10570: sub context_names {
10571:     my %context_title = &Apache::lonlocal::texthash(
10572:        author => 'Creating users when an Author',
10573:        course => 'Creating users when in a course',
10574:        domain => 'Creating users when a Domain Coordinator',
10575:     );
10576:     return %context_title;
10577: }
10578: 
10579: sub print_usermodification {
10580:     my ($position,$dom,$settings,$rowtotal) = @_;
10581:     my $numinrow = 4;
10582:     my ($context,$datatable,$rowcount);
10583:     if ($position eq 'top') {
10584:         $rowcount = 0;
10585:         $context = 'author'; 
10586:         foreach my $role ('ca','aa') {
10587:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10588:                                                    $numinrow,$rowcount);
10589:             $$rowtotal ++;
10590:             $rowcount ++;
10591:         }
10592:     } elsif ($position eq 'bottom') {
10593:         $context = 'course';
10594:         $rowcount = 0;
10595:         foreach my $role ('st','ep','ta','in','cr') {
10596:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10597:                                                    $numinrow,$rowcount);
10598:             $$rowtotal ++;
10599:             $rowcount ++;
10600:         }
10601:     }
10602:     return $datatable;
10603: }
10604: 
10605: sub print_defaults {
10606:     my ($position,$dom,$settings,$rowtotal) = @_;
10607:     my $rownum = 0;
10608:     my ($datatable,$css_class,$titles);
10609:     unless ($position eq 'bottom') {
10610:         $titles = &defaults_titles($dom);
10611:     }
10612:     if ($position eq 'top') {
10613:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
10614:                      'datelocale_def','portal_def');
10615:         my %defaults;
10616:         if (ref($settings) eq 'HASH') {
10617:             %defaults = %{$settings};
10618:         } else {
10619:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10620:             foreach my $item (@items) {
10621:                 $defaults{$item} = $domdefaults{$item};
10622:             }
10623:         }
10624:         foreach my $item (@items) {
10625:             if ($rownum%2) {
10626:                 $css_class = '';
10627:             } else {
10628:                 $css_class = ' class="LC_odd_row" ';
10629:             }
10630:             $datatable .= '<tr'.$css_class.'>'.
10631:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
10632:                           '</span></td><td class="LC_right_item" colspan="3">';
10633:             if ($item eq 'auth_def') {
10634:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
10635:                 my %shortauth = (
10636:                                  internal => 'int',
10637:                                  krb4 => 'krb4',
10638:                                  krb5 => 'krb5',
10639:                                  localauth  => 'loc',
10640:                                  lti => 'lti',
10641:                                 );
10642:                 my %authnames = &authtype_names();
10643:                 foreach my $auth (@authtypes) {
10644:                     my $checked = ' ';
10645:                     if ($defaults{$item} eq $auth) {
10646:                         $checked = ' checked="checked" ';
10647:                     }
10648:                     $datatable .= '<label><input type="radio" name="'.$item.
10649:                                   '" value="'.$auth.'"'.$checked.'/>'.
10650:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
10651:                 }
10652:             } elsif ($item eq 'timezone_def') {
10653:                 my $includeempty = 1;
10654:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
10655:             } elsif ($item eq 'datelocale_def') {
10656:                 my $includeempty = 1;
10657:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
10658:             } elsif ($item eq 'lang_def') {
10659:                 my $includeempty = 1;
10660:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
10661:             } else {
10662:                 my $size;
10663:                 if ($item eq 'portal_def') {
10664:                     $size = ' size="25"';
10665:                 }
10666:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
10667:                               $defaults{$item}.'"'.$size.' />';
10668:             }
10669:             $datatable .= '</td></tr>';
10670:             $rownum ++;
10671:         }
10672:     } elsif ($position eq 'middle') {
10673:         my %defaults;
10674:         if (ref($settings) eq 'HASH') {
10675:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10676:                 my $maxnum = @{$settings->{'inststatusorder'}};
10677:                 for (my $i=0; $i<$maxnum; $i++) {
10678:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
10679:                     my $item = $settings->{'inststatusorder'}->[$i];
10680:                     my $title = $settings->{'inststatustypes'}->{$item};
10681:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
10682:                     $datatable .= '<tr'.$css_class.'>'.
10683:                                   '<td><span class="LC_nobreak">'.
10684:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
10685:                     for (my $k=0; $k<=$maxnum; $k++) {
10686:                         my $vpos = $k+1;
10687:                         my $selstr;
10688:                         if ($k == $i) {
10689:                             $selstr = ' selected="selected" ';
10690:                         }
10691:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10692:                     }
10693:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
10694:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
10695:                                   &mt('delete').'</span></td>'.
10696:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
10697:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
10698:                                   '</span></td></tr>';
10699:                 }
10700:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
10701:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
10702:                 $datatable .= '<tr '.$css_class.'>'.
10703:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
10704:                 for (my $k=0; $k<=$maxnum; $k++) {
10705:                     my $vpos = $k+1;
10706:                     my $selstr;
10707:                     if ($k == $maxnum) {
10708:                         $selstr = ' selected="selected" ';
10709:                     }
10710:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10711:                 }
10712:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
10713:                               '<input type="text" size="10" name="addinststatus" value="" />'.
10714:                               '&nbsp;'.&mt('(new)').
10715:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
10716:                               &mt('Name displayed').':'.
10717:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
10718:                               '</tr>'."\n";
10719:                 $rownum ++;
10720:             }
10721:         }
10722:     } else {
10723:         my ($unamemaprules,$ruleorder) =
10724:             &Apache::lonnet::inst_userrules($dom,'unamemap');
10725:         $css_class = $rownum%2?' class="LC_odd_row"':'';
10726:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
10727:             my $numinrow = 2;
10728:             $datatable .= '<tr'.$css_class.'><td>'.&mt('Available conversions').'</td><td><table>'.
10729:                           &user_formats_row('unamemap',$settings,$unamemaprules,
10730:                                             $ruleorder,$numinrow).
10731:                           '</table></td></tr>';
10732:         }
10733:         if ($datatable eq '') {
10734:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
10735:                           &mt('No rules set for domain in customized localenroll.pm').
10736:                           '</td></tr>';
10737:         }
10738:     }
10739:     $$rowtotal += $rownum;
10740:     return $datatable;
10741: }
10742: 
10743: sub get_languages_hash {
10744:     my %langchoices;
10745:     foreach my $id (&Apache::loncommon::languageids()) {
10746:         my $code = &Apache::loncommon::supportedlanguagecode($id);
10747:         if ($code ne '') {
10748:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
10749:         }
10750:     }
10751:     return %langchoices;
10752: }
10753: 
10754: sub defaults_titles {
10755:     my ($dom) = @_;
10756:     my %titles = &Apache::lonlocal::texthash (
10757:                    'auth_def'      => 'Default authentication type',
10758:                    'auth_arg_def'  => 'Default authentication argument',
10759:                    'lang_def'      => 'Default language',
10760:                    'timezone_def'  => 'Default timezone',
10761:                    'datelocale_def' => 'Default locale for dates',
10762:                    'portal_def'     => 'Portal/Default URL',
10763:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
10764:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
10765:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
10766:                  );
10767:     if ($dom) {
10768:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
10769:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
10770:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
10771:         $protocol = 'http' if ($protocol ne 'https');
10772:         if ($uint_dom) {
10773:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
10774:                                          $uint_dom);
10775:         }
10776:     }
10777:     return (\%titles);
10778: }
10779: 
10780: sub print_scantron {
10781:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
10782:     if ($position eq 'top') {
10783:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
10784:     } else {
10785:         return &print_scantronconfig($dom,$settings,\$rowtotal);
10786:     }
10787: }
10788: 
10789: sub scantron_javascript {
10790:     return <<"ENDSCRIPT";
10791: 
10792: <script type="text/javascript">
10793: // <![CDATA[
10794: 
10795: function toggleScantron(form) {
10796:     var csvfieldset = new Array();
10797:     if (document.getElementById('scantroncsv_cols')) {
10798:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
10799:     }
10800:     if (document.getElementById('scantroncsv_options')) {
10801:         csvfieldset.push(document.getElementById('scantroncsv_options'));
10802:     }
10803:     if (csvfieldset.length) {
10804:         if (document.getElementById('scantronconfcsv')) {
10805:             var scantroncsv = document.getElementById('scantronconfcsv');
10806:             if (scantroncsv.checked) {
10807:                 for (var i=0; i<csvfieldset.length; i++) {
10808:                     csvfieldset[i].style.display = 'block';
10809:                 }
10810:             } else {
10811:                 for (var i=0; i<csvfieldset.length; i++) {
10812:                     csvfieldset[i].style.display = 'none';
10813:                 }
10814:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
10815:                 if (csvselects.length) {
10816:                     for (var j=0; j<csvselects.length; j++) {
10817:                         csvselects[j].selectedIndex = 0;
10818:                     }
10819:                 }
10820:             }
10821:         }
10822:     }
10823:     return;
10824: }
10825: // ]]>
10826: </script>
10827: 
10828: ENDSCRIPT
10829: 
10830: }
10831: 
10832: sub print_scantronformat {
10833:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10834:     my $itemcount = 1;
10835:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10836:         %confhash);
10837:     my $switchserver = &check_switchserver($dom,$confname);
10838:     my %lt = &Apache::lonlocal::texthash (
10839:                 default => 'Default bubblesheet format file error',
10840:                 custom  => 'Custom bubblesheet format file error',
10841:              );
10842:     my %scantronfiles = (
10843:         default => 'default.tab',
10844:         custom => 'custom.tab',
10845:     );
10846:     foreach my $key (keys(%scantronfiles)) {
10847:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10848:                               .$scantronfiles{$key};
10849:     }
10850:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10851:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10852:         if (!$switchserver) {
10853:             my $servadm = $r->dir_config('lonAdmEMail');
10854:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10855:             if ($configuserok eq 'ok') {
10856:                 if ($author_ok eq 'ok') {
10857:                     my %legacyfile = (
10858:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10859:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10860:                     );
10861:                     my %md5chk;
10862:                     foreach my $type (keys(%legacyfile)) {
10863:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10864:                         chomp($md5chk{$type});
10865:                     }
10866:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10867:                         foreach my $type (keys(%legacyfile)) {
10868:                             ($scantronurls{$type},my $error) =
10869:                                 &legacy_scantronformat($r,$dom,$confname,
10870:                                                  $type,$legacyfile{$type},
10871:                                                  $scantronurls{$type},
10872:                                                  $scantronfiles{$type});
10873:                             if ($error ne '') {
10874:                                 $error{$type} = $error;
10875:                             }
10876:                         }
10877:                         if (keys(%error) == 0) {
10878:                             $is_custom = 1;
10879:                             $confhash{'scantron'}{'scantronformat'} =
10880:                                 $scantronurls{'custom'};
10881:                             my $putresult =
10882:                                 &Apache::lonnet::put_dom('configuration',
10883:                                                          \%confhash,$dom);
10884:                             if ($putresult ne 'ok') {
10885:                                 $error{'custom'} =
10886:                                     '<span class="LC_error">'.
10887:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10888:                             }
10889:                         }
10890:                     } else {
10891:                         ($scantronurls{'default'},my $error) =
10892:                             &legacy_scantronformat($r,$dom,$confname,
10893:                                           'default',$legacyfile{'default'},
10894:                                           $scantronurls{'default'},
10895:                                           $scantronfiles{'default'});
10896:                         if ($error eq '') {
10897:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10898:                             my $putresult =
10899:                                 &Apache::lonnet::put_dom('configuration',
10900:                                                          \%confhash,$dom);
10901:                             if ($putresult ne 'ok') {
10902:                                 $error{'default'} =
10903:                                     '<span class="LC_error">'.
10904:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10905:                             }
10906:                         } else {
10907:                             $error{'default'} = $error;
10908:                         }
10909:                     }
10910:                 }
10911:             }
10912:         } else {
10913:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10914:         }
10915:     }
10916:     if (ref($settings) eq 'HASH') {
10917:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10918:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10919:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10920:                 $scantronurl = '';
10921:             } else {
10922:                 $scantronurl = $settings->{'scantronformat'};
10923:             }
10924:             $is_custom = 1;
10925:         } else {
10926:             $scantronurl = $scantronurls{'default'};
10927:         }
10928:     } else {
10929:         if ($is_custom) {
10930:             $scantronurl = $scantronurls{'custom'};
10931:         } else {
10932:             $scantronurl = $scantronurls{'default'};
10933:         }
10934:     }
10935:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10936:     $datatable .= '<tr'.$css_class.'>';
10937:     if (!$is_custom) {
10938:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
10939:                       '<span class="LC_nobreak">';
10940:         if ($scantronurl) {
10941:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
10942:                                                          undef,undef,undef,undef,'background-color:#ffffff');
10943:         } else {
10944:             $datatable = &mt('File unavailable for display');
10945:         }
10946:         $datatable .= '</span></td>';
10947:         if (keys(%error) == 0) { 
10948:             $datatable .= '<td style="vertical-align: bottom">';
10949:             if (!$switchserver) {
10950:                 $datatable .= &mt('Upload:').'<br />';
10951:             }
10952:         } else {
10953:             my $errorstr;
10954:             foreach my $key (sort(keys(%error))) {
10955:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10956:             }
10957:             $datatable .= '<td>'.$errorstr;
10958:         }
10959:     } else {
10960:         if (keys(%error) > 0) {
10961:             my $errorstr;
10962:             foreach my $key (sort(keys(%error))) {
10963:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10964:             } 
10965:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
10966:         } elsif ($scantronurl) {
10967:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
10968:                                                        undef,undef,undef,undef,'background-color:#ffffff');
10969:             $datatable .= '<td><span class="LC_nobreak">'.
10970:                           $link.
10971:                           '<label><input type="checkbox" name="scantronformat_del"'.
10972:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
10973:                           '<td><span class="LC_nobreak">&nbsp;'.
10974:                           &mt('Replace:').'</span><br />';
10975:         }
10976:     }
10977:     if (keys(%error) == 0) {
10978:         if ($switchserver) {
10979:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
10980:         } else {
10981:             $datatable .='<span class="LC_nobreak">&nbsp;'.
10982:                          '<input type="file" name="scantronformat" /></span>';
10983:         }
10984:     }
10985:     $datatable .= '</td></tr>';
10986:     $$rowtotal ++;
10987:     return $datatable;
10988: }
10989: 
10990: sub legacy_scantronformat {
10991:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
10992:     my ($url,$error);
10993:     my @statinfo = &Apache::lonnet::stat_file($newurl);
10994:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
10995:         (my $result,$url) =
10996:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
10997:                          '','',$newfile);
10998:         if ($result ne 'ok') {
10999:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
11000:         }
11001:     }
11002:     return ($url,$error);
11003: }
11004: 
11005: sub print_scantronconfig {
11006:     my ($dom,$settings,$rowtotal) = @_;
11007:     my $itemcount = 2;
11008:     my $is_checked = ' checked="checked"';
11009:     my %optionson = (
11010:                      hdr => ' checked="checked"',
11011:                      pad => ' checked="checked"',
11012:                      rem => ' checked="checked"',
11013:                     );
11014:     my %optionsoff = (
11015:                       hdr => '',
11016:                       pad => '',
11017:                       rem => '',
11018:                      );
11019:     my $currcsvsty = 'none';
11020:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
11021:     my @fields = &scantroncsv_fields();
11022:     my %titles = &scantronconfig_titles();
11023:     if (ref($settings) eq 'HASH') {
11024:         if (ref($settings->{config}) eq 'HASH') {
11025:             if ($settings->{config}->{dat}) {
11026:                 $checked{'dat'} = $is_checked;
11027:             }
11028:             if (ref($settings->{config}->{csv}) eq 'HASH') {
11029:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
11030:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
11031:                     if (keys(%csvfields) > 0) {
11032:                         $checked{'csv'} = $is_checked;
11033:                         $currcsvsty = 'block';
11034:                     }
11035:                 }
11036:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
11037:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
11038:                     foreach my $option (keys(%optionson)) {
11039:                         unless ($csvoptions{$option}) {
11040:                             $optionsoff{$option} = $optionson{$option};
11041:                             $optionson{$option} = '';
11042:                         }
11043:                     }
11044:                 }
11045:             }
11046:         } else {
11047:             $checked{'dat'} = $is_checked;
11048:         }
11049:     } else {
11050:         $checked{'dat'} = $is_checked;
11051:     }
11052:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
11053:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11054:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
11055:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
11056:     foreach my $item ('dat','csv') {
11057:         my $id;
11058:         if ($item eq 'csv') {
11059:             $id = 'id="scantronconfcsv" ';
11060:         }
11061:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
11062:                       $titles{$item}.'</label>'.('&nbsp;'x3);
11063:         if ($item eq 'csv') {
11064:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
11065:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
11066:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
11067:             foreach my $col (@fields) {
11068:                 my $selnone;
11069:                 if ($csvfields{$col} eq '') {
11070:                     $selnone = ' selected="selected"';
11071:                 }
11072:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
11073:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
11074:                               '<option value=""'.$selnone.'></option>';
11075:                 for (my $i=0; $i<20; $i++) {
11076:                     my $shown = $i+1;
11077:                     my $sel;
11078:                     unless ($selnone) {
11079:                         if (exists($csvfields{$col})) {
11080:                             if ($csvfields{$col} == $i) {
11081:                                 $sel = ' selected="selected"';
11082:                             }
11083:                         }
11084:                     }
11085:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
11086:                 }
11087:                 $datatable .= '</select></td></tr>';
11088:            }
11089:            $datatable .= '</table></fieldset>'.
11090:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
11091:                          '<legend>'.&mt('CSV Options').'</legend>';
11092:            foreach my $option ('hdr','pad','rem') {
11093:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
11094:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
11095:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
11096:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
11097:            }
11098:            $datatable .= '</fieldset>';
11099:            $itemcount ++;
11100:         }
11101:     }
11102:     $datatable .= '</td></tr>';
11103:     $$rowtotal ++;
11104:     return $datatable;
11105: }
11106: 
11107: sub scantronconfig_titles {
11108:     return &Apache::lonlocal::texthash(
11109:                                           dat => 'Standard format (.dat)',
11110:                                           csv => 'Comma separated values (.csv)',
11111:                                           hdr => 'Remove first line in file (contains column titles)',
11112:                                           pad => 'Prepend 0s to PaperID',
11113:                                           rem => 'Remove leading spaces (except Question Response columns)',
11114:                                           CODE => 'CODE',
11115:                                           ID   => 'Student ID',
11116:                                           PaperID => 'Paper ID',
11117:                                           FirstName => 'First Name',
11118:                                           LastName => 'Last Name',
11119:                                           FirstQuestion => 'First Question Response',
11120:                                           Section => 'Section',
11121:     );
11122: }
11123: 
11124: sub scantroncsv_fields {
11125:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
11126: }
11127: 
11128: sub print_coursecategories {
11129:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
11130:     my $datatable;
11131:     if ($position eq 'top') {
11132:         my (%checked);
11133:         my @catitems = ('unauth','auth');
11134:         my @cattypes = ('std','domonly','codesrch','none');
11135:         $checked{'unauth'} = 'std';
11136:         $checked{'auth'} = 'std';
11137:         if (ref($settings) eq 'HASH') {
11138:             foreach my $type (@cattypes) {
11139:                 if ($type eq $settings->{'unauth'}) {
11140:                     $checked{'unauth'} = $type;
11141:                 }
11142:                 if ($type eq $settings->{'auth'}) {
11143:                     $checked{'auth'} = $type;
11144:                 }
11145:             }
11146:         }
11147:         my %lt = &Apache::lonlocal::texthash (
11148:                                                unauth   => 'Catalog type for unauthenticated users',
11149:                                                auth     => 'Catalog type for authenticated users',
11150:                                                none     => 'No catalog',
11151:                                                std      => 'Standard catalog',
11152:                                                domonly  => 'Domain-only catalog',
11153:                                                codesrch => "Code search form",
11154:                                              );
11155:        my $itemcount = 0;
11156:        foreach my $item (@catitems) {
11157:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11158:            $datatable .= '<tr '.$css_class.'>'.
11159:                          '<td>'.$lt{$item}.'</td>'.
11160:                          '<td class="LC_right_item"><span class="LC_nobreak">';
11161:            foreach my $type (@cattypes) {
11162:                my $ischecked;
11163:                if ($checked{$item} eq $type) {
11164:                    $ischecked=' checked="checked"';
11165:                }
11166:                $datatable .= '<label>'.
11167:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
11168:                              ' />'.$lt{$type}.'</label>&nbsp;';
11169:            }
11170:            $datatable .= '</span></td></tr>';
11171:            $itemcount ++;
11172:         }
11173:         $$rowtotal += $itemcount;
11174:     } elsif ($position eq 'middle') {
11175:         my $toggle_cats_crs = ' ';
11176:         my $toggle_cats_dom = ' checked="checked" ';
11177:         my $can_cat_crs = ' ';
11178:         my $can_cat_dom = ' checked="checked" ';
11179:         my $toggle_catscomm_comm = ' ';
11180:         my $toggle_catscomm_dom = ' checked="checked" ';
11181:         my $can_catcomm_comm = ' ';
11182:         my $can_catcomm_dom = ' checked="checked" ';
11183:         my $toggle_catsplace_place = ' ';
11184:         my $toggle_catsplace_dom = ' checked="checked" ';
11185:         my $can_catplace_place = ' ';
11186:         my $can_catplace_dom = ' checked="checked" ';
11187: 
11188:         if (ref($settings) eq 'HASH') {
11189:             if ($settings->{'togglecats'} eq 'crs') {
11190:                 $toggle_cats_crs = $toggle_cats_dom;
11191:                 $toggle_cats_dom = ' ';
11192:             }
11193:             if ($settings->{'categorize'} eq 'crs') {
11194:                 $can_cat_crs = $can_cat_dom;
11195:                 $can_cat_dom = ' ';
11196:             }
11197:             if ($settings->{'togglecatscomm'} eq 'comm') {
11198:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
11199:                 $toggle_catscomm_dom = ' ';
11200:             }
11201:             if ($settings->{'categorizecomm'} eq 'comm') {
11202:                 $can_catcomm_comm = $can_catcomm_dom;
11203:                 $can_catcomm_dom = ' ';
11204:             }
11205:             if ($settings->{'togglecatsplace'} eq 'place') {
11206:                 $toggle_catsplace_place = $toggle_catsplace_dom;
11207:                 $toggle_catsplace_dom = ' ';
11208:             }
11209:             if ($settings->{'categorizeplace'} eq 'place') {
11210:                 $can_catplace_place = $can_catplace_dom;
11211:                 $can_catplace_dom = ' ';
11212:             }
11213:         }
11214:         my %title = &Apache::lonlocal::texthash (
11215:                      togglecats      => 'Show/Hide a course in catalog',
11216:                      togglecatscomm  => 'Show/Hide a community in catalog',
11217:                      togglecatsplace => 'Show/Hide a placement test in catalog',
11218:                      categorize      => 'Assign a category to a course',
11219:                      categorizecomm  => 'Assign a category to a community',
11220:                      categorizeplace => 'Assign a category to a placement test',
11221:                     );
11222:         my %level = &Apache::lonlocal::texthash (
11223:                      dom   => 'Set in Domain',
11224:                      crs   => 'Set in Course',
11225:                      comm  => 'Set in Community',
11226:                      place => 'Set in Placement Test',
11227:                     );
11228:         $datatable = '<tr class="LC_odd_row">'.
11229:                   '<td>'.$title{'togglecats'}.'</td>'.
11230:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11231:                   '<input type="radio" name="togglecats"'.
11232:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11233:                   '<label><input type="radio" name="togglecats"'.
11234:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
11235:                   '</tr><tr>'.
11236:                   '<td>'.$title{'categorize'}.'</td>'.
11237:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11238:                   '<label><input type="radio" name="categorize"'.
11239:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11240:                   '<label><input type="radio" name="categorize"'.
11241:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
11242:                   '</tr><tr class="LC_odd_row">'.
11243:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
11244:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11245:                   '<input type="radio" name="togglecatscomm"'.
11246:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11247:                   '<label><input type="radio" name="togglecatscomm"'.
11248:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
11249:                   '</tr><tr>'.
11250:                   '<td>'.$title{'categorizecomm'}.'</td>'.
11251:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11252:                   '<label><input type="radio" name="categorizecomm"'.
11253:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11254:                   '<label><input type="radio" name="categorizecomm"'.
11255:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
11256:                   '</tr><tr class="LC_odd_row">'.
11257:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
11258:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11259:                   '<input type="radio" name="togglecatsplace"'.
11260:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11261:                   '<label><input type="radio" name="togglecatscomm"'.
11262:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
11263:                   '</tr><tr>'.
11264:                   '<td>'.$title{'categorizeplace'}.'</td>'.
11265:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11266:                   '<label><input type="radio" name="categorizeplace"'.
11267:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11268:                   '<label><input type="radio" name="categorizeplace"'.
11269:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
11270:                   '</tr>';
11271:         $$rowtotal += 6;
11272:     } else {
11273:         my $css_class;
11274:         my $itemcount = 1;
11275:         my $cathash; 
11276:         if (ref($settings) eq 'HASH') {
11277:             $cathash = $settings->{'cats'};
11278:         }
11279:         if (ref($cathash) eq 'HASH') {
11280:             my (@cats,@trails,%allitems,%idx,@jsarray);
11281:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
11282:                                                    \%allitems,\%idx,\@jsarray);
11283:             my $maxdepth = scalar(@cats);
11284:             my $colattrib = '';
11285:             if ($maxdepth > 2) {
11286:                 $colattrib = ' colspan="2" ';
11287:             }
11288:             my @path;
11289:             if (@cats > 0) {
11290:                 if (ref($cats[0]) eq 'ARRAY') {
11291:                     my $numtop = @{$cats[0]};
11292:                     my $maxnum = $numtop;
11293:                     my %default_names = (
11294:                           instcode    => &mt('Official courses'),
11295:                           communities => &mt('Communities'),
11296:                           placement   => &mt('Placement Tests'),
11297:                     );
11298: 
11299:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
11300:                         ($cathash->{'instcode::0'} eq '') ||
11301:                         (!grep(/^communities$/,@{$cats[0]})) || 
11302:                         ($cathash->{'communities::0'} eq '') ||
11303:                         (!grep(/^placement$/,@{$cats[0]})) ||
11304:                         ($cathash->{'placement::0'} eq '')) {
11305:                         $maxnum ++;
11306:                     }
11307:                     my $lastidx;
11308:                     for (my $i=0; $i<$numtop; $i++) {
11309:                         my $parent = $cats[0][$i];
11310:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11311:                         my $item = &escape($parent).'::0';
11312:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
11313:                         $lastidx = $idx{$item};
11314:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11315:                                       .'<select name="'.$item.'"'.$chgstr.'>';
11316:                         for (my $k=0; $k<=$maxnum; $k++) {
11317:                             my $vpos = $k+1;
11318:                             my $selstr;
11319:                             if ($k == $i) {
11320:                                 $selstr = ' selected="selected" ';
11321:                             }
11322:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11323:                         }
11324:                         $datatable .= '</select></span></td><td>';
11325:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
11326:                             $datatable .=  '<span class="LC_nobreak">'
11327:                                            .$default_names{$parent}.'</span>';
11328:                             if ($parent eq 'instcode') {
11329:                                 $datatable .= '<br /><span class="LC_nobreak">('
11330:                                               .&mt('with institutional codes')
11331:                                               .')</span></td><td'.$colattrib.'>';
11332:                             } else {
11333:                                 $datatable .= '<table><tr><td>';
11334:                             }
11335:                             $datatable .= '<span class="LC_nobreak">'
11336:                                           .'<label><input type="radio" name="'
11337:                                           .$parent.'" value="1" checked="checked" />'
11338:                                           .&mt('Display').'</label>';
11339:                             if ($parent eq 'instcode') {
11340:                                 $datatable .= '&nbsp;';
11341:                             } else {
11342:                                 $datatable .= '</span></td></tr><tr><td>'
11343:                                               .'<span class="LC_nobreak">';
11344:                             }
11345:                             $datatable .= '<label><input type="radio" name="'
11346:                                           .$parent.'" value="0" />'
11347:                                           .&mt('Do not display').'</label></span>';
11348:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
11349:                                 $datatable .= '</td></tr></table>';
11350:                             }
11351:                             $datatable .= '</td>';
11352:                         } else {
11353:                             $datatable .= $parent
11354:                                           .'&nbsp;<span class="LC_nobreak"><label>'
11355:                                           .'<input type="checkbox" name="deletecategory" '
11356:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
11357:                         }
11358:                         my $depth = 1;
11359:                         push(@path,$parent);
11360:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
11361:                         pop(@path);
11362:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
11363:                         $itemcount ++;
11364:                     }
11365:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11366:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
11367:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
11368:                     for (my $k=0; $k<=$maxnum; $k++) {
11369:                         my $vpos = $k+1;
11370:                         my $selstr;
11371:                         if ($k == $numtop) {
11372:                             $selstr = ' selected="selected" ';
11373:                         }
11374:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11375:                     }
11376:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
11377:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
11378:                                   .'</tr>'."\n";
11379:                     $itemcount ++;
11380:                     foreach my $default ('instcode','communities','placement') {
11381:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
11382:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
11383:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
11384:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
11385:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
11386:                             for (my $k=0; $k<=$maxnum; $k++) {
11387:                                 my $vpos = $k+1;
11388:                                 my $selstr;
11389:                                 if ($k == $maxnum) {
11390:                                     $selstr = ' selected="selected" ';
11391:                                 }
11392:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11393:                             }
11394:                             $datatable .= '</select></span></td>'.
11395:                                           '<td><span class="LC_nobreak">'.
11396:                                           $default_names{$default}.'</span>';
11397:                             if ($default eq 'instcode') {
11398:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
11399:                                               .&mt('with institutional codes').')</span>';
11400:                             }
11401:                             $datatable .= '</td>'
11402:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
11403:                                           .&mt('Display').'</label>&nbsp;'
11404:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
11405:                                           .&mt('Do not display').'</label></span></td></tr>';
11406:                         }
11407:                     }
11408:                 }
11409:             } else {
11410:                 $datatable .= &initialize_categories($itemcount);
11411:             }
11412:         } else {
11413:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
11414:                           .&initialize_categories($itemcount);
11415:         }
11416:         $$rowtotal += $itemcount;
11417:     }
11418:     return $datatable;
11419: }
11420: 
11421: sub print_serverstatuses {
11422:     my ($dom,$settings,$rowtotal) = @_;
11423:     my $datatable;
11424:     my @pages = &serverstatus_pages();
11425:     my (%namedaccess,%machineaccess);
11426:     foreach my $type (@pages) {
11427:         $namedaccess{$type} = '';
11428:         $machineaccess{$type}= '';
11429:     }
11430:     if (ref($settings) eq 'HASH') {
11431:         foreach my $type (@pages) {
11432:             if (exists($settings->{$type})) {
11433:                 if (ref($settings->{$type}) eq 'HASH') {
11434:                     foreach my $key (keys(%{$settings->{$type}})) {
11435:                         if ($key eq 'namedusers') {
11436:                             $namedaccess{$type} = $settings->{$type}->{$key};
11437:                         } elsif ($key eq 'machines') {
11438:                             $machineaccess{$type} = $settings->{$type}->{$key};
11439:                         }
11440:                     }
11441:                 }
11442:             }
11443:         }
11444:     }
11445:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11446:     my $rownum = 0;
11447:     my $css_class;
11448:     foreach my $type (@pages) {
11449:         $rownum ++;
11450:         $css_class = $rownum%2?' class="LC_odd_row"':'';
11451:         $datatable .= '<tr'.$css_class.'>'.
11452:                       '<td><span class="LC_nobreak">'.
11453:                       $titles->{$type}.'</span></td>'.
11454:                       '<td class="LC_left_item">'.
11455:                       '<input type="text" name="'.$type.'_namedusers" '.
11456:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
11457:                       '<td class="LC_right_item">'.
11458:                       '<span class="LC_nobreak">'.
11459:                       '<input type="text" name="'.$type.'_machines" '.
11460:                       'value="'.$machineaccess{$type}.'" size="10" />'.
11461:                       '</span></td></tr>'."\n";
11462:     }
11463:     $$rowtotal += $rownum;
11464:     return $datatable;
11465: }
11466: 
11467: sub serverstatus_pages {
11468:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
11469:             'checksums','clusterstatus','certstatus','metadata_keywords',
11470:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
11471:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
11472: }
11473: 
11474: sub defaults_javascript {
11475:     my ($settings) = @_;
11476:     return unless (ref($settings) eq 'HASH');
11477:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
11478:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
11479:         if ($maxnum eq '') {
11480:             $maxnum = 0;
11481:         }
11482:         $maxnum ++;
11483:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
11484:         return <<"ENDSCRIPT";
11485: <script type="text/javascript">
11486: // <![CDATA[
11487: function reorderTypes(form,caller) {
11488:     var changedVal;
11489: $jstext 
11490:     var newpos = 'addinststatus_pos';
11491:     var current = new Array;
11492:     var maxh = $maxnum;
11493:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11494:     var oldVal;
11495:     if (caller == newpos) {
11496:         changedVal = newitemVal;
11497:     } else {
11498:         var curritem = 'inststatus_pos_'+caller;
11499:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
11500:         current[newitemVal] = newpos;
11501:     }
11502:     for (var i=0; i<inststatuses.length; i++) {
11503:         if (inststatuses[i] != caller) {
11504:             var elementName = 'inststatus_pos_'+inststatuses[i];
11505:             if (form.elements[elementName]) {
11506:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11507:                 current[currVal] = elementName;
11508:             }
11509:         }
11510:     }
11511:     for (var j=0; j<maxh; j++) {
11512:         if (current[j] == undefined) {
11513:             oldVal = j;
11514:         }
11515:     }
11516:     if (oldVal < changedVal) {
11517:         for (var k=oldVal+1; k<=changedVal ; k++) {
11518:            var elementName = current[k];
11519:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11520:         }
11521:     } else {
11522:         for (var k=changedVal; k<oldVal; k++) {
11523:             var elementName = current[k];
11524:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11525:         }
11526:     }
11527:     return;
11528: }
11529: 
11530: // ]]>
11531: </script>
11532: 
11533: ENDSCRIPT
11534:     }
11535:     return;
11536: }
11537: 
11538: sub passwords_javascript {
11539:     my ($prefix) = @_;
11540:     my %intalert;
11541:     if ($prefix eq 'passwords') {
11542:         %intalert = &Apache::lonlocal::texthash (
11543:             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.',
11544:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
11545:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
11546:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
11547:             passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
11548:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
11549:         );
11550:     } elsif ($prefix eq 'secrets') {
11551:         %intalert = &Apache::lonlocal::texthash (
11552:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
11553:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
11554:         );
11555:     }
11556:     &js_escape(\%intalert);
11557:     my $defmin = $Apache::lonnet::passwdmin;
11558:     my $intauthjs; 
11559:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
11560: 
11561: function warnIntAuth(field) {
11562:     if (field.name == 'intauth_check') {
11563:         if (field.value == '2') {
11564:             alert('$intalert{authcheck}');
11565:         }
11566:     }
11567:     if (field.name == 'intauth_cost') {
11568:         field.value.replace(/\s/g,'');
11569:         if (field.value != '') {
11570:             var regexdigit=/^\\d+\$/;
11571:             if (!regexdigit.test(field.value)) {
11572:                 alert('$intalert{authcost}');
11573:             }
11574:         }
11575:     }
11576:     return;
11577: }
11578: 
11579: ENDSCRIPT
11580: 
11581:      }
11582: 
11583:      $intauthjs .= <<"ENDSCRIPT";
11584: 
11585: function warnInt$prefix(field) {
11586:     field.value.replace(/^\s+/,'');
11587:     field.value.replace(/\s+\$/,'');
11588:     var regexdigit=/^\\d+\$/;
11589:     if (field.name == '${prefix}_min') {
11590:         if (field.value == '') {
11591:             alert('$intalert{passmin}');
11592:             field.value = '$defmin';
11593:         } else {
11594:             if (!regexdigit.test(field.value)) {
11595:                 alert('$intalert{passmin}');
11596:                 field.value = '$defmin';
11597:             }
11598:             var minval = parseInt(field.value,10);
11599:             if (minval < $defmin) {
11600:                 alert('$intalert{passmin}');
11601:                 field.value = '$defmin';
11602:             }
11603:         }
11604:     } else {
11605:         if (field.value == '0') {
11606:             field.value = '';
11607:         }
11608:         if (field.value != '') {
11609:             if (field.name == '${prefix}_expire') {
11610:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
11611:                 if (!regexpposnum.test(field.value)) {
11612:                     alert('$intalert{passexp}');
11613:                     field.value = '';
11614:                 } else {
11615:                     var expval = parseFloat(field.value);
11616:                     if (expval == 0) {
11617:                         alert('$intalert{passexp}');
11618:                         field.value = '';
11619:                     }
11620:                 }
11621:             } else {
11622:                 if (!regexdigit.test(field.value)) {
11623:                     if (field.name == '${prefix}_max') {
11624:                         alert('$intalert{passmax}');
11625:                     } else {
11626:                         if (field.name == '${prefix}_numsaved') {
11627:                             alert('$intalert{passnum}');
11628:                         }
11629:                     }
11630:                     field.value = '';
11631:                 }
11632:             }
11633:         }
11634:     }
11635:     return;
11636: }
11637: 
11638: ENDSCRIPT
11639:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
11640: }
11641: 
11642: sub coursecategories_javascript {
11643:     my ($settings) = @_;
11644:     my ($output,$jstext,$cathash);
11645:     if (ref($settings) eq 'HASH') {
11646:         $cathash = $settings->{'cats'};
11647:     }
11648:     if (ref($cathash) eq 'HASH') {
11649:         my (@cats,@jsarray,%idx);
11650:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
11651:         if (@jsarray > 0) {
11652:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
11653:             for (my $i=0; $i<@jsarray; $i++) {
11654:                 if (ref($jsarray[$i]) eq 'ARRAY') {
11655:                     my $catstr = join('","',@{$jsarray[$i]});
11656:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
11657:                 }
11658:             }
11659:         }
11660:     } else {
11661:         $jstext  = '    var categories = Array(1);'."\n".
11662:                    '    categories[0] = Array("instcode_pos");'."\n"; 
11663:     }
11664:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
11665:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
11666:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
11667:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
11668:     &js_escape(\$instcode_reserved);
11669:     &js_escape(\$communities_reserved);
11670:     &js_escape(\$placement_reserved);
11671:     &js_escape(\$choose_again);
11672:     $output = <<"ENDSCRIPT";
11673: <script type="text/javascript">
11674: // <![CDATA[
11675: function reorderCats(form,parent,item,idx) {
11676:     var changedVal;
11677: $jstext
11678:     var newpos = 'addcategory_pos';
11679:     if (parent == '') {
11680:         var has_instcode = 0;
11681:         var maxtop = categories[idx].length;
11682:         for (var j=0; j<maxtop; j++) {
11683:             if (categories[idx][j] == 'instcode::0') {
11684:                 has_instcode == 1;
11685:             }
11686:         }
11687:         if (has_instcode == 0) {
11688:             categories[idx][maxtop] = 'instcode_pos';
11689:         }
11690:     } else {
11691:         newpos += '_'+parent;
11692:     }
11693:     var maxh = 1 + categories[idx].length;
11694:     var current = new Array;
11695:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11696:     if (item == newpos) {
11697:         changedVal = newitemVal;
11698:     } else {
11699:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
11700:         current[newitemVal] = newpos;
11701:     }
11702:     for (var i=0; i<categories[idx].length; i++) {
11703:         var elementName = categories[idx][i];
11704:         if (elementName != item) {
11705:             if (form.elements[elementName]) {
11706:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11707:                 current[currVal] = elementName;
11708:             }
11709:         }
11710:     }
11711:     var oldVal;
11712:     for (var j=0; j<maxh; j++) {
11713:         if (current[j] == undefined) {
11714:             oldVal = j;
11715:         }
11716:     }
11717:     if (oldVal < changedVal) {
11718:         for (var k=oldVal+1; k<=changedVal ; k++) {
11719:            var elementName = current[k];
11720:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11721:         }
11722:     } else {
11723:         for (var k=changedVal; k<oldVal; k++) {
11724:             var elementName = current[k];
11725:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11726:         }
11727:     }
11728:     return;
11729: }
11730: 
11731: function categoryCheck(form) {
11732:     if (form.elements['addcategory_name'].value == 'instcode') {
11733:         alert('$instcode_reserved\\n$choose_again');
11734:         return false;
11735:     }
11736:     if (form.elements['addcategory_name'].value == 'communities') {
11737:         alert('$communities_reserved\\n$choose_again');
11738:         return false;
11739:     }
11740:     if (form.elements['addcategory_name'].value == 'placement') {
11741:         alert('$placement_reserved\\n$choose_again');
11742:         return false;
11743:     }
11744:     return true;
11745: }
11746: 
11747: // ]]>
11748: </script>
11749: 
11750: ENDSCRIPT
11751:     return $output;
11752: }
11753: 
11754: sub initialize_categories {
11755:     my ($itemcount) = @_;
11756:     my ($datatable,$css_class,$chgstr);
11757:     my %default_names = &Apache::lonlocal::texthash (
11758:                       instcode    => 'Official courses (with institutional codes)',
11759:                       communities => 'Communities',
11760:                       placement   => 'Placement Tests',
11761:                         );
11762:     my %selnum = (
11763:                    instcode    => '0',
11764:                    communities => '1',
11765:                    placement   => '2',
11766:                  );
11767:     my %selected;
11768:     foreach my $default ('instcode','communities','placement') {
11769:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11770:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
11771:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
11772:         $selected{$selnum{$default}} = ' selected="selected"';
11773:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11774:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
11775:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
11776:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
11777:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
11778:                      .'<option value="3">4</option></select>&nbsp;'
11779:                      .$default_names{$default}
11780:                      .'</span></td><td><span class="LC_nobreak">'
11781:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
11782:                      .&mt('Display').'</label>&nbsp;<label>'
11783:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
11784:                  .'</label></span></td></tr>';
11785:         $itemcount ++;
11786:     }
11787:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11788:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
11789:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11790:                   .'<select name="addcategory_pos"'.$chgstr.'>'
11791:                   .'<option value="0">1</option>'
11792:                   .'<option value="1">2</option>'
11793:                   .'<option value="2">3</option>'
11794:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
11795:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
11796:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
11797:                   .'</td></tr>';
11798:     return $datatable;
11799: }
11800: 
11801: sub build_category_rows {
11802:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
11803:     my ($text,$name,$item,$chgstr);
11804:     if (ref($cats) eq 'ARRAY') {
11805:         my $maxdepth = scalar(@{$cats});
11806:         if (ref($cats->[$depth]) eq 'HASH') {
11807:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
11808:                 my $numchildren = @{$cats->[$depth]{$parent}};
11809:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11810:                 $text .= '<td><table class="LC_data_table">';
11811:                 my ($idxnum,$parent_name,$parent_item);
11812:                 my $higher = $depth - 1;
11813:                 if ($higher == 0) {
11814:                     $parent_name = &escape($parent).'::'.$higher;
11815:                 } else {
11816:                     if (ref($path) eq 'ARRAY') {
11817:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11818:                     }
11819:                 }
11820:                 $parent_item = 'addcategory_pos_'.$parent_name;
11821:                 for (my $j=0; $j<=$numchildren; $j++) {
11822:                     if ($j < $numchildren) {
11823:                         $name = $cats->[$depth]{$parent}[$j];
11824:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
11825:                         $idxnum = $idx->{$item};
11826:                     } else {
11827:                         $name = $parent_name;
11828:                         $item = $parent_item;
11829:                     }
11830:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
11831:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
11832:                     for (my $i=0; $i<=$numchildren; $i++) {
11833:                         my $vpos = $i+1;
11834:                         my $selstr;
11835:                         if ($j == $i) {
11836:                             $selstr = ' selected="selected" ';
11837:                         }
11838:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
11839:                     }
11840:                     $text .= '</select>&nbsp;';
11841:                     if ($j < $numchildren) {
11842:                         my $deeper = $depth+1;
11843:                         $text .= $name.'&nbsp;'
11844:                                  .'<label><input type="checkbox" name="deletecategory" value="'
11845:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
11846:                         if(ref($path) eq 'ARRAY') {
11847:                             push(@{$path},$name);
11848:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11849:                             pop(@{$path});
11850:                         }
11851:                     } else {
11852:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11853:                         if ($j == $numchildren) {
11854:                             $text .= $name;
11855:                         } else {
11856:                             $text .= $item;
11857:                         }
11858:                         $text .= '" value="" />';
11859:                     }
11860:                     $text .= '</td></tr>';
11861:                 }
11862:                 $text .= '</table></td>';
11863:             } else {
11864:                 my $higher = $depth-1;
11865:                 if ($higher == 0) {
11866:                     $name = &escape($parent).'::'.$higher;
11867:                 } else {
11868:                     if (ref($path) eq 'ARRAY') {
11869:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11870:                     }
11871:                 }
11872:                 my $colspan;
11873:                 if ($parent ne 'instcode') {
11874:                     $colspan = $maxdepth - $depth - 1;
11875:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11876:                 }
11877:             }
11878:         }
11879:     }
11880:     return $text;
11881: }
11882: 
11883: sub modifiable_userdata_row {
11884:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11885:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11886:     my ($role,$rolename,$statustype);
11887:     $role = $item;
11888:     if ($context eq 'cancreate') {
11889:         if ($item =~ /^(emailusername)_(.+)$/) {
11890:             $role = $1;
11891:             $statustype = $2;
11892:             if (ref($usertypes) eq 'HASH') {
11893:                 if ($usertypes->{$statustype}) {
11894:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11895:                 } else {
11896:                     $rolename = &mt('Data provided by user');
11897:                 }
11898:             }
11899:         }
11900:     } elsif ($context eq 'selfcreate') {
11901:         if (ref($usertypes) eq 'HASH') {
11902:             $rolename = $usertypes->{$role};
11903:         } else {
11904:             $rolename = $role;
11905:         }
11906:     } elsif ($context eq 'lti') {
11907:         $rolename = &mt('Institutional data used (if available)');
11908:     } elsif ($context eq 'privacy') {
11909:         $rolename = $itemdesc;
11910:     } else {
11911:         if ($role eq 'cr') {
11912:             $rolename = &mt('Custom role');
11913:         } else {
11914:             $rolename = &Apache::lonnet::plaintext($role);
11915:         }
11916:     }
11917:     my (@fields,%fieldtitles);
11918:     if (ref($fieldsref) eq 'ARRAY') {
11919:         @fields = @{$fieldsref};
11920:     } else {
11921:         @fields = ('lastname','firstname','middlename','generation',
11922:                    'permanentemail','id');
11923:     }
11924:     if ((ref($titlesref) eq 'HASH')) {
11925:         %fieldtitles = %{$titlesref};
11926:     } else {
11927:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11928:     }
11929:     my $output;
11930:     my $css_class;
11931:     if ($rowcount%2) {
11932:         $css_class = 'LC_odd_row';
11933:     }
11934:     if ($customcss) {
11935:         $css_class .= " $customcss";
11936:     }
11937:     $css_class =~ s/^\s+//;
11938:     if ($css_class) {
11939:         $css_class = ' class="'.$css_class.'"';
11940:     }
11941:     if ($rowstyle) {
11942:         $css_class .= ' style="'.$rowstyle.'"';
11943:     }
11944:     if ($rowid) {
11945:         $rowid = ' id="'.$rowid.'"';
11946:     }
11947:     $output = '<tr '.$css_class.$rowid.'>'.
11948:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
11949:               '<td class="LC_left_item" colspan="2"><table>';
11950:     my $rem;
11951:     my %checks;
11952:     my %current;
11953:     if (ref($settings) eq 'HASH') {
11954:         my $hashref;
11955:         if ($context eq 'lti') {
11956:             if (ref($settings) eq 'HASH') {
11957:                 $hashref = $settings->{'instdata'};
11958:             }
11959:         } elsif ($context eq 'privacy') {
11960:             my ($key,$inner) = split(/_/,$role);
11961:             if (ref($settings) eq 'HASH') {
11962:                 if (ref($settings->{$key}) eq 'HASH') {
11963:                     $hashref = $settings->{$key}->{$inner};
11964:                 }
11965:             }
11966:         } elsif (ref($settings->{$context}) eq 'HASH') {
11967:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
11968:                 $hashref = $settings->{'lti_instdata'};
11969:             }
11970:             if ($role eq 'emailusername') {
11971:                 if ($statustype) {
11972:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
11973:                         $hashref = $settings->{$context}->{$role}->{$statustype};
11974:                     }
11975:                 }
11976:             }
11977:         }
11978:         if (ref($hashref) eq 'HASH') { 
11979:             foreach my $field (@fields) {
11980:                 if ($hashref->{$field}) {
11981:                     if ($role eq 'emailusername') {
11982:                         $checks{$field} = $hashref->{$field};
11983:                     } else {
11984:                         $checks{$field} = ' checked="checked" ';
11985:                     }
11986:                 }
11987:             }
11988:         }
11989:     }
11990:  
11991:     my $total = scalar(@fields);
11992:     for (my $i=0; $i<$total; $i++) {
11993:         $rem = $i%($numinrow);
11994:         if ($rem == 0) {
11995:             if ($i > 0) {
11996:                 $output .= '</tr>';
11997:             }
11998:             $output .= '<tr>';
11999:         }
12000:         my $check = ' ';
12001:         unless ($role eq 'emailusername') {
12002:             if (exists($checks{$fields[$i]})) {
12003:                 $check = $checks{$fields[$i]};
12004:             } elsif ($context eq 'privacy') {
12005:                 if ($role =~ /^priv_(domain|course)$/) {
12006:                     if (ref($settings) ne 'HASH') {
12007:                         $check = ' checked="checked" ';
12008:                     }
12009:                 } elsif ($role =~ /^priv_(author|community)$/) {
12010:                     if (ref($settings) ne 'HASH') {
12011:                         unless ($fields[$i] eq 'id') {
12012:                             $check = ' checked="checked" ';
12013:                         }
12014:                     }
12015:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
12016:                     if (ref($settings) ne 'HASH') {
12017:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
12018:                             $check = ' checked="checked" ';
12019:                         }
12020:                     }
12021:                 }
12022:             } elsif ($context ne 'lti') {
12023:                 if ($role eq 'st') {
12024:                     if (ref($settings) ne 'HASH') {
12025:                         $check = ' checked="checked" '; 
12026:                     }
12027:                 }
12028:             }
12029:         }
12030:         $output .= '<td class="LC_left_item">'.
12031:                    '<span class="LC_nobreak">';
12032:         my $prefix = 'canmodify';
12033:         if ($role eq 'emailusername') {
12034:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
12035:                 $checks{$fields[$i]} = 'omit';
12036:             }
12037:             foreach my $option ('required','optional','omit') {
12038:                 my $checked='';
12039:                 if ($checks{$fields[$i]} eq $option) {
12040:                     $checked='checked="checked" ';
12041:                 }
12042:                 $output .= '<label>'.
12043:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
12044:                            &mt($option).'</label>'.('&nbsp;' x2);
12045:             }
12046:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
12047:         } else {
12048:             if ($context eq 'lti') {
12049:                 $prefix = 'lti';
12050:             } elsif ($context eq 'privacy') {
12051:                 $prefix = 'privacy';
12052:             }
12053:             $output .= '<label>'.
12054:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
12055:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
12056:                        '</label>';
12057:         }
12058:         $output .= '</span></td>';
12059:     }
12060:     $rem = $total%$numinrow;
12061:     my $colsleft;
12062:     if ($rem) {
12063:         $colsleft = $numinrow - $rem;
12064:     }
12065:     if ($colsleft > 1) {
12066:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
12067:                    '&nbsp;</td>';
12068:     } elsif ($colsleft == 1) {
12069:         $output .= '<td class="LC_left_item">&nbsp;</td>';
12070:     }
12071:     $output .= '</tr></table></td></tr>';
12072:     return $output;
12073: }
12074: 
12075: sub insttypes_row {
12076:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
12077:         $customcss,$rowstyle) = @_;
12078:     my %lt = &Apache::lonlocal::texthash (
12079:                       cansearch => 'Users allowed to search',
12080:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
12081:                       lockablenames => 'User preference to lock name',
12082:                       selfassign    => 'Self-reportable affiliations',
12083:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
12084:              );
12085:     my $showdom;
12086:     if ($context eq 'cansearch') {
12087:         $showdom = ' ('.$dom.')';
12088:     }
12089:     my $class = 'LC_left_item';
12090:     if ($context eq 'statustocreate') {
12091:         $class = 'LC_right_item';
12092:     }
12093:     my $css_class;
12094:     if ($$rowtotal%2) {
12095:         $css_class = 'LC_odd_row';
12096:     }
12097:     if ($customcss) {
12098:         $css_class .= ' '.$customcss;
12099:     }
12100:     $css_class =~ s/^\s+//;
12101:     if ($css_class) {
12102:         $css_class = ' class="'.$css_class.'"';
12103:     }
12104:     if ($rowstyle) {
12105:         $css_class .= ' style="'.$rowstyle.'"';
12106:     }
12107:     if ($onclick) {
12108:         $onclick = 'onclick="'.$onclick.'" ';
12109:     }
12110:     my $output = '<tr'.$css_class.'>'.
12111:                  '<td>'.$lt{$context}.$showdom.
12112:                  '</td><td class="'.$class.'" colspan="2"><table>';
12113:     my $rem;
12114:     if (ref($types) eq 'ARRAY') {
12115:         for (my $i=0; $i<@{$types}; $i++) {
12116:             if (defined($usertypes->{$types->[$i]})) {
12117:                 my $rem = $i%($numinrow);
12118:                 if ($rem == 0) {
12119:                     if ($i > 0) {
12120:                         $output .= '</tr>';
12121:                     }
12122:                     $output .= '<tr>';
12123:                 }
12124:                 my $check = ' ';
12125:                 if (ref($settings) eq 'HASH') {
12126:                     if (ref($settings->{$context}) eq 'ARRAY') {
12127:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
12128:                             $check = ' checked="checked" ';
12129:                         }
12130:                     } elsif (ref($settings->{$context}) eq 'HASH') {
12131:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
12132:                             $check = ' checked="checked" ';
12133:                         }
12134:                     } elsif ($context eq 'statustocreate') {
12135:                         $check = ' checked="checked" ';
12136:                     }
12137:                 }
12138:                 $output .= '<td class="LC_left_item">'.
12139:                            '<span class="LC_nobreak"><label>'.
12140:                            '<input type="checkbox" name="'.$context.'" '.
12141:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
12142:                            $usertypes->{$types->[$i]}.'</label></span></td>';
12143:             }
12144:         }
12145:         $rem = @{$types}%($numinrow);
12146:     }
12147:     my $colsleft = $numinrow - $rem;
12148:     if ($context eq 'overrides') {
12149:         if ($colsleft > 1) {
12150:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12151:         } else {
12152:             $output .= '<td class="LC_left_item">';
12153:         }
12154:         $output .= '&nbsp;';  
12155:     } else {
12156:         if ($rem == 0) {
12157:             $output .= '<tr>';
12158:         }
12159:         if ($colsleft > 1) {
12160:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12161:         } else {
12162:             $output .= '<td class="LC_left_item">';
12163:         }
12164:         my $defcheck = ' ';
12165:         if (ref($settings) eq 'HASH') {  
12166:             if (ref($settings->{$context}) eq 'ARRAY') {
12167:                 if (grep(/^default$/,@{$settings->{$context}})) {
12168:                     $defcheck = ' checked="checked" ';
12169:                 }
12170:             } elsif ($context eq 'statustocreate') {
12171:                 $defcheck = ' checked="checked" ';
12172:             }
12173:         }
12174:         $output .= '<span class="LC_nobreak"><label>'.
12175:                    '<input type="checkbox" name="'.$context.'" '.
12176:                    'value="default"'.$defcheck.$onclick.' />'.
12177:                    $othertitle.'</label></span>';
12178:     }
12179:     $output .= '</td></tr></table></td></tr>';
12180:     return $output;
12181: }
12182: 
12183: sub sorted_searchtitles {
12184:     my %searchtitles = &Apache::lonlocal::texthash(
12185:                          'uname' => 'username',
12186:                          'lastname' => 'last name',
12187:                          'lastfirst' => 'last name, first name',
12188:                      );
12189:     my @titleorder = ('uname','lastname','lastfirst');
12190:     return (\%searchtitles,\@titleorder);
12191: }
12192: 
12193: sub sorted_searchtypes {
12194:     my %srchtypes_desc = (
12195:                            exact    => 'is exact match',
12196:                            contains => 'contains ..',
12197:                            begins   => 'begins with ..',
12198:                          );
12199:     my @srchtypeorder = ('exact','begins','contains');
12200:     return (\%srchtypes_desc,\@srchtypeorder);
12201: }
12202: 
12203: sub usertype_update_row {
12204:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
12205:     my $datatable;
12206:     my $numinrow = 4;
12207:     foreach my $type (@{$types}) {
12208:         if (defined($usertypes->{$type})) {
12209:             $$rownums ++;
12210:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
12211:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
12212:                           '</td><td class="LC_left_item"><table>';
12213:             for (my $i=0; $i<@{$fields}; $i++) {
12214:                 my $rem = $i%($numinrow);
12215:                 if ($rem == 0) {
12216:                     if ($i > 0) {
12217:                         $datatable .= '</tr>';
12218:                     }
12219:                     $datatable .= '<tr>';
12220:                 }
12221:                 my $check = ' ';
12222:                 if (ref($settings) eq 'HASH') {
12223:                     if (ref($settings->{'fields'}) eq 'HASH') {
12224:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
12225:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
12226:                                 $check = ' checked="checked" ';
12227:                             }
12228:                         }
12229:                     }
12230:                 }
12231: 
12232:                 if ($i == @{$fields}-1) {
12233:                     my $colsleft = $numinrow - $rem;
12234:                     if ($colsleft > 1) {
12235:                         $datatable .= '<td colspan="'.$colsleft.'">';
12236:                     } else {
12237:                         $datatable .= '<td>';
12238:                     }
12239:                 } else {
12240:                     $datatable .= '<td>';
12241:                 }
12242:                 $datatable .= '<span class="LC_nobreak"><label>'.
12243:                               '<input type="checkbox" name="updateable_'.$type.
12244:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
12245:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
12246:             }
12247:             $datatable .= '</tr></table></td></tr>';
12248:         }
12249:     }
12250:     return $datatable;
12251: }
12252: 
12253: sub modify_login {
12254:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12255:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
12256:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
12257:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
12258:     %title = ( coursecatalog => 'Display course catalog',
12259:                adminmail => 'Display administrator E-mail address',
12260:                helpdesk  => 'Display "Contact Helpdesk" link',
12261:                newuser => 'Link for visitors to create a user account',
12262:                loginheader => 'Log-in box header',
12263:                saml => 'Dual SSO and non-SSO login');
12264:     @offon = ('off','on');
12265:     if (ref($domconfig{login}) eq 'HASH') {
12266:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
12267:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
12268:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
12269:             }
12270:         }
12271:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
12272:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
12273:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
12274:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
12275:                     $saml{$lonhost} = 1;
12276:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
12277:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
12278:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
12279:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
12280:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
12281:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
12282:                 }
12283:             }
12284:         }
12285:     }
12286:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
12287:                                            \%domconfig,\%loginhash);
12288:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12289:     foreach my $item (@toggles) {
12290:         $loginhash{login}{$item} = $env{'form.'.$item};
12291:     }
12292:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
12293:     if (ref($colchanges{'login'}) eq 'HASH') {  
12294:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
12295:                                          \%loginhash);
12296:     }
12297: 
12298:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12299:     my %domservers = &Apache::lonnet::get_servers($dom);
12300:     my @loginvia_attribs = ('serverpath','custompath','exempt');
12301:     if (keys(%servers) > 1) {
12302:         foreach my $lonhost (keys(%servers)) {
12303:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
12304:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
12305:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
12306:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
12307:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
12308:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12309:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12310:                         $changes{'loginvia'}{$lonhost} = 1;
12311:                     } else {
12312:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
12313:                         $changes{'loginvia'}{$lonhost} = 1;
12314:                     }
12315:                 } else {
12316:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12317:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12318:                         $changes{'loginvia'}{$lonhost} = 1;
12319:                     }
12320:                 }
12321:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
12322:                     foreach my $item (@loginvia_attribs) {
12323:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
12324:                     }
12325:                 } else {
12326:                     foreach my $item (@loginvia_attribs) {
12327:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12328:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12329:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
12330:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12331:                                 $new = '/';
12332:                             }
12333:                         }
12334:                         if (($item eq 'custompath') && 
12335:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12336:                             $new = '';
12337:                         }
12338:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
12339:                             $changes{'loginvia'}{$lonhost} = 1;
12340:                         }
12341:                         if ($item eq 'exempt') {
12342:                             $new = &check_exempt_addresses($new);
12343:                         }
12344:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12345:                     }
12346:                 }
12347:             } else {
12348:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12349:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12350:                     $changes{'loginvia'}{$lonhost} = 1;
12351:                     foreach my $item (@loginvia_attribs) {
12352:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12353:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12354:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12355:                                 $new = '/';
12356:                             }
12357:                         }
12358:                         if (($item eq 'custompath') && 
12359:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12360:                             $new = '';
12361:                         }
12362:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12363:                     }
12364:                 }
12365:             }
12366:         }
12367:     }
12368: 
12369:     my $servadm = $r->dir_config('lonAdmEMail');
12370:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
12371:     if (ref($domconfig{'login'}) eq 'HASH') {
12372:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
12373:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
12374:                 if ($lang eq 'nolang') {
12375:                     push(@currlangs,$lang);
12376:                 } elsif (defined($langchoices{$lang})) {
12377:                     push(@currlangs,$lang);
12378:                 } else {
12379:                     next;
12380:                 }
12381:             }
12382:         }
12383:     }
12384:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
12385:     if (@currlangs > 0) {
12386:         foreach my $lang (@currlangs) {
12387:             if (grep(/^\Q$lang\E$/,@delurls)) {
12388:                 $changes{'helpurl'}{$lang} = 1;
12389:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
12390:                 $changes{'helpurl'}{$lang} = 1;
12391:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
12392:                 push(@newlangs,$lang);
12393:             } else {
12394:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12395:             }
12396:         }
12397:     }
12398:     unless (grep(/^nolang$/,@currlangs)) {
12399:         if ($env{'form.loginhelpurl_nolang.filename'}) {
12400:             $changes{'helpurl'}{'nolang'} = 1;
12401:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
12402:             push(@newlangs,'nolang');
12403:         }
12404:     }
12405:     if ($env{'form.loginhelpurl_add_lang'}) {
12406:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
12407:             ($env{'form.loginhelpurl_add_file.filename'})) {
12408:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
12409:             $addedfile = $env{'form.loginhelpurl_add_lang'};
12410:         }
12411:     }
12412:     if ((@newlangs > 0) || ($addedfile)) {
12413:         my $error;
12414:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12415:         if ($configuserok eq 'ok') {
12416:             if ($switchserver) {
12417:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
12418:             } elsif ($author_ok eq 'ok') {
12419:                 my @allnew = @newlangs;
12420:                 if ($addedfile ne '') {
12421:                     push(@allnew,$addedfile);
12422:                 }
12423:                 foreach my $lang (@allnew) {
12424:                     my $formelem = 'loginhelpurl_'.$lang;
12425:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
12426:                         $formelem = 'loginhelpurl_add_file';
12427:                     }
12428:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12429:                                                                "help/$lang",'','',$newfile{$lang});
12430:                     if ($result eq 'ok') {
12431:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
12432:                         $changes{'helpurl'}{$lang} = 1;
12433:                     } else {
12434:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
12435:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12436:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
12437:                             (!grep(/^\Q$lang\E$/,@delurls))) {
12438:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12439:                         }
12440:                     }
12441:                 }
12442:             } else {
12443:                 $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);
12444:             }
12445:         } else {
12446:             $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);
12447:         }
12448:         if ($error) {
12449:             &Apache::lonnet::logthis($error);
12450:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12451:         }
12452:     }
12453: 
12454:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
12455:     if (ref($domconfig{'login'}) eq 'HASH') {
12456:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
12457:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
12458:                 if ($domservers{$lonhost}) {
12459:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12460:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
12461:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
12462:                     }
12463:                 }
12464:             }
12465:         }
12466:     }
12467:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
12468:     foreach my $lonhost (sort(keys(%domservers))) {
12469:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12470:             $changes{'headtag'}{$lonhost} = 1;
12471:         } else {
12472:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
12473:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
12474:             }
12475:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
12476:                 push(@newhosts,$lonhost);
12477:             } elsif ($currheadtagurls{$lonhost}) {
12478:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
12479:                 if ($currexempt{$lonhost}) {
12480:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
12481:                         $changes{'headtag'}{$lonhost} = 1;
12482:                     }
12483:                 } elsif ($possexempt{$lonhost}) {
12484:                     $changes{'headtag'}{$lonhost} = 1;
12485:                 }
12486:                 if ($possexempt{$lonhost}) {
12487:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12488:                 }
12489:             }
12490:         }
12491:     }
12492:     if (@newhosts) {
12493:         my $error;
12494:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12495:         if ($configuserok eq 'ok') {
12496:             if ($switchserver) {
12497:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
12498:             } elsif ($author_ok eq 'ok') {
12499:                 foreach my $lonhost (@newhosts) {
12500:                     my $formelem = 'loginheadtag_'.$lonhost;
12501:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12502:                                                                           "login/headtag/$lonhost",'','',
12503:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
12504:                     if ($result eq 'ok') {
12505:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
12506:                         $changes{'headtag'}{$lonhost} = 1;
12507:                         if ($possexempt{$lonhost}) {
12508:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12509:                         }
12510:                     } else {
12511:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
12512:                                            $newheadtagurls{$lonhost},$result);
12513:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12514:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
12515:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
12516:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
12517:                         }
12518:                     }
12519:                 }
12520:             } else {
12521:                 $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);
12522:             }
12523:         } else {
12524:             $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);
12525:         }
12526:         if ($error) {
12527:             &Apache::lonnet::logthis($error);
12528:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12529:         }
12530:     }
12531:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
12532:     my @newsamlimgs;
12533:     foreach my $lonhost (keys(%domservers)) {
12534:         if ($env{'form.saml_'.$lonhost}) {
12535:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
12536:                 push(@newsamlimgs,$lonhost);
12537:             }
12538:             foreach my $item ('text','alt','url','title','notsso') {
12539:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
12540:             }
12541:             if ($saml{$lonhost}) {
12542:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
12543: #FIXME Need to obsolete published image
12544:                     delete($currsaml{$lonhost}{'img'});
12545:                     $changes{'saml'}{$lonhost} = 1;
12546:                 }
12547:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
12548:                     $changes{'saml'}{$lonhost} = 1;
12549:                 }
12550:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
12551:                     $changes{'saml'}{$lonhost} = 1;
12552:                 }
12553:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
12554:                     $changes{'saml'}{$lonhost} = 1;
12555:                 }
12556:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
12557:                     $changes{'saml'}{$lonhost} = 1;
12558:                 }
12559:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
12560:                     $changes{'saml'}{$lonhost} = 1;
12561:                 }
12562:             } else {
12563:                 $changes{'saml'}{$lonhost} = 1;
12564:             }
12565:             foreach my $item ('text','alt','url','title','notsso') {
12566:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
12567:             }
12568:         } else {
12569:             if ($saml{$lonhost}) {  
12570:                 $changes{'saml'}{$lonhost} = 1;
12571:                 delete($currsaml{$lonhost});
12572:             }
12573:         }
12574:     }
12575:     foreach my $posshost (keys(%currsaml)) {
12576:         unless (exists($domservers{$posshost})) { 
12577:             delete($currsaml{$posshost}); 
12578:         }
12579:     }
12580:     %{$loginhash{'login'}{'saml'}} = %currsaml;
12581:     if (@newsamlimgs) {
12582:         my $error;
12583:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12584:         if ($configuserok eq 'ok') {
12585:             if ($switchserver) {
12586:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
12587:             } elsif ($author_ok eq 'ok') {
12588:                 foreach my $lonhost (@newsamlimgs) {
12589:                     my $formelem = 'saml_img_'.$lonhost;
12590:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12591:                                                         "login/saml/$lonhost",'','',
12592:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
12593:                     if ($result eq 'ok') {
12594:                         $currsaml{$lonhost}{'img'} = $imgurl;
12595:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
12596:                         $changes{'saml'}{$lonhost} = 1;
12597:                     } else {
12598:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
12599:                                            $lonhost,$result);
12600:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12601:                     }
12602:                 }
12603:             } else {
12604:                 $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);
12605:             }
12606:         } else {
12607:             $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);
12608:         }
12609:         if ($error) {
12610:             &Apache::lonnet::logthis($error);
12611:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12612:         }
12613:     }
12614:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
12615: 
12616:     my $defaulthelpfile = '/adm/loginproblems.html';
12617:     my $defaulttext = &mt('Default in use');
12618: 
12619:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
12620:                                              $dom);
12621:     if ($putresult eq 'ok') {
12622:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12623:         my %defaultchecked = (
12624:                     'coursecatalog' => 'on',
12625:                     'helpdesk'      => 'on',
12626:                     'adminmail'     => 'off',
12627:                     'newuser'       => 'off',
12628:         );
12629:         if (ref($domconfig{'login'}) eq 'HASH') {
12630:             foreach my $item (@toggles) {
12631:                 if ($defaultchecked{$item} eq 'on') { 
12632:                     if (($domconfig{'login'}{$item} eq '0') &&
12633:                         ($env{'form.'.$item} eq '1')) {
12634:                         $changes{$item} = 1;
12635:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12636:                               $domconfig{'login'}{$item} eq '1') &&
12637:                              ($env{'form.'.$item} eq '0')) {
12638:                         $changes{$item} = 1;
12639:                     }
12640:                 } elsif ($defaultchecked{$item} eq 'off') {
12641:                     if (($domconfig{'login'}{$item} eq '1') &&
12642:                         ($env{'form.'.$item} eq '0')) {
12643:                         $changes{$item} = 1;
12644:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12645:                               $domconfig{'login'}{$item} eq '0') &&
12646:                              ($env{'form.'.$item} eq '1')) {
12647:                         $changes{$item} = 1;
12648:                     }
12649:                 }
12650:             }
12651:         }
12652:         if (keys(%changes) > 0 || $colchgtext) {
12653:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12654:             if (exists($changes{'saml'})) {
12655:                 my $hostid_in_use;
12656:                 my @hosts = &Apache::lonnet::current_machine_ids();
12657:                 if (@hosts > 1) {
12658:                     foreach my $hostid (@hosts) {
12659:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
12660:                             $hostid_in_use = $hostid;
12661:                             last;
12662:                         }
12663:                     }
12664:                 } else {
12665:                     $hostid_in_use = $r->dir_config('lonHostID');
12666:                 }
12667:                 if (($hostid_in_use) &&
12668:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
12669:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
12670:                 }
12671:                 if (ref($lastactref) eq 'HASH') {
12672:                     if (ref($changes{'saml'}) eq 'HASH') {
12673:                         my %updates;
12674:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
12675:                         $lastactref->{'samllanding'} = \%updates;
12676:                     }
12677:                 }
12678:             }
12679:             if (ref($lastactref) eq 'HASH') {
12680:                 $lastactref->{'domainconfig'} = 1;
12681:             }
12682:             $resulttext = &mt('Changes made:').'<ul>';
12683:             foreach my $item (sort(keys(%changes))) {
12684:                 if ($item eq 'loginvia') {
12685:                     if (ref($changes{$item}) eq 'HASH') {
12686:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
12687:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12688:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
12689:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
12690:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
12691:                                     $protocol = 'http' if ($protocol ne 'https');
12692:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
12693: 
12694:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
12695:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
12696:                                     } else {
12697:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
12698:                                     }
12699:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
12700:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
12701:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
12702:                                     }
12703:                                     $resulttext .= '</li>';
12704:                                 } else {
12705:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
12706:                                 }
12707:                             } else {
12708:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
12709:                             }
12710:                         }
12711:                         $resulttext .= '</ul></li>';
12712:                     }
12713:                 } elsif ($item eq 'helpurl') {
12714:                     if (ref($changes{$item}) eq 'HASH') {
12715:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
12716:                             if (grep(/^\Q$lang\E$/,@delurls)) {
12717:                                 my ($chg,$link);
12718:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
12719:                                 if ($lang eq 'nolang') {
12720:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
12721:                                 } else {
12722:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
12723:                                 }
12724:                                 $resulttext .= '<li>'.$chg.'</li>';
12725:                             } else {
12726:                                 my $chg;
12727:                                 if ($lang eq 'nolang') {
12728:                                     $chg = &mt('custom log-in help file for no preferred language');
12729:                                 } else {
12730:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
12731:                                 }
12732:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
12733:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
12734:                                                       '?inhibitmenu=yes',$chg,600,500).
12735:                                                '</li>';
12736:                             }
12737:                         }
12738:                     }
12739:                 } elsif ($item eq 'headtag') {
12740:                     if (ref($changes{$item}) eq 'HASH') {
12741:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12742:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12743:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
12744:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12745:                                 $resulttext .= '<li><a href="'.
12746:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
12747:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
12748:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
12749:                                 if ($possexempt{$lonhost}) {
12750:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
12751:                                 } else {
12752:                                     $resulttext .= &mt('included for any client IP');
12753:                                 }
12754:                                 $resulttext .= '</li>';
12755:                             }
12756:                         }
12757:                     }
12758:                 } elsif ($item eq 'saml') {
12759:                     if (ref($changes{$item}) eq 'HASH') {
12760:                         my %notlt = (
12761:                                        text   => 'Text for log-in by SSO',
12762:                                        img    => 'SSO button image',
12763:                                        alt    => 'Alt text for button image',
12764:                                        url    => 'SSO URL',
12765:                                        title  => 'Tooltip for SSO link',
12766:                                        notsso => 'Text for non-SSO log-in',
12767:                                     );
12768:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12769:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
12770:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
12771:                                                '<ul>';
12772:                                 foreach my $key ('text','img','alt','url','title','notsso') {
12773:                                     if ($currsaml{$lonhost}{$key} eq '') {
12774:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
12775:                                     } else {
12776:                                         my $value = "'$currsaml{$lonhost}{$key}'";
12777:                                         if ($key eq 'img') {
12778:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
12779:                                         }
12780:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
12781:                                                                   $value).'</li>';
12782:                                     }
12783:                                 }
12784:                                 $resulttext .= '</ul></li>';
12785:                             } else {
12786:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
12787:                             }
12788:                         }
12789:                     }
12790:                 } elsif ($item eq 'captcha') {
12791:                     if (ref($loginhash{'login'}) eq 'HASH') {
12792:                         my $chgtxt;
12793:                         if ($loginhash{'login'}{$item} eq 'notused') {
12794:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
12795:                         } else {
12796:                             my %captchas = &captcha_phrases();
12797:                             if ($captchas{$loginhash{'login'}{$item}}) {
12798:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
12799:                             } else {
12800:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
12801:                             }
12802:                         }
12803:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12804:                     }
12805:                 } elsif ($item eq 'recaptchakeys') {
12806:                     if (ref($loginhash{'login'}) eq 'HASH') {
12807:                         my ($privkey,$pubkey);
12808:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
12809:                             $pubkey = $loginhash{'login'}{$item}{'public'};
12810:                             $privkey = $loginhash{'login'}{$item}{'private'};
12811:                         }
12812:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
12813:                         if (!$pubkey) {
12814:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
12815:                         } else {
12816:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
12817:                         }
12818:                         if (!$privkey) {
12819:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
12820:                         } else {
12821:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
12822:                         }
12823:                         $chgtxt .= '</ul>';
12824:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12825:                     }
12826:                 } elsif ($item eq 'recaptchaversion') {
12827:                     if (ref($loginhash{'login'}) eq 'HASH') {
12828:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
12829:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
12830:                                            '</li>';
12831:                         }
12832:                     }
12833:                 } else {
12834:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
12835:                 }
12836:             }
12837:             $resulttext .= $colchgtext.'</ul>';
12838:         } else {
12839:             $resulttext = &mt('No changes made to log-in page settings');
12840:         }
12841:     } else {
12842:         $resulttext = '<span class="LC_error">'.
12843: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12844:     }
12845:     if ($errors) {
12846:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12847:                        $errors.'</ul>';
12848:     }
12849:     return $resulttext;
12850: }
12851: 
12852: sub check_exempt_addresses {
12853:     my ($iplist) = @_;
12854:     $iplist =~ s/^\s+//;
12855:     $iplist =~ s/\s+$//;
12856:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12857:     my (@okips,$new);
12858:     foreach my $ip (@poss_ips) {
12859:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12860:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12861:                 push(@okips,$ip);
12862:             }
12863:         }
12864:     }
12865:     if (@okips > 0) {
12866:         $new = join(',',@okips);
12867:     } else {
12868:         $new = '';
12869:     }
12870:     return $new;
12871: }
12872: 
12873: sub color_font_choices {
12874:     my %choices =
12875:         &Apache::lonlocal::texthash (
12876:             img => "Header",
12877:             bgs => "Background colors",
12878:             links => "Link colors",
12879:             images => "Images",
12880:             font => "Font color",
12881:             fontmenu => "Font menu",
12882:             pgbg => "Page",
12883:             tabbg => "Header",
12884:             sidebg => "Border",
12885:             link => "Link",
12886:             alink => "Active link",
12887:             vlink => "Visited link",
12888:         );
12889:     return %choices;
12890: }
12891: 
12892: sub modify_ipaccess {
12893:     my ($dom,$lastactref,%domconfig) = @_;
12894:     my (@allpos,%changes,%confhash,$errors,$resulttext);
12895:     my (@items,%deletions,%itemids,@warnings);
12896:     my ($typeorder,$types) = &commblocktype_text();
12897:     if ($env{'form.ipaccess_add'}) {
12898:         my $name = $env{'form.ipaccess_name_add'};
12899:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
12900:         if ($newid) {
12901:             $itemids{'add'} = $newid;
12902:             push(@items,'add');
12903:             $changes{$newid} = 1;
12904:         } else {
12905:             $error = &mt('Failed to acquire unique ID for new IP access control item');
12906:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12907:         }
12908:     }
12909:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
12910:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
12911:         if (@todelete) {
12912:             map { $deletions{$_} = 1; } @todelete;
12913:         }
12914:         my $maxnum = $env{'form.ipaccess_maxnum'};
12915:         for (my $i=0; $i<$maxnum; $i++) {
12916:             my $itemid = $env{'form.ipaccess_id_'.$i};
12917:             $itemid =~ s/\D+//g;
12918:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12919:                 if ($deletions{$itemid}) {
12920:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
12921:                 } else {
12922:                     push(@items,$i);
12923:                     $itemids{$i} = $itemid;
12924:                 }
12925:             }
12926:         }
12927:     }
12928:     foreach my $idx (@items) {
12929:         my $itemid = $itemids{$idx};
12930:         next unless ($itemid);
12931:         my %current;
12932:         unless ($idx eq 'add') {
12933:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12934:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
12935:             }
12936:         }
12937:         my $position = $env{'form.ipaccess_pos_'.$itemid};
12938:         $position =~ s/\D+//g;
12939:         if ($position ne '') {
12940:             $allpos[$position] = $itemid;
12941:         }
12942:         my $name = $env{'form.ipaccess_name_'.$idx};
12943:         $name =~ s/^\s+|\s+$//g;
12944:         $confhash{$itemid}{'name'} = $name;
12945:         my $possrange = $env{'form.ipaccess_range_'.$idx};
12946:         $possrange =~ s/^\s+|\s+$//g;
12947:         unless ($possrange eq '') {
12948:             $possrange =~ s/[\r\n]+/\s/g;
12949:             $possrange =~ s/\s*-\s*/-/g;
12950:             $possrange =~ s/\s+/,/g;
12951:             $possrange =~ s/,+/,/g;
12952:             if ($possrange ne '') {
12953:                 my (@ok,$count);
12954:                 $count = 0; 
12955:                 foreach my $poss (split(/\,/,$possrange)) {
12956:                     $count ++;
12957:                     $poss = &validate_ip_pattern($poss);
12958:                     if ($poss ne '') {
12959:                         push(@ok,$poss);
12960:                     }
12961:                 }
12962:                 my $diff = $count - scalar(@ok);
12963:                 if ($diff) {
12964:                     $errors .= '<li><span class="LC_error">'.
12965:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
12966:                                    $diff,$name).
12967:                                '</span></li>';
12968:                 }
12969:                 if (@ok) {
12970:                     my @cidr_list;
12971:                     foreach my $item (@ok) {
12972:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
12973:                     }
12974:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
12975:                 }
12976:             }
12977:         }
12978:         foreach my $field ('name','ip') {
12979:             unless (($idx eq 'add') || ($changes{$itemid})) {
12980:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
12981:                     $changes{$itemid} = 1;
12982:                     last;
12983:                 }
12984:             }
12985:         }
12986:         $confhash{$itemid}{'commblocks'} = {};
12987:          
12988:         my %commblocks;
12989:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);  
12990:         foreach my $type (@{$typeorder}) {
12991:             if ($commblocks{$type}) {
12992:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
12993:             }
12994:             unless (($idx eq 'add') || ($changes{$itemid})) {
12995:                 if (ref($current{'commblocks'}) eq 'HASH') {
12996:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
12997:                         $changes{$itemid} = 1;
12998:                     }
12999:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
13000:                     $changes{$itemid} = 1;
13001:                 }
13002:             }
13003:         }
13004:         $confhash{$itemid}{'courses'} = {};
13005:         my %crsdeletions;
13006:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
13007:         if (@delcrs) {
13008:             map { $crsdeletions{$_} = 1; } @delcrs;
13009:         }
13010:         if (ref($current{'courses'}) eq 'HASH') {
13011:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
13012:                 if ($crsdeletions{$cid}) {
13013:                     $changes{$itemid} = 1;
13014:                 } else {
13015:                     $confhash{$itemid}{'courses'}{$cid} = 1;
13016:                 }
13017:             }
13018:         }
13019:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
13020:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
13021:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) && 
13022:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
13023:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
13024:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
13025:                 $errors .= '<li><span class="LC_error">'.
13026:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
13027:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
13028:                            '</span></li>';
13029:             } else {
13030:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
13031:                 $changes{$itemid} = 1;
13032:             }
13033:         }
13034:     }
13035:     if (@allpos > 0) {
13036:         my $idx = 0;
13037:         foreach my $itemid (@allpos) {
13038:             if ($itemid ne '') {
13039:                 $confhash{$itemid}{'order'} = $idx;
13040:                 unless ($changes{$itemid}) {
13041:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
13042:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
13043:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
13044:                                 $changes{$itemid} = 1;
13045:                             }
13046:                         }
13047:                     }
13048:                 }
13049:                 $idx ++;
13050:             }
13051:         }
13052:     }
13053:     if (keys(%changes)) {
13054:         my %defaultshash = (
13055:                               ipaccess => \%confhash,
13056:                            );
13057:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
13058:                                                  $dom);
13059:         if ($putresult eq 'ok') {
13060:             my $cachetime = 1800;
13061:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
13062:             if (ref($lastactref) eq 'HASH') {
13063:                 $lastactref->{'ipaccess'} = 1;
13064:             }
13065:             $resulttext = &mt('Changes made:').'<ul>';
13066:             my %bynum;
13067:             foreach my $itemid (sort(keys(%changes))) {
13068:                 if (ref($confhash{$itemid}) eq 'HASH') {
13069:                     my $position = $confhash{$itemid}{'order'};
13070:                     if ($position =~ /^\d+$/) {
13071:                         $bynum{$position} = $itemid;
13072:                     }
13073:                 }
13074:             }
13075:             if (keys(%deletions)) {
13076:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
13077:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13078:                 }
13079:             }
13080:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13081:                 my $itemid = $bynum{$pos};
13082:                 if (ref($confhash{$itemid}) eq 'HASH') {
13083:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
13084:                     my $position = $pos + 1;
13085:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13086:                     if ($confhash{$itemid}{'ip'} eq '') {
13087:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
13088:                     } else {
13089:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
13090:                     }
13091:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
13092:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
13093:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
13094:                                        '</li>';
13095:                     } else {
13096:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
13097:                     }
13098:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
13099:                         my @courses;
13100:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
13101:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1}); 
13102:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
13103:                         }
13104:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
13105:                                              join('</li><li>',@courses).'</li></ul>';
13106:                     } else {
13107:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
13108:                     }
13109:                     $resulttext .= '</ul></li>';
13110:                 }
13111:             }
13112:             $resulttext .= '</ul>';
13113:         } else {
13114:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13115:         }
13116:     } else {
13117:         $resulttext = &mt('No changes made');
13118:     }
13119:     if ($errors) {
13120:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13121:                        $errors.'</ul></p>';
13122:     }
13123:     return $resulttext;
13124: }
13125: 
13126: sub get_ipaccess_id {
13127:     my ($domain,$location) = @_;
13128:     # get lock on ipaccess db
13129:     my $lockhash = {
13130:                       lock => $env{'user.name'}.
13131:                               ':'.$env{'user.domain'},
13132:                    };
13133:     my $tries = 0;
13134:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13135:     my ($id,$error);
13136: 
13137:     while (($gotlock ne 'ok') && ($tries<10)) {
13138:         $tries ++;
13139:         sleep (0.1);
13140:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13141:     }
13142:     if ($gotlock eq 'ok') {
13143:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
13144:         if ($currids{'lock'}) {
13145:             delete($currids{'lock'});
13146:             if (keys(%currids)) {
13147:                 my @curr = sort { $a <=> $b } keys(%currids);
13148:                 if ($curr[-1] =~ /^\d+$/) {
13149:                     $id = 1 + $curr[-1];
13150:                 }
13151:             } else {
13152:                 $id = 1;
13153:             }
13154:             if ($id) {
13155:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
13156:                     $error = 'nostore';
13157:                 }
13158:             } else {
13159:                 $error = 'nonumber';
13160:             }
13161:         }
13162:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
13163:     } else {
13164:         $error = 'nolock';
13165:     }
13166:     return ($id,$error);
13167: }
13168: 
13169: sub modify_rolecolors {
13170:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
13171:     my ($resulttext,%rolehash);
13172:     $rolehash{'rolecolors'} = {};
13173:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
13174:         if ($domconfig{'rolecolors'} eq '') {
13175:             $domconfig{'rolecolors'} = {};
13176:         }
13177:     }
13178:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
13179:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
13180:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
13181:                                              $dom);
13182:     if ($putresult eq 'ok') {
13183:         if (keys(%changes) > 0) {
13184:             &Apache::loncommon::devalidate_domconfig_cache($dom);
13185:             if (ref($lastactref) eq 'HASH') {
13186:                 $lastactref->{'domainconfig'} = 1;
13187:             }
13188:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
13189:                                              $rolehash{'rolecolors'});
13190:         } else {
13191:             $resulttext = &mt('No changes made to default color schemes');
13192:         }
13193:     } else {
13194:         $resulttext = '<span class="LC_error">'.
13195: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13196:     }
13197:     if ($errors) {
13198:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13199:                        $errors.'</ul>';
13200:     }
13201:     return $resulttext;
13202: }
13203: 
13204: sub modify_colors {
13205:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
13206:     my (%changes,%choices);
13207:     my @bgs;
13208:     my @links = ('link','alink','vlink');
13209:     my @logintext;
13210:     my @images;
13211:     my $servadm = $r->dir_config('lonAdmEMail');
13212:     my $errors;
13213:     my %defaults;
13214:     foreach my $role (@{$roles}) {
13215:         if ($role eq 'login') {
13216:             %choices = &login_choices();
13217:             @logintext = ('textcol','bgcol');
13218:         } else {
13219:             %choices = &color_font_choices();
13220:         }
13221:         if ($role eq 'login') {
13222:             @images = ('img','logo','domlogo','login');
13223:             @bgs = ('pgbg','mainbg','sidebg');
13224:         } else {
13225:             @images = ('img');
13226:             @bgs = ('pgbg','tabbg','sidebg');
13227:         }
13228:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
13229:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
13230:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
13231:         }
13232:         if ($role eq 'login') {
13233:             foreach my $item (@logintext) {
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{'logintext'}{$item})) {
13239:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13240:                 }
13241:             }
13242:         } else {
13243:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
13244:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
13245:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
13246:             }
13247:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
13248:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
13249:             }
13250:         }
13251:         foreach my $item (@bgs) {
13252:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13253:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13254:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13255:             }
13256:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
13257:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13258:             }
13259:         }
13260:         foreach my $item (@links) {
13261:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13262:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13263:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13264:             }
13265:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
13266:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13267:             }
13268:         }
13269:         my ($configuserok,$author_ok,$switchserver) = 
13270:             &config_check($dom,$confname,$servadm);
13271:         my ($width,$height) = &thumb_dimensions();
13272:         if (ref($domconfig->{$role}) ne 'HASH') {
13273:             $domconfig->{$role} = {};
13274:         }
13275:         foreach my $img (@images) {
13276:             if ($role eq 'login') {
13277:                 if (($img eq 'img') || ($img eq 'logo')) {  
13278:                     if (defined($env{'form.login_showlogo_'.$img})) {
13279:                         $confhash->{$role}{'showlogo'}{$img} = 1;
13280:                     } else { 
13281:                         $confhash->{$role}{'showlogo'}{$img} = 0;
13282:                     }
13283:                 }
13284:                 if ($env{'form.login_alt_'.$img} ne '') {
13285:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
13286:                 }
13287:             }
13288: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
13289: 		 && !defined($domconfig->{$role}{$img})
13290: 		 && !$env{'form.'.$role.'_del_'.$img}
13291: 		 && $env{'form.'.$role.'_import_'.$img}) {
13292: 		# import the old configured image from the .tab setting
13293: 		# if they haven't provided a new one 
13294: 		$domconfig->{$role}{$img} = 
13295: 		    $env{'form.'.$role.'_import_'.$img};
13296: 	    }
13297:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
13298:                 my $error;
13299:                 if ($configuserok eq 'ok') {
13300:                     if ($switchserver) {
13301:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
13302:                     } else {
13303:                         if ($author_ok eq 'ok') {
13304:                             my ($result,$logourl) = 
13305:                                 &publishlogo($r,'upload',$role.'_'.$img,
13306:                                            $dom,$confname,$img,$width,$height);
13307:                             if ($result eq 'ok') {
13308:                                 $confhash->{$role}{$img} = $logourl;
13309:                                 $changes{$role}{'images'}{$img} = 1;
13310:                             } else {
13311:                                 $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);
13312:                             }
13313:                         } else {
13314:                             $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);
13315:                         }
13316:                     }
13317:                 } else {
13318:                     $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);
13319:                 }
13320:                 if ($error) {
13321:                     &Apache::lonnet::logthis($error);
13322:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13323:                 }
13324:             } elsif ($domconfig->{$role}{$img} ne '') {
13325:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
13326:                     my $error;
13327:                     if ($configuserok eq 'ok') {
13328: # is confname an author?
13329:                         if ($switchserver eq '') {
13330:                             if ($author_ok eq 'ok') {
13331:                                 my ($result,$logourl) = 
13332:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
13333:                                             $dom,$confname,$img,$width,$height);
13334:                                 if ($result eq 'ok') {
13335:                                     $confhash->{$role}{$img} = $logourl;
13336: 				    $changes{$role}{'images'}{$img} = 1;
13337:                                 }
13338:                             }
13339:                         }
13340:                     }
13341:                 }
13342:             }
13343:         }
13344:         if (ref($domconfig) eq 'HASH') {
13345:             if (ref($domconfig->{$role}) eq 'HASH') {
13346:                 foreach my $img (@images) {
13347:                     if ($domconfig->{$role}{$img} ne '') {
13348:                         if ($env{'form.'.$role.'_del_'.$img}) {
13349:                             $confhash->{$role}{$img} = '';
13350:                             $changes{$role}{'images'}{$img} = 1;
13351:                         } else {
13352:                             if ($confhash->{$role}{$img} eq '') {
13353:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
13354:                             }
13355:                         }
13356:                     } else {
13357:                         if ($env{'form.'.$role.'_del_'.$img}) {
13358:                             $confhash->{$role}{$img} = '';
13359:                             $changes{$role}{'images'}{$img} = 1;
13360:                         } 
13361:                     }
13362:                     if ($role eq 'login') {
13363:                         if (($img eq 'logo') || ($img eq 'img')) {
13364:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
13365:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
13366:                                     $domconfig->{$role}{'showlogo'}{$img}) {
13367:                                     $changes{$role}{'showlogo'}{$img} = 1; 
13368:                                 }
13369:                             } else {
13370:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13371:                                     $changes{$role}{'showlogo'}{$img} = 1;
13372:                                 }
13373:                             }
13374:                         }
13375:                         if ($img ne 'login') {
13376:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
13377:                                 if ($confhash->{$role}{'alttext'}{$img} ne
13378:                                     $domconfig->{$role}{'alttext'}{$img}) {
13379:                                     $changes{$role}{'alttext'}{$img} = 1;
13380:                                 }
13381:                             } else {
13382:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13383:                                     $changes{$role}{'alttext'}{$img} = 1;
13384:                                 }
13385:                             }
13386:                         }
13387:                     }
13388:                 }
13389:                 if ($domconfig->{$role}{'font'} ne '') {
13390:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
13391:                         $changes{$role}{'font'} = 1;
13392:                     }
13393:                 } else {
13394:                     if ($confhash->{$role}{'font'}) {
13395:                         $changes{$role}{'font'} = 1;
13396:                     }
13397:                 }
13398:                 if ($role ne 'login') {
13399:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
13400:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
13401:                             $changes{$role}{'fontmenu'} = 1;
13402:                         }
13403:                     } else {
13404:                         if ($confhash->{$role}{'fontmenu'}) {
13405:                             $changes{$role}{'fontmenu'} = 1;
13406:                         }
13407:                     }
13408:                 }
13409:                 foreach my $item (@bgs) {
13410:                     if ($domconfig->{$role}{$item} ne '') {
13411:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13412:                             $changes{$role}{'bgs'}{$item} = 1;
13413:                         } 
13414:                     } else {
13415:                         if ($confhash->{$role}{$item}) {
13416:                             $changes{$role}{'bgs'}{$item} = 1;
13417:                         }
13418:                     }
13419:                 }
13420:                 foreach my $item (@links) {
13421:                     if ($domconfig->{$role}{$item} ne '') {
13422:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13423:                             $changes{$role}{'links'}{$item} = 1;
13424:                         }
13425:                     } else {
13426:                         if ($confhash->{$role}{$item}) {
13427:                             $changes{$role}{'links'}{$item} = 1;
13428:                         }
13429:                     }
13430:                 }
13431:                 foreach my $item (@logintext) {
13432:                     if ($domconfig->{$role}{$item} ne '') {
13433:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13434:                             $changes{$role}{'logintext'}{$item} = 1;
13435:                         }
13436:                     } else {
13437:                         if ($confhash->{$role}{$item}) {
13438:                             $changes{$role}{'logintext'}{$item} = 1;
13439:                         }
13440:                     }
13441:                 }
13442:             } else {
13443:                 &default_change_checker($role,\@images,\@links,\@bgs,
13444:                                         \@logintext,$confhash,\%changes); 
13445:             }
13446:         } else {
13447:             &default_change_checker($role,\@images,\@links,\@bgs,
13448:                                     \@logintext,$confhash,\%changes); 
13449:         }
13450:     }
13451:     return ($errors,%changes);
13452: }
13453: 
13454: sub config_check {
13455:     my ($dom,$confname,$servadm) = @_;
13456:     my ($configuserok,$author_ok,$switchserver,%currroles);
13457:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
13458:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
13459:                                                    $confname,$servadm);
13460:     if ($configuserok eq 'ok') {
13461:         $switchserver = &check_switchserver($dom,$confname);
13462:         if ($switchserver eq '') {
13463:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
13464:         }
13465:     }
13466:     return ($configuserok,$author_ok,$switchserver);
13467: }
13468: 
13469: sub default_change_checker {
13470:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
13471:     foreach my $item (@{$links}) {
13472:         if ($confhash->{$role}{$item}) {
13473:             $changes->{$role}{'links'}{$item} = 1;
13474:         }
13475:     }
13476:     foreach my $item (@{$bgs}) {
13477:         if ($confhash->{$role}{$item}) {
13478:             $changes->{$role}{'bgs'}{$item} = 1;
13479:         }
13480:     }
13481:     foreach my $item (@{$logintext}) {
13482:         if ($confhash->{$role}{$item}) {
13483:             $changes->{$role}{'logintext'}{$item} = 1;
13484:         }
13485:     }
13486:     foreach my $img (@{$images}) {
13487:         if ($env{'form.'.$role.'_del_'.$img}) {
13488:             $confhash->{$role}{$img} = '';
13489:             $changes->{$role}{'images'}{$img} = 1;
13490:         }
13491:         if ($role eq 'login') {
13492:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13493:                 $changes->{$role}{'showlogo'}{$img} = 1;
13494:             }
13495:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
13496:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13497:                     $changes->{$role}{'alttext'}{$img} = 1;
13498:                 }
13499:             }
13500:         }
13501:     }
13502:     if ($confhash->{$role}{'font'}) {
13503:         $changes->{$role}{'font'} = 1;
13504:     }
13505: }
13506: 
13507: sub display_colorchgs {
13508:     my ($dom,$changes,$roles,$confhash) = @_;
13509:     my (%choices,$resulttext);
13510:     if (!grep(/^login$/,@{$roles})) {
13511:         $resulttext = &mt('Changes made:').'<br />';
13512:     }
13513:     foreach my $role (@{$roles}) {
13514:         if ($role eq 'login') {
13515:             %choices = &login_choices();
13516:         } else {
13517:             %choices = &color_font_choices();
13518:         }
13519:         if (ref($changes->{$role}) eq 'HASH') {
13520:             if ($role ne 'login') {
13521:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
13522:             }
13523:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
13524:                 if ($role ne 'login') {
13525:                     $resulttext .= '<ul>';
13526:                 }
13527:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
13528:                     if ($role ne 'login') {
13529:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
13530:                     }
13531:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
13532:                         if (($role eq 'login') && ($key eq 'showlogo')) {
13533:                             if ($confhash->{$role}{$key}{$item}) {
13534:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
13535:                             } else {
13536:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
13537:                             }
13538:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
13539:                             if ($confhash->{$role}{$key}{$item} ne '') {
13540:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
13541:                                                $confhash->{$role}{$key}{$item}).'</li>';
13542:                             } else {
13543:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
13544:                             }
13545:                         } elsif ($confhash->{$role}{$item} eq '') {
13546:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
13547:                         } else {
13548:                             my $newitem = $confhash->{$role}{$item};
13549:                             if ($key eq 'images') {
13550:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
13551:                             }
13552:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
13553:                         }
13554:                     }
13555:                     if ($role ne 'login') {
13556:                         $resulttext .= '</ul></li>';
13557:                     }
13558:                 } else {
13559:                     if ($confhash->{$role}{$key} eq '') {
13560:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
13561:                     } else {
13562:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
13563:                     }
13564:                 }
13565:                 if ($role ne 'login') {
13566:                     $resulttext .= '</ul>';
13567:                 }
13568:             }
13569:         }
13570:     }
13571:     return $resulttext;
13572: }
13573: 
13574: sub thumb_dimensions {
13575:     return ('200','50');
13576: }
13577: 
13578: sub check_dimensions {
13579:     my ($inputfile) = @_;
13580:     my ($fullwidth,$fullheight);
13581:     if ($inputfile =~ m|^[/\w.\-]+$|) {
13582:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
13583:             my $imageinfo = <PIPE>;
13584:             if (!close(PIPE)) {
13585:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
13586:             }
13587:             chomp($imageinfo);
13588:             my ($fullsize) = 
13589:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
13590:             if ($fullsize) {
13591:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
13592:             }
13593:         }
13594:     }
13595:     return ($fullwidth,$fullheight);
13596: }
13597: 
13598: sub check_configuser {
13599:     my ($uhome,$dom,$confname,$servadm) = @_;
13600:     my ($configuserok,%currroles);
13601:     if ($uhome eq 'no_host') {
13602:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
13603:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
13604:         $configuserok = 
13605:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
13606:                              $configpass,'','','','','',undef,$servadm);
13607:     } else {
13608:         $configuserok = 'ok';
13609:         %currroles = 
13610:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
13611:     }
13612:     return ($configuserok,%currroles);
13613: }
13614: 
13615: sub check_authorstatus {
13616:     my ($dom,$confname,%currroles) = @_;
13617:     my $author_ok;
13618:     if (!$currroles{':'.$dom.':au'}) {
13619:         my $start = time;
13620:         my $end = 0;
13621:         $author_ok = 
13622:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
13623:                                         'au',$end,$start,'','','domconfig');
13624:     } else {
13625:         $author_ok = 'ok';
13626:     }
13627:     return $author_ok;
13628: }
13629: 
13630: sub publishlogo {
13631:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
13632:     my ($output,$fname,$logourl,$madethumb);
13633:     if ($action eq 'upload') {
13634:         $fname=$env{'form.'.$formname.'.filename'};
13635:         chop($env{'form.'.$formname});
13636:     } else {
13637:         ($fname) = ($formname =~ /([^\/]+)$/);
13638:     }
13639:     if ($savefileas ne '') {
13640:         $fname = $savefileas;
13641:     }
13642:     $fname=&Apache::lonnet::clean_filename($fname);
13643: # See if there is anything left
13644:     unless ($fname) { return ('error: no uploaded file'); }
13645:     $fname="$subdir/$fname";
13646:     my $docroot=$r->dir_config('lonDocRoot');
13647:     my $filepath="$docroot/priv";
13648:     my $relpath = "$dom/$confname";
13649:     my ($fnamepath,$file,$fetchthumb);
13650:     $file=$fname;
13651:     if ($fname=~m|/|) {
13652:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
13653:     }
13654:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
13655:     my $count;
13656:     for ($count=5;$count<=$#parts;$count++) {
13657:         $filepath.="/$parts[$count]";
13658:         if ((-e $filepath)!=1) {
13659:             mkdir($filepath,02770);
13660:         }
13661:     }
13662:     # Check for bad extension and disallow upload
13663:     if ($file=~/\.(\w+)$/ &&
13664:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13665:         $output = 
13666:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
13667:     } elsif ($file=~/\.(\w+)$/ &&
13668:         !defined(&Apache::loncommon::fileembstyle($1))) {
13669:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
13670:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
13671:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
13672:     } elsif (-d "$filepath/$file") {
13673:         $output = &mt('Filename is a directory name - rename the file and re-upload');
13674:     } else {
13675:         my $source = $filepath.'/'.$file;
13676:         my $logfile;
13677:         if (!open($logfile,">>",$source.'.log')) {
13678:             return (&mt('No write permission to Authoring Space'));
13679:         }
13680:         print $logfile
13681: "\n================= Publish ".localtime()." ================\n".
13682: $env{'user.name'}.':'.$env{'user.domain'}."\n";
13683: # Save the file
13684:         if (!open(FH,">",$source)) {
13685:             &Apache::lonnet::logthis('Failed to create '.$source);
13686:             return (&mt('Failed to create file'));
13687:         }
13688:         if ($action eq 'upload') {
13689:             if (!print FH ($env{'form.'.$formname})) {
13690:                 &Apache::lonnet::logthis('Failed to write to '.$source);
13691:                 return (&mt('Failed to write file'));
13692:             }
13693:         } else {
13694:             my $original = &Apache::lonnet::filelocation('',$formname);
13695:             if(!copy($original,$source)) {
13696:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
13697:                 return (&mt('Failed to write file'));
13698:             }
13699:         }
13700:         close(FH);
13701:         chmod(0660, $source); # Permissions to rw-rw---.
13702: 
13703:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
13704:         my $copyfile=$targetdir.'/'.$file;
13705: 
13706:         my @parts=split(/\//,$targetdir);
13707:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
13708:         for (my $count=5;$count<=$#parts;$count++) {
13709:             $path.="/$parts[$count]";
13710:             if (!-e $path) {
13711:                 print $logfile "\nCreating directory ".$path;
13712:                 mkdir($path,02770);
13713:             }
13714:         }
13715:         my $versionresult;
13716:         if (-e $copyfile) {
13717:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
13718:         } else {
13719:             $versionresult = 'ok';
13720:         }
13721:         if ($versionresult eq 'ok') {
13722:             if (copy($source,$copyfile)) {
13723:                 print $logfile "\nCopied original source to ".$copyfile."\n";
13724:                 $output = 'ok';
13725:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
13726:                 push(@{$modified_urls},[$copyfile,$source]);
13727:                 my $metaoutput = 
13728:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
13729:                 unless ($registered_cleanup) {
13730:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13731:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13732:                     $registered_cleanup=1;
13733:                 }
13734:             } else {
13735:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
13736:                 $output = &mt('Failed to copy file to RES space').", $!";
13737:             }
13738:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
13739:                 my $inputfile = $filepath.'/'.$file;
13740:                 my $outfile = $filepath.'/'.'tn-'.$file;
13741:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
13742:                 if ($fullwidth ne '' && $fullheight ne '') { 
13743:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
13744:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
13745:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
13746:                         system({$args[0]} @args);
13747:                         chmod(0660, $filepath.'/tn-'.$file);
13748:                         if (-e $outfile) {
13749:                             my $copyfile=$targetdir.'/tn-'.$file;
13750:                             if (copy($outfile,$copyfile)) {
13751:                                 print $logfile "\nCopied source to ".$copyfile."\n";
13752:                                 my $thumb_metaoutput = 
13753:                                     &write_metadata($dom,$confname,$formname,
13754:                                                     $targetdir,'tn-'.$file,$logfile);
13755:                                 push(@{$modified_urls},[$copyfile,$outfile]);
13756:                                 unless ($registered_cleanup) {
13757:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13758:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13759:                                     $registered_cleanup=1;
13760:                                 }
13761:                                 $madethumb = 1;
13762:                             } else {
13763:                                 print $logfile "\nUnable to write ".$copyfile.
13764:                                                ':'.$!."\n";
13765:                             }
13766:                         }
13767:                     }
13768:                 }
13769:             }
13770:         } else {
13771:             $output = $versionresult;
13772:         }
13773:     }
13774:     return ($output,$logourl,$madethumb);
13775: }
13776: 
13777: sub logo_versioning {
13778:     my ($targetdir,$file,$logfile) = @_;
13779:     my $target = $targetdir.'/'.$file;
13780:     my ($maxversion,$fn,$extn,$output);
13781:     $maxversion = 0;
13782:     if ($file =~ /^(.+)\.(\w+)$/) {
13783:         $fn=$1;
13784:         $extn=$2;
13785:     }
13786:     opendir(DIR,$targetdir);
13787:     while (my $filename=readdir(DIR)) {
13788:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
13789:             $maxversion=($1>$maxversion)?$1:$maxversion;
13790:         }
13791:     }
13792:     $maxversion++;
13793:     print $logfile "\nCreating old version ".$maxversion."\n";
13794:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
13795:     if (copy($target,$copyfile)) {
13796:         print $logfile "Copied old target to ".$copyfile."\n";
13797:         $copyfile=$copyfile.'.meta';
13798:         if (copy($target.'.meta',$copyfile)) {
13799:             print $logfile "Copied old target metadata to ".$copyfile."\n";
13800:             $output = 'ok';
13801:         } else {
13802:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
13803:             $output = &mt('Failed to copy old meta').", $!, ";
13804:         }
13805:     } else {
13806:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
13807:         $output = &mt('Failed to copy old target').", $!, ";
13808:     }
13809:     return $output;
13810: }
13811: 
13812: sub write_metadata {
13813:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
13814:     my (%metadatafields,%metadatakeys,$output);
13815:     $metadatafields{'title'}=$formname;
13816:     $metadatafields{'creationdate'}=time;
13817:     $metadatafields{'lastrevisiondate'}=time;
13818:     $metadatafields{'copyright'}='public';
13819:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
13820:                                          $env{'user.domain'};
13821:     $metadatafields{'authorspace'}=$confname.':'.$dom;
13822:     $metadatafields{'domain'}=$dom;
13823:     {
13824:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
13825:         my $mfh;
13826:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
13827:             foreach (sort(keys(%metadatafields))) {
13828:                 unless ($_=~/\./) {
13829:                     my $unikey=$_;
13830:                     $unikey=~/^([A-Za-z]+)/;
13831:                     my $tag=$1;
13832:                     $tag=~tr/A-Z/a-z/;
13833:                     print $mfh "\n\<$tag";
13834:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
13835:                         my $value=$metadatafields{$unikey.'.'.$_};
13836:                         $value=~s/\"/\'\'/g;
13837:                         print $mfh ' '.$_.'="'.$value.'"';
13838:                     }
13839:                     print $mfh '>'.
13840:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
13841:                             .'</'.$tag.'>';
13842:                 }
13843:             }
13844:             $output = 'ok';
13845:             print $logfile "\nWrote metadata";
13846:             close($mfh);
13847:         } else {
13848:             print $logfile "\nFailed to open metadata file";
13849:             $output = &mt('Could not write metadata');
13850:         }
13851:     }
13852:     return $output;
13853: }
13854: 
13855: sub notifysubscribed {
13856:     foreach my $targetsource (@{$modified_urls}){
13857:         next unless (ref($targetsource) eq 'ARRAY');
13858:         my ($target,$source)=@{$targetsource};
13859:         if ($source ne '') {
13860:             if (open(my $logfh,">>",$source.'.log')) {
13861:                 print $logfh "\nCleanup phase: Notifications\n";
13862:                 my @subscribed=&subscribed_hosts($target);
13863:                 foreach my $subhost (@subscribed) {
13864:                     print $logfh "\nNotifying host ".$subhost.':';
13865:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
13866:                     print $logfh $reply;
13867:                 }
13868:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
13869:                 foreach my $subhost (@subscribedmeta) {
13870:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
13871:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
13872:                                                         $subhost);
13873:                     print $logfh $reply;
13874:                 }
13875:                 print $logfh "\n============ Done ============\n";
13876:                 close($logfh);
13877:             }
13878:         }
13879:     }
13880:     return OK;
13881: }
13882: 
13883: sub subscribed_hosts {
13884:     my ($target) = @_;
13885:     my @subscribed;
13886:     if (open(my $fh,"<","$target.subscription")) {
13887:         while (my $subline=<$fh>) {
13888:             if ($subline =~ /^($match_lonid):/) {
13889:                 my $host = $1;
13890:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
13891:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
13892:                         push(@subscribed,$host);
13893:                     }
13894:                 }
13895:             }
13896:         }
13897:     }
13898:     return @subscribed;
13899: }
13900: 
13901: sub check_switchserver {
13902:     my ($dom,$confname) = @_;
13903:     my ($allowed,$switchserver);
13904:     my $home = &Apache::lonnet::homeserver($confname,$dom);
13905:     if ($home eq 'no_host') {
13906:         $home = &Apache::lonnet::domain($dom,'primary');
13907:     }
13908:     my @ids=&Apache::lonnet::current_machine_ids();
13909:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
13910:     if (!$allowed) {
13911: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
13912:     }
13913:     return $switchserver;
13914: }
13915: 
13916: sub modify_quotas {
13917:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13918:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
13919:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
13920:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
13921:         $validationfieldsref);
13922:     if ($action eq 'quotas') {
13923:         $context = 'tools'; 
13924:     } else {
13925:         $context = $action;
13926:     }
13927:     if ($context eq 'requestcourses') {
13928:         @usertools = ('official','unofficial','community','textbook','placement','lti');
13929:         @options =('norequest','approval','validate','autolimit');
13930:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
13931:         %titles = &courserequest_titles();
13932:         $toolregexp = join('|',@usertools);
13933:         %conditions = &courserequest_conditions();
13934:         $confname = $dom.'-domainconfig';
13935:         my $servadm = $r->dir_config('lonAdmEMail');
13936:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13937:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
13938:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
13939:     } elsif ($context eq 'requestauthor') {
13940:         @usertools = ('author');
13941:         %titles = &authorrequest_titles();
13942:     } else {
13943:         @usertools = ('aboutme','blog','webdav','portfolio');
13944:         %titles = &tool_titles();
13945:     }
13946:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13947:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13948:     foreach my $key (keys(%env)) {
13949:         if ($context eq 'requestcourses') {
13950:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
13951:                 my $item = $1;
13952:                 my $type = $2;
13953:                 if ($type =~ /^limit_(.+)/) {
13954:                     $limithash{$item}{$1} = $env{$key};
13955:                 } else {
13956:                     $confhash{$item}{$type} = $env{$key};
13957:                 }
13958:             }
13959:         } elsif ($context eq 'requestauthor') {
13960:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
13961:                 $confhash{$1} = $env{$key};
13962:             }
13963:         } else {
13964:             if ($key =~ /^form\.quota_(.+)$/) {
13965:                 $confhash{'defaultquota'}{$1} = $env{$key};
13966:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
13967:                 $confhash{'authorquota'}{$1} = $env{$key};
13968:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
13969:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
13970:             }
13971:         }
13972:     }
13973:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13974:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
13975:         @approvalnotify = sort(@approvalnotify);
13976:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
13977:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
13978:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
13979:         foreach my $type (@hasuniquecode) {
13980:             if (grep(/^\Q$type\E$/,@crstypes)) {
13981:                 $confhash{'uniquecode'}{$type} = 1;
13982:             }
13983:         }
13984:         my (%newbook,%allpos);
13985:         if ($context eq 'requestcourses') {
13986:             foreach my $type ('textbooks','templates') {
13987:                 @{$allpos{$type}} = (); 
13988:                 my $invalid;
13989:                 if ($type eq 'textbooks') {
13990:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
13991:                 } else {
13992:                     $invalid = &mt('Invalid LON-CAPA course for template');
13993:                 }
13994:                 if ($env{'form.'.$type.'_addbook'}) {
13995:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
13996:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
13997:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
13998:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
13999:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
14000:                         } else {
14001:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
14002:                             my $position = $env{'form.'.$type.'_addbook_pos'};
14003:                             $position =~ s/\D+//g;
14004:                             if ($position ne '') {
14005:                                 $allpos{$type}[$position] = $newbook{$type};
14006:                             }
14007:                         }
14008:                     } else {
14009:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
14010:                     }
14011:                 }
14012:             } 
14013:         }
14014:         if (ref($domconfig{$action}) eq 'HASH') {
14015:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
14016:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
14017:                     $changes{'notify'}{'approval'} = 1;
14018:                 }
14019:             } else {
14020:                 if ($confhash{'notify'}{'approval'}) {
14021:                     $changes{'notify'}{'approval'} = 1;
14022:                 }
14023:             }
14024:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
14025:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
14026:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
14027:                         unless ($confhash{'uniquecode'}{$crstype}) {
14028:                             $changes{'uniquecode'} = 1;
14029:                         }
14030:                     }
14031:                     unless ($changes{'uniquecode'}) {
14032:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
14033:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
14034:                                 $changes{'uniquecode'} = 1;
14035:                             }
14036:                         }
14037:                     }
14038:                } else {
14039:                    $changes{'uniquecode'} = 1;
14040:                }
14041:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
14042:                 $changes{'uniquecode'} = 1;
14043:             }
14044:             if ($context eq 'requestcourses') {
14045:                 foreach my $type ('textbooks','templates') {
14046:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
14047:                         my %deletions;
14048:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
14049:                         if (@todelete) {
14050:                             map { $deletions{$_} = 1; } @todelete;
14051:                         }
14052:                         my %imgdeletions;
14053:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
14054:                         if (@todeleteimages) {
14055:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
14056:                         }
14057:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
14058:                         for (my $i=0; $i<=$maxnum; $i++) {
14059:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
14060:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
14061:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
14062:                                 if ($deletions{$key}) {
14063:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
14064:                                         #FIXME need to obsolete item in RES space
14065:                                     }
14066:                                     next;
14067:                                 } else {
14068:                                     my $newpos = $env{'form.'.$itemid};
14069:                                     $newpos =~ s/\D+//g;
14070:                                     foreach my $item ('subject','title','publisher','author') {
14071:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14072:                                                  ($type eq 'templates'));
14073:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
14074:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
14075:                                             $changes{$type}{$key} = 1;
14076:                                         }
14077:                                     }
14078:                                     $allpos{$type}[$newpos] = $key;
14079:                                 }
14080:                                 if ($imgdeletions{$key}) {
14081:                                     $changes{$type}{$key} = 1;
14082:                                     #FIXME need to obsolete item in RES space
14083:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
14084:                                     my ($cdom,$cnum) = split(/_/,$key);
14085:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14086:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14087:                                     } else {
14088:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
14089:                                                                                       $cdom,$cnum,$type,$configuserok,
14090:                                                                                       $switchserver,$author_ok);
14091:                                         if ($imgurl) {
14092:                                             $confhash{$type}{$key}{'image'} = $imgurl;
14093:                                             $changes{$type}{$key} = 1; 
14094:                                         }
14095:                                         if ($error) {
14096:                                             &Apache::lonnet::logthis($error);
14097:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14098:                                         }
14099:                                     }
14100:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
14101:                                     $confhash{$type}{$key}{'image'} = 
14102:                                         $domconfig{$action}{$type}{$key}{'image'};
14103:                                 }
14104:                             }
14105:                         }
14106:                     }
14107:                 }
14108:             }
14109:         } else {
14110:             if ($confhash{'notify'}{'approval'}) {
14111:                 $changes{'notify'}{'approval'} = 1;
14112:             }
14113:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
14114:                 $changes{'uniquecode'} = 1;
14115:             }
14116:         }
14117:         if ($context eq 'requestcourses') {
14118:             foreach my $type ('textbooks','templates') {
14119:                 if ($newbook{$type}) {
14120:                     $changes{$type}{$newbook{$type}} = 1;
14121:                     foreach my $item ('subject','title','publisher','author') {
14122:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14123:                                  ($type eq 'template'));
14124:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
14125:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
14126:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
14127:                         }
14128:                     }
14129:                     if ($type eq 'textbooks') {
14130:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
14131:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
14132:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14133:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14134:                             } else {
14135:                                 my ($imageurl,$error) =
14136:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
14137:                                                             $configuserok,$switchserver,$author_ok);
14138:                                 if ($imageurl) {
14139:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
14140:                                 }
14141:                                 if ($error) {
14142:                                     &Apache::lonnet::logthis($error);
14143:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14144:                                 }
14145:                             }
14146:                         }
14147:                     }
14148:                 }
14149:                 if (@{$allpos{$type}} > 0) {
14150:                     my $idx = 0;
14151:                     foreach my $item (@{$allpos{$type}}) {
14152:                         if ($item ne '') {
14153:                             $confhash{$type}{$item}{'order'} = $idx;
14154:                             if (ref($domconfig{$action}) eq 'HASH') {
14155:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
14156:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
14157:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
14158:                                             $changes{$type}{$item} = 1;
14159:                                         }
14160:                                     }
14161:                                 }
14162:                             }
14163:                             $idx ++;
14164:                         }
14165:                     }
14166:                 }
14167:             }
14168:             if (ref($validationitemsref) eq 'ARRAY') {
14169:                 foreach my $item (@{$validationitemsref}) {
14170:                     if ($item eq 'fields') {
14171:                         my @changed;
14172:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
14173:                         if (@{$confhash{'validation'}{$item}} > 0) {
14174:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
14175:                         }
14176:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14177:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14178:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
14179:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
14180:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
14181:                                 } else {
14182:                                     @changed = @{$confhash{'validation'}{$item}};
14183:                                 }
14184:                             } else {
14185:                                 @changed = @{$confhash{'validation'}{$item}};
14186:                             }
14187:                         } else {
14188:                             @changed = @{$confhash{'validation'}{$item}};
14189:                         }
14190:                         if (@changed) {
14191:                             if ($confhash{'validation'}{$item}) {
14192:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
14193:                             } else {
14194:                                 $changes{'validation'}{$item} = &mt('None');
14195:                             }
14196:                         }
14197:                     } else {
14198:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
14199:                         if ($item eq 'markup') {
14200:                             if ($env{'form.requestcourses_validation_'.$item}) {
14201:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
14202:                             }
14203:                         }
14204:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14205:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14206:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
14207:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14208:                                 }
14209:                             } else {
14210:                                 if ($confhash{'validation'}{$item} ne '') {
14211:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14212:                                 }
14213:                             }
14214:                         } else {
14215:                             if ($confhash{'validation'}{$item} ne '') {
14216:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14217:                             }
14218:                         }
14219:                     }
14220:                 }
14221:             }
14222:             if ($env{'form.validationdc'}) {
14223:                 my $newval = $env{'form.validationdc'};
14224:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
14225:                 if (exists($domcoords{$newval})) {
14226:                     $confhash{'validation'}{'dc'} = $newval;
14227:                 }
14228:             }
14229:             if (ref($confhash{'validation'}) eq 'HASH') {
14230:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14231:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14232:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14233:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
14234:                                 if ($confhash{'validation'}{'dc'} eq '') {
14235:                                     $changes{'validation'}{'dc'} = &mt('None');
14236:                                 } else {
14237:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14238:                                 }
14239:                             }
14240:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
14241:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14242:                         }
14243:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
14244:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14245:                     }
14246:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
14247:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14248:                 }
14249:             } else {
14250:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14251:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14252:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14253:                             $changes{'validation'}{'dc'} = &mt('None');
14254:                         }
14255:                     }
14256:                 }
14257:             }
14258:         }
14259:     } else {
14260:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
14261:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
14262:     }
14263:     foreach my $item (@usertools) {
14264:         foreach my $type (@{$types},'default','_LC_adv') {
14265:             my $unset; 
14266:             if ($context eq 'requestcourses') {
14267:                 $unset = '0';
14268:                 if ($type eq '_LC_adv') {
14269:                     $unset = '';
14270:                 }
14271:                 if ($confhash{$item}{$type} eq 'autolimit') {
14272:                     $confhash{$item}{$type} .= '=';
14273:                     unless ($limithash{$item}{$type} =~ /\D/) {
14274:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
14275:                     }
14276:                 }
14277:             } elsif ($context eq 'requestauthor') {
14278:                 $unset = '0';
14279:                 if ($type eq '_LC_adv') {
14280:                     $unset = '';
14281:                 }
14282:             } else {
14283:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
14284:                     $confhash{$item}{$type} = 1;
14285:                 } else {
14286:                     $confhash{$item}{$type} = 0;
14287:                 }
14288:             }
14289:             if (ref($domconfig{$action}) eq 'HASH') {
14290:                 if ($action eq 'requestauthor') {
14291:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
14292:                         $changes{$type} = 1;
14293:                     }
14294:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
14295:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
14296:                         $changes{$item}{$type} = 1;
14297:                     }
14298:                 } else {
14299:                     if ($context eq 'requestcourses') {
14300:                         if ($confhash{$item}{$type} ne $unset) {
14301:                             $changes{$item}{$type} = 1;
14302:                         }
14303:                     } else {
14304:                         if (!$confhash{$item}{$type}) {
14305:                             $changes{$item}{$type} = 1;
14306:                         }
14307:                     }
14308:                 }
14309:             } else {
14310:                 if ($context eq 'requestcourses') {
14311:                     if ($confhash{$item}{$type} ne $unset) {
14312:                         $changes{$item}{$type} = 1;
14313:                     }
14314:                 } elsif ($context eq 'requestauthor') {
14315:                     if ($confhash{$type} ne $unset) {
14316:                         $changes{$type} = 1;
14317:                     }
14318:                 } else {
14319:                     if (!$confhash{$item}{$type}) {
14320:                         $changes{$item}{$type} = 1;
14321:                     }
14322:                 }
14323:             }
14324:         }
14325:     }
14326:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
14327:         if (ref($domconfig{'quotas'}) eq 'HASH') {
14328:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14329:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
14330:                     if (exists($confhash{'defaultquota'}{$key})) {
14331:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
14332:                             $changes{'defaultquota'}{$key} = 1;
14333:                         }
14334:                     } else {
14335:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
14336:                     }
14337:                 }
14338:             } else {
14339:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
14340:                     if (exists($confhash{'defaultquota'}{$key})) {
14341:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
14342:                             $changes{'defaultquota'}{$key} = 1;
14343:                         }
14344:                     } else {
14345:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
14346:                     }
14347:                 }
14348:             }
14349:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14350:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
14351:                     if (exists($confhash{'authorquota'}{$key})) {
14352:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
14353:                             $changes{'authorquota'}{$key} = 1;
14354:                         }
14355:                     } else {
14356:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
14357:                     }
14358:                 }
14359:             }
14360:         }
14361:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
14362:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
14363:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14364:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14365:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
14366:                             $changes{'defaultquota'}{$key} = 1;
14367:                         }
14368:                     } else {
14369:                         if (!exists($domconfig{'quotas'}{$key})) {
14370:                             $changes{'defaultquota'}{$key} = 1;
14371:                         }
14372:                     }
14373:                 } else {
14374:                     $changes{'defaultquota'}{$key} = 1;
14375:                 }
14376:             }
14377:         }
14378:         if (ref($confhash{'authorquota'}) eq 'HASH') {
14379:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
14380:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14381:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14382:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
14383:                             $changes{'authorquota'}{$key} = 1;
14384:                         }
14385:                     } else {
14386:                         $changes{'authorquota'}{$key} = 1;
14387:                     }
14388:                 } else {
14389:                     $changes{'authorquota'}{$key} = 1;
14390:                 }
14391:             }
14392:         }
14393:     }
14394: 
14395:     if ($context eq 'requestauthor') {
14396:         $domdefaults{'requestauthor'} = \%confhash;
14397:     } else {
14398:         foreach my $key (keys(%confhash)) {
14399:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
14400:                 $domdefaults{$key} = $confhash{$key};
14401:             }
14402:         }
14403:     }
14404: 
14405:     my %quotahash = (
14406:                       $action => { %confhash }
14407:                     );
14408:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
14409:                                              $dom);
14410:     if ($putresult eq 'ok') {
14411:         if (keys(%changes) > 0) {
14412:             my $cachetime = 24*60*60;
14413:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14414:             if (ref($lastactref) eq 'HASH') {
14415:                 $lastactref->{'domdefaults'} = 1;
14416:             }
14417:             $resulttext = &mt('Changes made:').'<ul>';
14418:             unless (($context eq 'requestcourses') ||
14419:                     ($context eq 'requestauthor')) {
14420:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
14421:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
14422:                     foreach my $type (@{$types},'default') {
14423:                         if (defined($changes{'defaultquota'}{$type})) {
14424:                             my $typetitle = $usertypes->{$type};
14425:                             if ($type eq 'default') {
14426:                                 $typetitle = $othertitle;
14427:                             }
14428:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
14429:                         }
14430:                     }
14431:                     $resulttext .= '</ul></li>';
14432:                 }
14433:                 if (ref($changes{'authorquota'}) eq 'HASH') {
14434:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
14435:                     foreach my $type (@{$types},'default') {
14436:                         if (defined($changes{'authorquota'}{$type})) {
14437:                             my $typetitle = $usertypes->{$type};
14438:                             if ($type eq 'default') {
14439:                                 $typetitle = $othertitle;
14440:                             }
14441:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
14442:                         }
14443:                     }
14444:                     $resulttext .= '</ul></li>';
14445:                 }
14446:             }
14447:             my %newenv;
14448:             foreach my $item (@usertools) {
14449:                 my (%haschgs,%inconf);
14450:                 if ($context eq 'requestauthor') {
14451:                     %haschgs = %changes;
14452:                     %inconf = %confhash;
14453:                 } else {
14454:                     if (ref($changes{$item}) eq 'HASH') {
14455:                         %haschgs = %{$changes{$item}};
14456:                     }
14457:                     if (ref($confhash{$item}) eq 'HASH') {
14458:                         %inconf = %{$confhash{$item}};
14459:                     }
14460:                 }
14461:                 if (keys(%haschgs) > 0) {
14462:                     my $newacc = 
14463:                         &Apache::lonnet::usertools_access($env{'user.name'},
14464:                                                           $env{'user.domain'},
14465:                                                           $item,'reload',$context);
14466:                     if (($context eq 'requestcourses') ||
14467:                         ($context eq 'requestauthor')) {
14468:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
14469:                             $newenv{'environment.canrequest.'.$item} = $newacc;
14470:                         }
14471:                     } else {
14472:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
14473:                             $newenv{'environment.availabletools.'.$item} = $newacc;
14474:                         }
14475:                     }
14476:                     unless ($context eq 'requestauthor') {
14477:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
14478:                     }
14479:                     foreach my $type (@{$types},'default','_LC_adv') {
14480:                         if ($haschgs{$type}) {
14481:                             my $typetitle = $usertypes->{$type};
14482:                             if ($type eq 'default') {
14483:                                 $typetitle = $othertitle;
14484:                             } elsif ($type eq '_LC_adv') {
14485:                                 $typetitle = 'LON-CAPA Advanced Users'; 
14486:                             }
14487:                             if ($inconf{$type}) {
14488:                                 if ($context eq 'requestcourses') {
14489:                                     my $cond;
14490:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
14491:                                         if ($1 eq '') {
14492:                                             $cond = &mt('(Automatic processing of any request).');
14493:                                         } else {
14494:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
14495:                                         }
14496:                                     } else { 
14497:                                         $cond = $conditions{$inconf{$type}};
14498:                                     }
14499:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
14500:                                 } elsif ($context eq 'requestauthor') {
14501:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
14502:                                                              $titles{$inconf{$type}},$typetitle);
14503: 
14504:                                 } else {
14505:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
14506:                                 }
14507:                             } else {
14508:                                 if ($type eq '_LC_adv') {
14509:                                     if ($inconf{$type} eq '0') {
14510:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14511:                                     } else { 
14512:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
14513:                                     }
14514:                                 } else {
14515:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14516:                                 }
14517:                             }
14518:                         }
14519:                     }
14520:                     unless ($context eq 'requestauthor') {
14521:                         $resulttext .= '</ul></li>';
14522:                     }
14523:                 }
14524:             }
14525:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
14526:                 if (ref($changes{'notify'}) eq 'HASH') {
14527:                     if ($changes{'notify'}{'approval'}) {
14528:                         if (ref($confhash{'notify'}) eq 'HASH') {
14529:                             if ($confhash{'notify'}{'approval'}) {
14530:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
14531:                             } else {
14532:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
14533:                             }
14534:                         }
14535:                     }
14536:                 }
14537:             }
14538:             if ($action eq 'requestcourses') {
14539:                 my @offon = ('off','on');
14540:                 if ($changes{'uniquecode'}) {
14541:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
14542:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
14543:                         $resulttext .= '<li>'.
14544:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
14545:                                        '</li>';
14546:                     } else {
14547:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
14548:                                        '</li>';
14549:                     }
14550:                 }
14551:                 foreach my $type ('textbooks','templates') {
14552:                     if (ref($changes{$type}) eq 'HASH') {
14553:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
14554:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
14555:                             my %coursehash = &Apache::lonnet::coursedescription($key);
14556:                             my $coursetitle = $coursehash{'description'};
14557:                             my $position = $confhash{$type}{$key}{'order'} + 1;
14558:                             $resulttext .= '<li>';
14559:                             foreach my $item ('subject','title','publisher','author') {
14560:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
14561:                                          ($type eq 'templates'));
14562:                                 my $name = $item.':';
14563:                                 $name =~ s/^(\w)/\U$1/;
14564:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
14565:                             }
14566:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
14567:                             if ($type eq 'textbooks') {
14568:                                 if ($confhash{$type}{$key}{'image'}) {
14569:                                     $resulttext .= ' '.&mt('Image: [_1]',
14570:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
14571:                                                    ' alt="Textbook cover" />').'<br />';
14572:                                 }
14573:                             }
14574:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
14575:                         }
14576:                         $resulttext .= '</ul></li>';
14577:                     }
14578:                 }
14579:                 if (ref($changes{'validation'}) eq 'HASH') {
14580:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
14581:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
14582:                         foreach my $item (@{$validationitemsref}) {
14583:                             if (exists($changes{'validation'}{$item})) {
14584:                                 if ($item eq 'markup') {
14585:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14586:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
14587:                                 } else {
14588:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14589:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
14590:                                 }
14591:                             }
14592:                         }
14593:                         if (exists($changes{'validation'}{'dc'})) {
14594:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
14595:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
14596:                         }
14597:                     }
14598:                 }
14599:             }
14600:             $resulttext .= '</ul>';
14601:             if (keys(%newenv)) {
14602:                 &Apache::lonnet::appenv(\%newenv);
14603:             }
14604:         } else {
14605:             if ($context eq 'requestcourses') {
14606:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
14607:             } elsif ($context eq 'requestauthor') {
14608:                 $resulttext = &mt('No changes made to rights to request author space.');
14609:             } else {
14610:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
14611:             }
14612:         }
14613:     } else {
14614:         $resulttext = '<span class="LC_error">'.
14615: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14616:     }
14617:     if ($errors) {
14618:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
14619:                        '<ul>'.$errors.'</ul></p>';
14620:     }
14621:     return $resulttext;
14622: }
14623: 
14624: sub process_textbook_image {
14625:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
14626:     my $filename = $env{'form.'.$caller.'.filename'};
14627:     my ($error,$url);
14628:     my ($width,$height) = (50,50);
14629:     if ($configuserok eq 'ok') {
14630:         if ($switchserver) {
14631:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
14632:                          $switchserver);
14633:         } elsif ($author_ok eq 'ok') {
14634:             my ($result,$imageurl) =
14635:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14636:                              "$type/$cdom/$cnum/cover",$width,$height);
14637:             if ($result eq 'ok') {
14638:                 $url = $imageurl;
14639:             } else {
14640:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14641:             }
14642:         } else {
14643:             $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);
14644:         }
14645:     } else {
14646:         $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);
14647:     }
14648:     return ($url,$error);
14649: }
14650: 
14651: sub modify_ltitools {
14652:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14653:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14654:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14655:     my $confname = $dom.'-domainconfig';
14656:     my $servadm = $r->dir_config('lonAdmEMail');
14657:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14658:     my (%posslti,%possfield);
14659:     my @courseroles = ('cc','in','ta','ep','st');
14660:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
14661:     map { $posslti{$_} = 1; } @ltiroles;
14662:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
14663:     map { $possfield{$_} = 1; } @allfields;
14664:     my %lt = &ltitools_names(); 
14665:     if ($env{'form.ltitools_add'}) {
14666:         my $title = $env{'form.ltitools_add_title'};
14667:         $title =~ s/(`)/'/g;
14668:         ($newid,my $error) = &get_ltitools_id($dom,$title);
14669:         if ($newid) {
14670:             my $position = $env{'form.ltitools_add_pos'};
14671:             $position =~ s/\D+//g;
14672:             if ($position ne '') {
14673:                 $allpos[$position] = $newid;
14674:             }
14675:             $changes{$newid} = 1;
14676:             foreach my $item ('title','url','key','secret','lifetime') {
14677:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
14678:                 if ($item eq 'lifetime') {
14679:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
14680:                 }
14681:                 if ($env{'form.ltitools_add_'.$item}) {
14682:                     if (($item eq 'key') || ($item eq 'secret')) {
14683:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14684:                     } else {
14685:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14686:                     }
14687:                 }
14688:             }
14689:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
14690:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
14691:             }
14692:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
14693:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
14694:             }
14695:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
14696:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
14697:             } else {
14698:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
14699:             }
14700:             foreach my $item ('width','height','linktext','explanation') {
14701:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
14702:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
14703:                 if (($item eq 'width') || ($item eq 'height')) {
14704:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
14705:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
14706:                     }
14707:                 } else {
14708:                     if ($env{'form.ltitools_add_'.$item} ne '') {
14709:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
14710:                     }
14711:                 }
14712:             }
14713:             if ($env{'form.ltitools_add_target'} eq 'window') {
14714:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14715:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
14716:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14717:             } else {
14718:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
14719:             }
14720:             foreach my $item ('passback','roster') {
14721:                 if ($env{'form.ltitools_'.$item.'_add'}) {
14722:                     $confhash{$newid}{$item} = 1;
14723:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
14724:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
14725:                         $lifetime =~ s/^\s+|\s+$//g;
14726:                         if ($lifetime =~ /^\d+\.?\d*$/) {
14727:                             $confhash{$newid}{$item.'valid'} = $lifetime;
14728:                         }
14729:                     }
14730:                 }
14731:             }
14732:             if ($env{'form.ltitools_add_image.filename'} ne '') {
14733:                 my ($imageurl,$error) =
14734:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
14735:                                             $configuserok,$switchserver,$author_ok);
14736:                 if ($imageurl) {
14737:                     $confhash{$newid}{'image'} = $imageurl;
14738:                 }
14739:                 if ($error) {
14740:                     &Apache::lonnet::logthis($error);
14741:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14742:                 }
14743:             }
14744:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
14745:             foreach my $field (@fields) {
14746:                 if ($possfield{$field}) {
14747:                     if ($field eq 'roles') {
14748:                         foreach my $role (@courseroles) {
14749:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
14750:                             if (($choice ne '') && ($posslti{$choice})) {
14751:                                 $confhash{$newid}{'roles'}{$role} = $choice;
14752:                                 if ($role eq 'cc') {
14753:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
14754:                                 }
14755:                             }
14756:                         }
14757:                     } else {
14758:                         $confhash{$newid}{'fields'}{$field} = 1;
14759:                     }
14760:                 }
14761:             }
14762:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
14763:                 if ($confhash{$newid}{'fields'}{'user'}) {
14764:                     if ($env{'form.ltitools_userincdom_add'}) {
14765:                         $confhash{$newid}{'incdom'} = 1;
14766:                     }
14767:                 }
14768:             }
14769:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
14770:             foreach my $item (@courseconfig) {
14771:                 $confhash{$newid}{'crsconf'}{$item} = 1;
14772:             }
14773:             if ($env{'form.ltitools_add_custom'}) {
14774:                 my $name = $env{'form.ltitools_add_custom_name'};
14775:                 my $value = $env{'form.ltitools_add_custom_value'};
14776:                 $value =~ s/(`)/'/g;
14777:                 $name =~ s/(`)/'/g;
14778:                 $confhash{$newid}{'custom'}{$name} = $value;
14779:             }
14780:         } else {
14781:             my $error = &mt('Failed to acquire unique ID for new external tool');   
14782:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14783:         }
14784:     }
14785:     if (ref($domconfig{$action}) eq 'HASH') {
14786:         my %deletions;
14787:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
14788:         if (@todelete) {
14789:             map { $deletions{$_} = 1; } @todelete;
14790:         }
14791:         my %customadds;
14792:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
14793:         if (@newcustom) {
14794:             map { $customadds{$_} = 1; } @newcustom;
14795:         } 
14796:         my %imgdeletions;
14797:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
14798:         if (@todeleteimages) {
14799:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14800:         }
14801:         my $maxnum = $env{'form.ltitools_maxnum'};
14802:         for (my $i=0; $i<=$maxnum; $i++) {
14803:             my $itemid = $env{'form.ltitools_id_'.$i};
14804:             $itemid =~ s/\D+//g;
14805:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14806:                 if ($deletions{$itemid}) {
14807:                     if ($domconfig{$action}{$itemid}{'image'}) {
14808:                         #FIXME need to obsolete item in RES space
14809:                     }
14810:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
14811:                     next;
14812:                 } else {
14813:                     my $newpos = $env{'form.ltitools_'.$itemid};
14814:                     $newpos =~ s/\D+//g;
14815:                     foreach my $item ('title','url','lifetime') {
14816:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14817:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14818:                             $changes{$itemid} = 1;
14819:                         }
14820:                     }
14821:                     foreach my $item ('key','secret') {
14822:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14823:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
14824:                             $changes{$itemid} = 1;
14825:                         }
14826:                     }
14827:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
14828:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
14829:                     }
14830:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
14831:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
14832:                     }
14833:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
14834:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
14835:                     } else {
14836:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
14837:                     }
14838:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
14839:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
14840:                             $changes{$itemid} = 1;
14841:                         }
14842:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
14843:                         $changes{$itemid} = 1;
14844:                     }
14845:                     foreach my $size ('width','height') {
14846:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
14847:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
14848:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
14849:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
14850:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14851:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
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'}{$size} ne '') {
14859:                                 $changes{$itemid} = 1;
14860:                             }
14861:                         }
14862:                     }
14863:                     foreach my $item ('linktext','explanation') {
14864:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
14865:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
14866:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
14867:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14868:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14869:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
14870:                                     $changes{$itemid} = 1;
14871:                                 }
14872:                             } else {
14873:                                 $changes{$itemid} = 1;
14874:                             }
14875:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14876:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
14877:                                 $changes{$itemid} = 1;
14878:                             }
14879:                         }
14880:                     }
14881:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
14882:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14883:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
14884:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14885:                     } else {
14886:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
14887:                     }
14888:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14889:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
14890:                             $changes{$itemid} = 1;
14891:                         }
14892:                     } else {
14893:                         $changes{$itemid} = 1;
14894:                     }
14895:                     foreach my $extra ('passback','roster') {
14896:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
14897:                             $confhash{$itemid}{$extra} = 1;
14898:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
14899:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
14900:                                 $lifetime =~ s/^\s+|\s+$//g;
14901:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
14902:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
14903:                                 }
14904:                             }
14905:                         }
14906:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
14907:                             $changes{$itemid} = 1;
14908:                         }
14909:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
14910:                             $changes{$itemid} = 1;
14911:                         }
14912:                     }
14913:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
14914:                     foreach my $item ('label','title','target','linktext','explanation','append') {
14915:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
14916:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
14917:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
14918:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
14919:                                     $changes{$itemid} = 1;
14920:                                 }
14921:                             } else {
14922:                                 $changes{$itemid} = 1;
14923:                             }
14924:                         }
14925:                     }
14926:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
14927:                     foreach my $field (@fields) {
14928:                         if ($possfield{$field}) {
14929:                             if ($field eq 'roles') {
14930:                                 foreach my $role (@courseroles) {
14931:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
14932:                                     if (($choice ne '') && ($posslti{$choice})) {
14933:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
14934:                                         if ($role eq 'cc') {
14935:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
14936:                                         }
14937:                                     }
14938:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
14939:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
14940:                                             $changes{$itemid} = 1;
14941:                                         }
14942:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
14943:                                         $changes{$itemid} = 1;
14944:                                     }
14945:                                 }
14946:                             } else {
14947:                                 $confhash{$itemid}{'fields'}{$field} = 1;
14948:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
14949:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
14950:                                         $changes{$itemid} = 1;
14951:                                     }
14952:                                 } else {
14953:                                     $changes{$itemid} = 1;
14954:                                 }
14955:                             }
14956:                         }
14957:                     }
14958:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
14959:                         if ($confhash{$itemid}{'fields'}{'user'}) {
14960:                             if ($env{'form.ltitools_userincdom_'.$i}) {
14961:                                 $confhash{$itemid}{'incdom'} = 1;
14962:                             }
14963:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
14964:                                 $changes{$itemid} = 1;
14965:                             }
14966:                         }
14967:                     }
14968:                     $allpos[$newpos] = $itemid;
14969:                 }
14970:                 if ($imgdeletions{$itemid}) {
14971:                     $changes{$itemid} = 1;
14972:                     #FIXME need to obsolete item in RES space
14973:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
14974:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
14975:                                                                  $itemid,$configuserok,$switchserver,
14976:                                                                  $author_ok);
14977:                     if ($imgurl) {
14978:                         $confhash{$itemid}{'image'} = $imgurl;
14979:                         $changes{$itemid} = 1;
14980:                     }
14981:                     if ($error) {
14982:                         &Apache::lonnet::logthis($error);
14983:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14984:                     }
14985:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
14986:                     $confhash{$itemid}{'image'} =
14987:                        $domconfig{$action}{$itemid}{'image'};
14988:                 }
14989:                 if ($customadds{$i}) {
14990:                     my $name = $env{'form.ltitools_custom_name_'.$i};
14991:                     $name =~ s/(`)/'/g;
14992:                     $name =~ s/^\s+//;
14993:                     $name =~ s/\s+$//;
14994:                     my $value = $env{'form.ltitools_custom_value_'.$i};
14995:                     $value =~ s/(`)/'/g;
14996:                     $value =~ s/^\s+//;
14997:                     $value =~ s/\s+$//;
14998:                     if ($name ne '') {
14999:                         $confhash{$itemid}{'custom'}{$name} = $value;
15000:                         $changes{$itemid} = 1;
15001:                     }
15002:                 }
15003:                 my %customdels;
15004:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
15005:                 if (@customdeletions) {
15006:                     $changes{$itemid} = 1;
15007:                 }
15008:                 map { $customdels{$_} = 1; } @customdeletions;
15009:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
15010:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
15011:                         unless ($customdels{$key}) {
15012:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
15013:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
15014:                             }
15015:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
15016:                                 $changes{$itemid} = 1;
15017:                             }
15018:                         }
15019:                     }
15020:                 }
15021:                 unless ($changes{$itemid}) {
15022:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
15023:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
15024:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
15025:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
15026:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
15027:                                         $changes{$itemid} = 1;
15028:                                         last;
15029:                                     }
15030:                                 }
15031:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
15032:                                 $changes{$itemid} = 1;
15033:                             }
15034:                         }
15035:                         last if ($changes{$itemid});
15036:                     }
15037:                 }
15038:             }
15039:         }
15040:     }
15041:     if (@allpos > 0) {
15042:         my $idx = 0;
15043:         foreach my $itemid (@allpos) {
15044:             if ($itemid ne '') {
15045:                 $confhash{$itemid}{'order'} = $idx;
15046:                 if (ref($domconfig{$action}) eq 'HASH') {
15047:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15048:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
15049:                             $changes{$itemid} = 1;
15050:                         }
15051:                     }
15052:                 }
15053:                 $idx ++;
15054:             }
15055:         }
15056:     }
15057:     my %ltitoolshash = (
15058:                           $action => { %confhash }
15059:                        );
15060:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
15061:                                              $dom);
15062:     if ($putresult eq 'ok') {
15063:         my %ltienchash = (
15064:                              $action => { %encconfig }
15065:                          );
15066:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
15067:         if (keys(%changes) > 0) {
15068:             my $cachetime = 24*60*60;
15069:             my %ltiall = %confhash;
15070:             foreach my $id (keys(%ltiall)) {
15071:                 if (ref($encconfig{$id}) eq 'HASH') {
15072:                     foreach my $item ('key','secret') {
15073:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
15074:                     }
15075:                 }
15076:             }
15077:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
15078:             if (ref($lastactref) eq 'HASH') {
15079:                 $lastactref->{'ltitools'} = 1;
15080:             }
15081:             $resulttext = &mt('Changes made:').'<ul>';
15082:             my %bynum;
15083:             foreach my $itemid (sort(keys(%changes))) {
15084:                 my $position = $confhash{$itemid}{'order'};
15085:                 $bynum{$position} = $itemid;
15086:             }
15087:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15088:                 my $itemid = $bynum{$pos}; 
15089:                 if (ref($confhash{$itemid}) ne 'HASH') {
15090:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
15091:                 } else {
15092:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
15093:                     if ($confhash{$itemid}{'image'}) {
15094:                         $resulttext .= '&nbsp;'.
15095:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
15096:                                        ' alt="'.&mt('Tool Provider icon').'" />';
15097:                     }
15098:                     $resulttext .= '</li><ul>';
15099:                     my $position = $pos + 1;
15100:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15101:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
15102:                         if ($confhash{$itemid}{$item} ne '') {
15103:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15104:                         }
15105:                     }
15106:                     if ($encconfig{$itemid}{'key'} ne '') {
15107:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
15108:                     }
15109:                     if ($encconfig{$itemid}{'secret'} ne '') {
15110:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15111:                         my $num = length($encconfig{$itemid}{'secret'});
15112:                         $resulttext .= ('*'x$num).'</li>';
15113:                     }
15114:                     $resulttext .= '<li>'.&mt('Configurable in course:');
15115:                     my @possconfig = ('label','title','target','linktext','explanation','append');
15116:                     my $numconfig = 0; 
15117:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
15118:                         foreach my $item (@possconfig) {
15119:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
15120:                                 $numconfig ++;
15121:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
15122:                             }
15123:                         }
15124:                     }
15125:                     if (!$numconfig) {
15126:                         $resulttext .= '&nbsp;'.&mt('None');
15127:                     }
15128:                     $resulttext .= '</li>';
15129:                     foreach my $item ('passback','roster') {
15130:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
15131:                         if ($confhash{$itemid}{$item}) {
15132:                             $resulttext .= &mt('Yes');
15133:                             if ($confhash{$itemid}{$item.'valid'}) {
15134:                                 if ($item eq 'passback') {
15135:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
15136:                                                            $confhash{$itemid}{$item.'valid'});
15137:                                 } else {
15138:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
15139:                                                            $confhash{$itemid}{$item.'valid'});
15140:                                 }
15141:                             }
15142:                         } else {
15143:                             $resulttext .= &mt('No');
15144:                         }
15145:                         $resulttext .= '</li>';
15146:                     }
15147:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
15148:                         my $displaylist;
15149:                         if ($confhash{$itemid}{'display'}{'target'}) {
15150:                             $displaylist = &mt('Display target').':&nbsp;'.
15151:                                            $confhash{$itemid}{'display'}{'target'}.',';
15152:                         }
15153:                         foreach my $size ('width','height') { 
15154:                             if ($confhash{$itemid}{'display'}{$size}) {
15155:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
15156:                                                 $confhash{$itemid}{'display'}{$size}.',';
15157:                             }
15158:                         }
15159:                         if ($displaylist) {
15160:                             $displaylist =~ s/,$//;
15161:                             $resulttext .= '<li>'.$displaylist.'</li>';
15162:                         }
15163:                         foreach my $item ('linktext','explanation') {
15164:                             if ($confhash{$itemid}{'display'}{$item}) {
15165:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
15166:                             }
15167:                         }
15168:                     }
15169:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
15170:                         my $fieldlist;
15171:                         foreach my $field (@allfields) {
15172:                             if ($confhash{$itemid}{'fields'}{$field}) {
15173:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
15174:                             }
15175:                         }
15176:                         if ($fieldlist) {
15177:                             $fieldlist =~ s/,$//;
15178:                             if ($confhash{$itemid}{'fields'}{'user'}) {
15179:                                 if ($confhash{$itemid}{'incdom'}) {
15180:                                     $fieldlist .= ' ('.&mt('username:domain').')';
15181:                                 } else {
15182:                                     $fieldlist .= ' ('.&mt('username').')';
15183:                                 }
15184:                             }
15185:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
15186:                         }
15187:                     }
15188:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
15189:                         my $rolemaps;
15190:                         foreach my $role (@courseroles) {
15191:                             if ($confhash{$itemid}{'roles'}{$role}) {
15192:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15193:                                              $confhash{$itemid}{'roles'}{$role}.',';
15194:                             }
15195:                         }
15196:                         if ($rolemaps) {
15197:                             $rolemaps =~ s/,$//; 
15198:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15199:                         }
15200:                     }
15201:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
15202:                         my $customlist;
15203:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
15204:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
15205:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
15206:                             } 
15207:                         }
15208:                         if ($customlist) {
15209:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15210:                         }
15211:                     } 
15212:                     $resulttext .= '</ul></li>';
15213:                 }
15214:             }
15215:             $resulttext .= '</ul>';
15216:         } else {
15217:             $resulttext = &mt('No changes made.');
15218:         }
15219:     } else {
15220:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15221:     }
15222:     if ($errors) {
15223:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15224:                        $errors.'</ul>';
15225:     }
15226:     return $resulttext;
15227: }
15228: 
15229: sub process_ltitools_image {
15230:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
15231:     my $filename = $env{'form.'.$caller.'.filename'};
15232:     my ($error,$url);
15233:     my ($width,$height) = (21,21);
15234:     if ($configuserok eq 'ok') {
15235:         if ($switchserver) {
15236:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
15237:                          $switchserver);
15238:         } elsif ($author_ok eq 'ok') {
15239:             my ($result,$imageurl,$madethumb) =
15240:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15241:                              "ltitools/$itemid/icon",$width,$height);
15242:             if ($result eq 'ok') {
15243:                 if ($madethumb) {
15244:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15245:                     my $imagethumb = "$path/tn-".$imagefile;
15246:                     $url = $imagethumb;
15247:                 } else {
15248:                     $url = $imageurl;
15249:                 }
15250:             } else {
15251:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15252:             }
15253:         } else {
15254:             $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);
15255:         }
15256:     } else {
15257:         $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);
15258:     }
15259:     return ($url,$error);
15260: }
15261: 
15262: sub get_ltitools_id {
15263:     my ($cdom,$title) = @_;
15264:     # get lock on ltitools db
15265:     my $lockhash = {
15266:                       lock => $env{'user.name'}.
15267:                               ':'.$env{'user.domain'},
15268:                    };
15269:     my $tries = 0;
15270:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15271:     my ($id,$error);
15272:  
15273:     while (($gotlock ne 'ok') && ($tries<10)) {
15274:         $tries ++;
15275:         sleep (0.1);
15276:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15277:     }
15278:     if ($gotlock eq 'ok') {
15279:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
15280:         if ($currids{'lock'}) {
15281:             delete($currids{'lock'});
15282:             if (keys(%currids)) {
15283:                 my @curr = sort { $a <=> $b } keys(%currids);
15284:                 if ($curr[-1] =~ /^\d+$/) {
15285:                     $id = 1 + $curr[-1];
15286:                 }
15287:             } else {
15288:                 $id = 1;
15289:             }
15290:             if ($id) {
15291:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
15292:                     $error = 'nostore';
15293:                 }
15294:             } else {
15295:                 $error = 'nonumber';
15296:             }
15297:         }
15298:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
15299:     } else {
15300:         $error = 'nolock';
15301:     }
15302:     return ($id,$error);
15303: }
15304: 
15305: sub modify_proctoring {
15306:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15307:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15308:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
15309:     my $confname = $dom.'-domainconfig';
15310:     my $servadm = $r->dir_config('lonAdmEMail');
15311:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
15312:     my %providernames = &proctoring_providernames();
15313:     my $maxnum = scalar(keys(%providernames));
15314: 
15315:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
15316:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
15317:     if (ref($requref) eq 'HASH') {
15318:         %requserfields = %{$requref};
15319:     }
15320:     if (ref($opturef) eq 'HASH') {
15321:         %optuserfields = %{$opturef};
15322:     }
15323:     if (ref($defref) eq 'HASH') {
15324:         %defaults = %{$defref};
15325:     }
15326:     if (ref($extref) eq 'HASH') {
15327:         %extended = %{$extref};
15328:     }
15329:     if (ref($crsref) eq 'HASH') {
15330:         %crsconf = %{$crsref};
15331:     }
15332:     if (ref($rolesref) eq 'ARRAY') {
15333:         @courseroles = @{$rolesref};
15334:     }
15335:     if (ref($ltiref) eq 'ARRAY') {
15336:         @ltiroles = @{$ltiref};
15337:     }
15338: 
15339:     if (ref($domconfig{$action}) eq 'HASH') {
15340:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
15341:         if (@todeleteimages) {
15342:             map { $imgdeletions{$_} = 1; } @todeleteimages;
15343:         }
15344:     }
15345:     my %customadds;
15346:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
15347:     if (@newcustom) {
15348:         map { $customadds{$_} = 1; } @newcustom;
15349:     }
15350:     foreach my $provider (sort(keys(%providernames))) {
15351:         $confhash{$provider} = {};
15352:         my $pos = $env{'form.proctoring_pos_'.$provider};
15353:         $pos =~ s/\D+//g;
15354:         $allpos[$pos] = $provider;
15355:         my (%current,%currentenc);
15356:         my $showroles = 0;
15357:         if (ref($domconfig{$action}) eq 'HASH') {
15358:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15359:                 %current = %{$domconfig{$action}{$provider}};
15360:                 foreach my $item ('key','secret') { 
15361:                     $currentenc{$item} = $current{$item};
15362:                     delete($current{$item});
15363:                 }
15364:             }
15365:         }
15366:         if ($env{'form.proctoring_available_'.$provider}) {
15367:             $confhash{$provider}{'available'} = 1;
15368:             unless ($current{'available'}) {
15369:                 $changes{$provider} = 1;
15370:             }
15371:         } else {
15372:             %{$confhash{$provider}} = %current;
15373:             %{$encconfhash{$provider}} = %currentenc;
15374:             $confhash{$provider}{'available'} = 0;
15375:             if ($current{'available'}) {
15376:                 $changes{$provider} = 1;
15377:             }
15378:         }
15379:         if ($confhash{$provider}{'available'}) {
15380:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
15381:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
15382:                 if ($field eq 'lifetime') {
15383:                     if ($possval =~ /^\d+$/) {
15384:                         $confhash{$provider}{$field} = $possval;
15385:                     }
15386:                 } elsif ($field eq 'version') {
15387:                     if ($possval =~ /^\d+\.\d+$/) {
15388:                         $confhash{$provider}{$field} = $possval;
15389:                     }
15390:                 } elsif ($field eq 'sigmethod') {
15391:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
15392:                         $confhash{$provider}{$field} = $possval;
15393:                     }
15394:                 } elsif ($field eq 'url') {
15395:                     $confhash{$provider}{$field} = $possval;
15396:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
15397:                     $encconfhash{$provider}{$field} = $possval;
15398:                     unless ($currentenc{$field} eq $possval) {
15399:                         $changes{$provider} = 1;
15400:                     }
15401:                 }
15402:                 unless (($field eq 'key') || ($field eq 'secret')) {
15403:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
15404:                         $changes{$provider} = 1;
15405:                     }
15406:                 }
15407:             }
15408:             if ($imgdeletions{$provider}) {
15409:                 $changes{$provider} = 1;
15410:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
15411:                 my ($imageurl,$error) =
15412:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
15413:                                               $configuserok,$switchserver,$author_ok);
15414:                 if ($imageurl) {
15415:                     $confhash{$provider}{'image'} = $imageurl;
15416:                     $changes{$provider} = 1; 
15417:                 }
15418:                 if ($error) {
15419:                     &Apache::lonnet::logthis($error);
15420:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15421:                 }
15422:             } elsif (exists($current{'image'})) {
15423:                 $confhash{$provider}{'image'} = $current{'image'};
15424:             }
15425:             if (ref($requserfields{$provider}) eq 'ARRAY') {
15426:                 if (@{$requserfields{$provider}} > 0) {
15427:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
15428:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
15429:                             $confhash{$provider}{'incdom'} = 1;
15430:                         }
15431:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
15432:                             $changes{$provider} = 1;
15433:                         }
15434:                     }
15435:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
15436:                         $showroles = 1;
15437:                     }
15438:                 }
15439:             }
15440:             $confhash{$provider}{'fields'} = [];
15441:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
15442:                 if (@{$optuserfields{$provider}} > 0) {
15443:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
15444:                     foreach my $field (@{$optuserfields{$provider}}) {
15445:                         if (grep(/^\Q$field\E$/,@optfields)) {
15446:                             push(@{$confhash{$provider}{'fields'}},$field);
15447:                         }
15448:                     }
15449:                 }
15450:                 if (ref($current{'fields'}) eq 'ARRAY') {
15451:                     unless ($changes{$provider}) {
15452:                         my @new = sort(@{$confhash{$provider}{'fields'}});
15453:                         my @old = sort(@{$current{'fields'}}); 
15454:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15455:                         if (@diffs) {
15456:                             $changes{$provider} = 1;
15457:                         }
15458:                     }
15459:                 } elsif (@{$confhash{$provider}{'fields'}}) {
15460:                     $changes{$provider} = 1;
15461:                 }
15462:             }
15463:             if (ref($defaults{$provider}) eq 'ARRAY') {  
15464:                 if (@{$defaults{$provider}} > 0) {
15465:                     my %options;
15466:                     if (ref($extended{$provider}) eq 'HASH') {
15467:                         %options = %{$extended{$provider}};
15468:                     }
15469:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
15470:                     foreach my $field (@{$defaults{$provider}}) {
15471:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
15472:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
15473:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
15474:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
15475:                             }
15476:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
15477:                             foreach my $inner (keys(%{$options{$field}})) {
15478:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
15479:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
15480:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
15481:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
15482:                                     }
15483:                                 } else {
15484:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
15485:                                 }
15486:                             }
15487:                         } else {
15488:                             if (grep(/^\Q$field\E$/,@checked)) {
15489:                                 push(@{$confhash{$provider}{'defaults'}},$field);
15490:                             }
15491:                         }
15492:                     }
15493:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15494:                         if (ref($current{'defaults'}) eq 'ARRAY') {
15495:                             unless ($changes{$provider}) {
15496:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
15497:                                 my @old = sort(@{$current{'defaults'}});
15498:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15499:                                 if (@diffs) {
15500:                                     $changes{$provider} = 1; 
15501:                                 }
15502:                             }
15503:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
15504:                             if (@{$current{'defaults'}}) {
15505:                                 $changes{$provider} = 1;
15506:                             }
15507:                         }
15508:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15509:                         if (ref($current{'defaults'}) eq 'HASH') {
15510:                             unless ($changes{$provider}) {
15511:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
15512:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
15513:                                         $changes{$provider} = 1;
15514:                                         last;
15515:                                     }
15516:                                 }
15517:                             }
15518:                             unless ($changes{$provider}) {
15519:                                 foreach my $key (keys(%{$current{'defaults'}})) {
15520:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
15521:                                         $changes{$provider} = 1;
15522:                                         last;
15523:                                     }
15524:                                 }
15525:                             }
15526:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
15527:                             $changes{$provider} = 1;
15528:                         }
15529:                     }
15530:                 }
15531:             }
15532:             if (ref($crsconf{$provider}) eq 'ARRAY') {
15533:                 if (@{$crsconf{$provider}} > 0) {
15534:                     $confhash{$provider}{'crsconf'} = [];
15535:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
15536:                     foreach my $crsfield (@{$crsconf{$provider}}) {
15537:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
15538:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
15539:                         }
15540:                     }
15541:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
15542:                         unless ($changes{$provider}) {  
15543:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
15544:                             my @old = sort(@{$current{'crsconf'}});
15545:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15546:                             if (@diffs) {
15547:                                 $changes{$provider} = 1;
15548:                             }
15549:                         }
15550:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
15551:                         $changes{$provider} = 1;
15552:                     }
15553:                 }
15554:             }
15555:             if ($showroles) {
15556:                 $confhash{$provider}{'roles'} = {};
15557:                 foreach my $role (@courseroles) {
15558:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
15559:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
15560:                         $confhash{$provider}{'roles'}{$role} = $poss;
15561:                     }
15562:                 }
15563:                 unless ($changes{$provider}) {
15564:                     if (ref($current{'roles'}) eq 'HASH') {
15565:                         foreach my $role (keys(%{$current{'roles'}})) {
15566:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
15567:                                 $changes{$provider} = 1;
15568:                                 last
15569:                             }
15570:                         }
15571:                         unless ($changes{$provider}) {
15572:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
15573:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
15574:                                     $changes{$provider} = 1;
15575:                                     last;
15576:                                 }
15577:                             }
15578:                         }
15579:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
15580:                         $changes{$provider} = 1;
15581:                     }
15582:                 }
15583:             }
15584:             if (ref($current{'custom'}) eq 'HASH') {
15585:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
15586:                 foreach my $key (keys(%{$current{'custom'}})) {
15587:                     if (grep(/^\Q$key\E$/,@customdels)) {
15588:                         $changes{$provider} = 1;
15589:                     } else {
15590:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
15591:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
15592:                             $changes{$provider} = 1;
15593:                         }
15594:                     }
15595:                 }
15596:             }
15597:             if ($customadds{$provider}) {
15598:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
15599:                 $name =~ s/(`)/'/g;
15600:                 $name =~ s/^\s+//;
15601:                 $name =~ s/\s+$//;
15602:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
15603:                 $value =~ s/(`)/'/g;
15604:                 $value =~ s/^\s+//;
15605:                 $value =~ s/\s+$//;
15606:                 if ($name ne '') {
15607:                     $confhash{$provider}{'custom'}{$name} = $value;
15608:                     $changes{$provider} = 1;
15609:                 }
15610:             }
15611:         }
15612:     }
15613:     if (@allpos > 0) {
15614:         my $idx = 0;
15615:         foreach my $provider (@allpos) {
15616:             if ($provider ne '') {
15617:                 $confhash{$provider}{'order'} = $idx;
15618:                 unless ($changes{$provider}) {
15619:                     if (ref($domconfig{$action}) eq 'HASH') {
15620:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15621:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
15622:                                 $changes{$provider} = 1;
15623:                             }
15624:                         }
15625:                     }
15626:                 }
15627:                 $idx ++;
15628:             }
15629:         }
15630:     }
15631:     my %proc_hash = (
15632:                           $action => { %confhash }
15633:                        );
15634:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
15635:                                              $dom);
15636:     if ($putresult eq 'ok') {
15637:         my %proc_enchash = (
15638:                              $action => { %encconfhash }
15639:                          );
15640:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
15641:         if (keys(%changes) > 0) {
15642:             my $cachetime = 24*60*60;
15643:             my %procall = %confhash;
15644:             foreach my $provider (keys(%procall)) {
15645:                 if (ref($encconfhash{$provider}) eq 'HASH') {
15646:                     foreach my $key ('key','secret') {
15647:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
15648:                     }
15649:                 }
15650:             }
15651:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
15652:             if (ref($lastactref) eq 'HASH') {
15653:                 $lastactref->{'proctoring'} = 1;
15654:             }
15655:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
15656:             my %bynum;
15657:             foreach my $provider (sort(keys(%changes))) {
15658:                 my $position = $confhash{$provider}{'order'};
15659:                 $bynum{$position} = $provider;
15660:             }
15661:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15662:                 my $provider = $bynum{$pos};
15663:                 my %lt = &proctoring_titles($provider);
15664:                 my %fieldtitles = &proctoring_fieldtitles($provider);
15665:                 if (!$confhash{$provider}{'available'}) {
15666:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
15667:                 } else {
15668:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
15669:                     if ($confhash{$provider}{'image'}) {
15670:                         $resulttext .= '&nbsp;'.
15671:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
15672:                                        ' alt="'.&mt('Proctoring icon').'" />';
15673:                     }
15674:                     $resulttext .= '<ul>';
15675:                     my $position = $pos + 1;
15676:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15677:                     foreach my $key ('version','sigmethod','url','lifetime') {
15678:                         if ($confhash{$provider}{$key} ne '') {
15679:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
15680:                         }
15681:                     }
15682:                     if ($encconfhash{$provider}{'key'} ne '') {
15683:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
15684:                     }
15685:                     if ($encconfhash{$provider}{'secret'} ne '') {
15686:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15687:                         my $num = length($encconfhash{$provider}{'secret'});
15688:                         $resulttext .= ('*'x$num).'</li>';
15689:                     }
15690:                     my (@fields,$showroles);
15691:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15692:                         push(@fields,@{$requserfields{$provider}});
15693:                     }
15694:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
15695:                         push(@fields,@{$confhash{$provider}{'fields'}});
15696:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
15697:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
15698:                     }
15699:                     if (@fields) {
15700:                         if (grep(/^roles$/,@fields)) {
15701:                             $showroles = 1;
15702:                         }
15703:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
15704:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
15705:                     }
15706:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15707:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
15708:                             if ($confhash{$provider}{'incdom'}) {
15709:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
15710:                             } else { 
15711:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
15712:                             }
15713:                         }
15714:                     }
15715:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15716:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
15717:                             $resulttext .= '<li>'.$lt{'defa'};
15718:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
15719:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
15720:                             }
15721:                             $resulttext =~ s/,$//;
15722:                             $resulttext .= '</li>';
15723:                         }
15724:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15725:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
15726:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
15727:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
15728:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
15729:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
15730:                                 }
15731:                             }
15732:                             $resulttext .= '</ul></li>';
15733:                         }
15734:                     }
15735:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
15736:                         if (@{$crsconf{$provider}} > 0) {
15737:                             $resulttext .= '<li>'.&mt('Configurable in course:');
15738:                             my $numconfig = 0;
15739:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
15740:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
15741:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
15742:                                         $numconfig ++;
15743:                                         if ($provider eq 'examity') {
15744:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
15745:                                         } else {
15746:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
15747:                                         }
15748:                                     }
15749:                                     $resulttext =~ s/,$//;
15750:                                 }
15751:                             }
15752:                             if (!$numconfig) {
15753:                                 $resulttext .= '&nbsp;'.&mt('None');
15754:                             }
15755:                             $resulttext .= '</li>';
15756:                         }
15757:                     }
15758:                     if ($showroles) {
15759:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
15760:                             my $rolemaps;
15761:                             foreach my $role (@courseroles) {
15762:                                 if ($confhash{$provider}{'roles'}{$role}) {
15763:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15764:                                                  $confhash{$provider}{'roles'}{$role}.',';
15765:                                 }
15766:                             }
15767:                             if ($rolemaps) {
15768:                                 $rolemaps =~ s/,$//;
15769:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15770:                             }
15771:                         }
15772:                     }
15773:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
15774:                         my $customlist;
15775:                         if (keys(%{$confhash{$provider}{'custom'}})) {
15776:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
15777:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
15778:                             }
15779:                             $customlist =~ s/,$//;
15780:                         }
15781:                         if ($customlist) {
15782:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15783:                         }
15784:                     } 
15785:                     $resulttext .= '</ul></li>';
15786:                 }
15787:             }
15788:             $resulttext .= '</ul>';
15789:         } else {
15790:             $resulttext = &mt('No changes made.');
15791:         }
15792:     } else {
15793:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15794:     }
15795:     if ($errors) {
15796:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15797:                        $errors.'</ul>';
15798:     }
15799:     return $resulttext;
15800: }
15801: 
15802: sub process_proctoring_image {
15803:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
15804:     my $filename = $env{'form.'.$caller.'.filename'};
15805:     my ($error,$url);
15806:     my ($width,$height) = (21,21);
15807:     if ($configuserok eq 'ok') {
15808:         if ($switchserver) {
15809:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
15810:                          $switchserver);
15811:         } elsif ($author_ok eq 'ok') {
15812:             my ($result,$imageurl,$madethumb) =
15813:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15814:                              "proctoring/$provider/icon",$width,$height);
15815:             if ($result eq 'ok') {
15816:                 if ($madethumb) {
15817:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15818:                     my $imagethumb = "$path/tn-".$imagefile;
15819:                     $url = $imagethumb;
15820:                 } else {
15821:                     $url = $imageurl;
15822:                 }
15823:             } else {
15824:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15825:             }
15826:         } else {
15827:             $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);
15828:         }
15829:     } else {
15830:         $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);
15831:     }
15832:     return ($url,$error);
15833: }
15834: 
15835: sub modify_lti {
15836:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15837:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15838:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
15839:     my (%posslti,%posslticrs,%posscrstype);
15840:     my @courseroles = ('cc','in','ta','ep','st');
15841:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
15842:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
15843:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
15844:     my %coursetypetitles = &Apache::lonlocal::texthash (
15845:                                official   => 'Official',
15846:                                unofficial => 'Unofficial',
15847:                                community  => 'Community',
15848:                                textbook   => 'Textbook',
15849:                                placement  => 'Placement Test',
15850:                                lti        => 'LTI Provider',
15851:     );
15852:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15853:     my %lt = &lti_names();
15854:     map { $posslti{$_} = 1; } @ltiroles;
15855:     map { $posslticrs{$_} = 1; } @lticourseroles;
15856:     map { $posscrstype{$_} = 1; } @coursetypes;
15857: 
15858:     my %menutitles = &ltimenu_titles();
15859: 
15860:     my (%currltisec,%secchanges,%newltisec,%newltienc,%keyset,%newkeyset);
15861:     $newltisec{'private'}{'keys'} = [];
15862:     $newltisec{'encrypt'} = {};
15863:     $newltisec{'rules'} = {};
15864:     $newltisec{'linkprot'} = {};
15865:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
15866:         %currltisec = %{$domconfig{'ltisec'}};
15867:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15868:             foreach my $id (keys(%{$currltisec{'linkprot'}})) {
15869:                 unless ($id =~ /^\d+$/) {
15870:                     delete($currltisec{'linkprot'}{$id});
15871:                 }
15872:             }
15873:         }
15874:         if (ref($currltisec{'private'}) eq 'HASH') {
15875:             if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
15876:                 $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
15877:                 map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
15878:             }
15879:         }
15880:     }
15881:     foreach my $item ('crs','dom','consumers') {
15882:         my $formelement;
15883:         if ($item eq 'consumers') { 
15884:             $formelement = 'form.ltisec_'.$item;
15885:         } else {
15886:             $formelement = 'form.ltisec_'.$item.'linkprot';
15887:         }
15888:         if ($env{$formelement}) {
15889:             $newltisec{'encrypt'}{$item} = 1;
15890:             if (ref($currltisec{'encrypt'}) eq 'HASH') {
15891:                 unless ($currltisec{'encrypt'}{$item}) {
15892:                     $secchanges{'encrypt'} = 1;
15893:                 }
15894:             } else {
15895:                 $secchanges{'encrypt'} = 1;
15896:             }
15897:         } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
15898:             if ($currltisec{'encrypt'}{$item}) {
15899:                 $secchanges{'encrypt'} = 1;
15900:             }
15901:         }
15902:     }
15903:     unless (exists($currltisec{'rules'})) {
15904:         $currltisec{'rules'} = {};
15905:     }
15906:     &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
15907: 
15908:     my @ids=&Apache::lonnet::current_machine_ids();
15909:     my %servers = &Apache::lonnet::get_servers($dom,'library');
15910:    
15911:     foreach my $hostid (keys(%servers)) {
15912:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
15913:             my $newkey;
15914:             my $keyitem = 'form.ltisec_privkey_'.$hostid;
15915:             if (exists($env{$keyitem})) {
15916:                 $env{$keyitem} =~ s/(`)/'/g;
15917:                 if ($keyset{$hostid}) {
15918:                     if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
15919:                         if ($env{$keyitem} ne '') {
15920:                             $secchanges{'private'} = 1;
15921:                             $newkeyset{$hostid} = $env{$keyitem};
15922:                         }
15923:                     }
15924:                 } elsif ($env{$keyitem} ne '') {
15925:                     unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) { 
15926:                         push(@{$newltisec{'private'}{'keys'}},$hostid);
15927:                     }
15928:                     $secchanges{'private'} = 1;
15929:                     $newkeyset{$hostid} = $env{$keyitem};
15930:                 }
15931:             }
15932:         }
15933:     }
15934: 
15935:     my (%linkprotchg,$linkprotoutput,$is_home);
15936:     my $proterror = &Apache::courseprefs::process_linkprot($dom,'',$currltisec{'linkprot'},
15937:                                                            \%linkprotchg,'domain');
15938:     my $home = &Apache::lonnet::domain($dom,'primary');
15939:     unless (($home eq 'no_host') || ($home eq '')) {
15940:         my @ids=&Apache::lonnet::current_machine_ids();
15941:         foreach my $id (@ids) { if ($id eq $home) { $is_home=1; } }
15942:     }
15943: 
15944:     if (keys(%linkprotchg)) {
15945:         $secchanges{'linkprot'} = 1;
15946:         my %oldlinkprot;
15947:         if (ref($currltisec{'linkprot'}) eq 'HASH') {
15948:             %oldlinkprot = %{$currltisec{'linkprot'}};
15949:         }
15950:         foreach my $id (keys(%linkprotchg)) {
15951:             if (ref($linkprotchg{$id}) eq 'HASH') {
15952:                 foreach my $inner (keys(%{$linkprotchg{$id}})) {
15953:                     if (($inner eq 'secret') || ($inner eq 'key')) {
15954:                         if ($is_home) {
15955:                             $newltienc{$id}{$inner} = $linkprotchg{$id}{$inner};
15956:                         }
15957:                     }
15958:                 }
15959:             } else {
15960:                 $newltisec{'linkprot'}{$id} = $linkprotchg{$id};
15961:             }
15962:         }
15963:         $linkprotoutput = &Apache::courseprefs::store_linkprot($dom,'','domain',\%linkprotchg,\%oldlinkprot);
15964:         if (keys(%linkprotchg)) {
15965:             %{$newltisec{'linkprot'}} = %linkprotchg;
15966:         }
15967:     }
15968:     if (ref($currltisec{'linkprot'}) eq 'HASH') {
15969:         foreach my $id (%{$currltisec{'linkprot'}}) {
15970:             next if ($id !~ /^\d+$/);
15971:             unless (exists($linkprotchg{$id})) {
15972:                 if (ref($currltisec{'linkprot'}{$id}) eq 'HASH') {
15973:                     foreach my $inner (keys(%{$currltisec{'linkprot'}{$id}})) {
15974:                         if (($inner eq 'secret') || ($inner eq 'key')) {
15975:                             if ($is_home) {
15976:                                 $newltienc{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
15977:                             }
15978:                         } else {
15979:                             $newltisec{'linkprot'}{$id}{$inner} = $currltisec{'linkprot'}{$id}{$inner};
15980:                         }
15981:                     }
15982:                 } else {
15983:                     $newltisec{'linkprot'}{$id} = $currltisec{'linkprot'}{$id};
15984:                 }
15985:             }
15986:         }
15987:     }
15988:     if ($proterror) {
15989:         $errors .= '<li>'.$proterror.'</li>';
15990:     }
15991:     my (@items,%deletions,%itemids);
15992:     if ($env{'form.lti_add'}) {
15993:         my $consumer = $env{'form.lti_consumer_add'};
15994:         $consumer =~ s/(`)/'/g;
15995:         ($newid,my $error) = &get_lti_id($dom,$consumer);
15996:         if ($newid) {
15997:             $itemids{'add'} = $newid;
15998:             push(@items,'add');
15999:             $changes{$newid} = 1;
16000:         } else {
16001:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
16002:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
16003:         }
16004:     }
16005:     if (ref($domconfig{$action}) eq 'HASH') {
16006:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
16007:         if (@todelete) {
16008:             map { $deletions{$_} = 1; } @todelete;
16009:         }
16010:         my $maxnum = $env{'form.lti_maxnum'};
16011:         for (my $i=0; $i<$maxnum; $i++) {
16012:             my $itemid = $env{'form.lti_id_'.$i};
16013:             $itemid =~ s/\D+//g;
16014:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16015:                 if ($deletions{$itemid}) {
16016:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
16017:                 } else {
16018:                     push(@items,$i);
16019:                     $itemids{$i} = $itemid;
16020:                 }
16021:             }
16022:         }
16023:     }
16024:     foreach my $idx (@items) {
16025:         my $itemid = $itemids{$idx};
16026:         next unless ($itemid);
16027:         my $position = $env{'form.lti_pos_'.$itemid};
16028:         $position =~ s/\D+//g;
16029:         if ($position ne '') {
16030:             $allpos[$position] = $itemid;
16031:         }
16032:         foreach my $item ('consumer','key','secret','lifetime','requser','crsinc') {
16033:             my $formitem = 'form.lti_'.$item.'_'.$idx;
16034:             $env{$formitem} =~ s/(`)/'/g;
16035:             if ($item eq 'lifetime') {
16036:                 $env{$formitem} =~ s/[^\d.]//g;
16037:             }
16038:             if ($env{$formitem} ne '') {
16039:                 if (($item eq 'key') || ($item eq 'secret')) {
16040:                     $encconfig{$itemid}{$item} = $env{$formitem};
16041:                 } else {
16042:                     $confhash{$itemid}{$item} = $env{$formitem};
16043:                     unless (($idx eq 'add') || ($changes{$itemid})) {
16044:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
16045:                             $changes{$itemid} = 1;
16046:                         }
16047:                     }
16048:                 }
16049:             }
16050:         }
16051:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
16052:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
16053:         }
16054:         if ($confhash{$itemid}{'requser'}) {
16055:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
16056:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid';
16057:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
16058:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
16059:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
16060:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
16061:                 $mapuser =~ s/(`)/'/g;
16062:                 $mapuser =~ s/^\s+|\s+$//g;
16063:                 $confhash{$itemid}{'mapuser'} = $mapuser;
16064:             }
16065:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
16066:             my @makeuser;
16067:             foreach my $ltirole (sort(@possmakeuser)) {
16068:                 if ($posslti{$ltirole}) {
16069:                     push(@makeuser,$ltirole);
16070:                 }
16071:             }
16072:             $confhash{$itemid}{'makeuser'} = \@makeuser;
16073:             if (@makeuser) {
16074:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
16075:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
16076:                     $confhash{$itemid}{'lcauth'} = $lcauth;
16077:                     if ($lcauth ne 'internal') {
16078:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
16079:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
16080:                         $lcauthparm =~ s/`//g;
16081:                         if ($lcauthparm ne '') {
16082:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
16083:                         }
16084:                     }
16085:                 } else {
16086:                     $confhash{$itemid}{'lcauth'} = 'lti';
16087:                 }
16088:             }
16089:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
16090:             if (@possinstdata) {
16091:                 foreach my $field (@possinstdata) {
16092:                     if (exists($fieldtitles{$field})) {
16093:                         push(@{$confhash{$itemid}{'instdata'}});
16094:                     }
16095:                 }
16096:             }
16097:             if ($env{'form.lti_callback_'.$idx}) {
16098:                 if ($env{'form.lti_callbackparam_'.$idx}) {
16099:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
16100:                     $callback =~ s/^\s+|\s+$//g;
16101:                     $confhash{$itemid}{'callback'} = $callback;
16102:                 }
16103:             }
16104:             foreach my $field ('topmenu','inlinemenu') {
16105:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
16106:                     $confhash{$itemid}{$field} = 1;
16107:                 }
16108:             }
16109:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
16110:                 $confhash{$itemid}{lcmenu} = [];
16111:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
16112:                 foreach my $field (@possmenu) {
16113:                     if (exists($menutitles{$field})) {
16114:                         if ($field eq 'grades') {
16115:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
16116:                         }
16117:                         push(@{$confhash{$itemid}{lcmenu}},$field);
16118:                     }
16119:                 }
16120:             }
16121:             if ($confhash{$itemid}{'crsinc'}) {
16122:                 if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
16123:                     ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
16124:                     $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
16125:                 } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
16126:                     my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
16127:                     $mapcrs =~ s/(`)/'/g;
16128:                     $mapcrs =~ s/^\s+|\s+$//g;
16129:                     $confhash{$itemid}{'mapcrs'} = $mapcrs;
16130:                 }
16131:                 my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
16132:                 my @crstypes;
16133:                 foreach my $type (sort(@posstypes)) {
16134:                     if ($posscrstype{$type}) {
16135:                         push(@crstypes,$type);
16136:                     }
16137:                 }
16138:                 $confhash{$itemid}{'mapcrstype'} = \@crstypes;
16139:                 if ($env{'form.lti_storecrs_'.$idx}) {
16140:                     $confhash{$itemid}{'storecrs'} = 1;
16141:                 }       
16142:                 if ($env{'form.lti_makecrs_'.$idx}) {
16143:                     $confhash{$itemid}{'makecrs'} = 1;
16144:                 }
16145:                 foreach my $ltirole (@lticourseroles) {
16146:                     my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
16147:                     if (grep(/^\Q$possrole\E$/,@courseroles)) {
16148:                         $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
16149:                     }
16150:                 }
16151:                 my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
16152:                 my @selfenroll;
16153:                 foreach my $type (sort(@possenroll)) {
16154:                     if ($posslticrs{$type}) {
16155:                         push(@selfenroll,$type);
16156:                     }
16157:                 }
16158:                 $confhash{$itemid}{'selfenroll'} = \@selfenroll;
16159:                 if ($env{'form.lti_crssec_'.$idx}) {
16160:                     if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
16161:                         $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
16162:                     } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
16163:                         my $section = $env{'form.lti_customsection_'.$idx};
16164:                         $section =~ s/(`)/'/g;
16165:                         $section =~ s/^\s+|\s+$//g;
16166:                         if ($section ne '') {
16167:                             $confhash{$itemid}{'section'} = $section;
16168:                         }
16169:                     }
16170:                 }
16171:                 foreach my $field ('passback','roster') {
16172:                     if ($env{'form.lti_'.$field.'_'.$idx}) {
16173:                         $confhash{$itemid}{$field} = 1;
16174:                     }
16175:                 }
16176:                 if ($env{'form.lti_passback_'.$idx}) {
16177:                     if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
16178:                         $confhash{$itemid}{'passbackformat'} = '1.0';
16179:                     } else {
16180:                         $confhash{$itemid}{'passbackformat'} = '1.1';
16181:                     }
16182:                 }
16183:             }
16184:             unless (($idx eq 'add') || ($changes{$itemid})) {
16185:                 if ($confhash{$itemid}{'crsinc'}) {
16186:                     foreach my $field ('mapcrs','storecrs','makecrs','section','passback','roster') {
16187:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16188:                             $changes{$itemid} = 1;
16189:                         }
16190:                     }
16191:                     unless ($changes{$itemid}) {
16192:                         if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
16193:                             if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
16194:                                 $changes{$itemid} = 1;
16195:                             }
16196:                         }
16197:                     }
16198:                     foreach my $field ('mapcrstype','selfenroll') {
16199:                         unless ($changes{$itemid}) {
16200:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16201:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16202:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16203:                                                                                    $confhash{$itemid}{$field});
16204:                                     if (@diffs) {
16205:                                         $changes{$itemid} = 1;
16206:                                     }
16207:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16208:                                     $changes{$itemid} = 1;
16209:                                 }
16210:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16211:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16212:                                     $changes{$itemid} = 1;
16213:                                 }
16214:                             }
16215:                         }
16216:                     }
16217:                     unless ($changes{$itemid}) {
16218:                         if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
16219:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16220:                                 foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
16221:                                     if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
16222:                                         $confhash{$itemid}{'maproles'}{$ltirole}) {
16223:                                         $changes{$itemid} = 1;
16224:                                         last;
16225:                                     }
16226:                                 }
16227:                                 unless ($changes{$itemid}) {
16228:                                     foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
16229:                                         if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
16230:                                             $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
16231:                                             $changes{$itemid} = 1;
16232:                                             last;
16233:                                         }
16234:                                     }
16235:                                 }
16236:                             } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
16237:                                 $changes{$itemid} = 1;
16238:                             }
16239:                         } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16240:                             unless ($changes{$itemid}) {
16241:                                 if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
16242:                                     $changes{$itemid} = 1;
16243:                                 }
16244:                             }
16245:                         }
16246:                     }
16247:                 }
16248:                 unless ($changes{$itemid}) {
16249:                     foreach my $field ('mapuser','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
16250:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16251:                             $changes{$itemid} = 1;
16252:                         }
16253:                     }
16254:                     unless ($changes{$itemid}) {
16255:                         foreach my $field ('makeuser','lcmenu') {
16256:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16257:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16258:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16259:                                                                                    $confhash{$itemid}{$field});
16260:                                     if (@diffs) {
16261:                                         $changes{$itemid} = 1;
16262:                                     }
16263:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16264:                                     $changes{$itemid} = 1;
16265:                                 }
16266:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16267:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16268:                                     $changes{$itemid} = 1;
16269:                                 }
16270:                             }
16271:                         }
16272:                     }
16273:                 }
16274:             }
16275:         }
16276:     }
16277:     if (@allpos > 0) {
16278:         my $idx = 0;
16279:         foreach my $itemid (@allpos) {
16280:             if ($itemid ne '') {
16281:                 $confhash{$itemid}{'order'} = $idx;
16282:                 if (ref($domconfig{$action}) eq 'HASH') {
16283:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16284:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
16285:                             $changes{$itemid} = 1;
16286:                         }
16287:                     }
16288:                 }
16289:                 $idx ++;
16290:             }
16291:         }
16292:     }
16293:     my %ltihash = (
16294:                       $action => { %confhash }
16295:                   );
16296:     my %ltienchash = (
16297:                          $action => { %encconfig }
16298:                      );
16299:     if (keys(%secchanges)) {
16300:         $ltihash{'ltisec'} = \%newltisec;
16301:         if ($secchanges{'linkprot'}) {
16302:             if ($is_home) {
16303:                 $ltienchash{'linkprot'} = \%newltienc;
16304:             }
16305:         }
16306:     }
16307:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
16308:     if ($putresult eq 'ok') {
16309:         my %keystore;
16310:         if (keys(%secchanges)) {
16311:             if ($secchanges{'private'}) {
16312:                 my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
16313:                 foreach my $hostid (keys(%newkeyset)) {
16314:                     my $storehash = {
16315:                                        key => $newkeyset{$hostid},
16316:                                        who => $env{'user.name'}.':'.$env{'user.domain'},
16317:                                     };
16318:                     $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
16319:                                                                     $dom,$hostid);
16320:                 }
16321:             }
16322:             if (ref($lastactref) eq 'HASH') {
16323:                 if (($secchanges{'encrypt'}) || ($secchanges{'private'})) {
16324:                     $lastactref->{'domdefaults'} = 1;
16325:                 }
16326:             }
16327:         }
16328:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
16329:         if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
16330:             return &mt('No changes made.');
16331:         }
16332:         $resulttext = &mt('Changes made:').'<ul>';
16333:         if (keys(%secchanges) > 0) {
16334:             foreach my $item (keys(%secchanges)) {
16335:                 if ($item eq 'encrypt') {
16336:                     my %encrypted = (
16337:                               crs  => {
16338:                                         on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
16339:                                         off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
16340:                                       },
16341:                               dom => {
16342:                                        on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
16343:                                        off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
16344:                                      },
16345:                               consumers => {
16346:                                              on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
16347:                                              off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
16348:                                            },
16349:                             );
16350:                     foreach my $type ('crs','dom','consumers') {
16351:                         my $shown = $encrypted{$type}{'off'};
16352:                         if (ref($newltisec{$item}) eq 'HASH') {
16353:                             if ($newltisec{$item}{$type}) {
16354:                                 $shown = $encrypted{$type}{'on'}; 
16355:                             }
16356:                         }
16357:                         $resulttext .= '<li>'.$shown.'</li>';
16358:                     } 
16359:                 } elsif ($item eq 'rules') {
16360:                      my %titles = &Apache::lonlocal::texthash(
16361:                                       min   => 'Minimum password length',
16362:                                       max   => 'Maximum password length',
16363:                                       chars => 'Required characters',
16364:                      );
16365:                      foreach my $rule ('min','max') {
16366:                          if ($newltisec{rules}{$rule} eq '') {
16367:                              if ($rule eq 'min') {
16368:                                  $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
16369:                                                 ' '.&mt('Default of [_1] will be used',
16370:                                                             $Apache::lonnet::passwdmin).'</li>';
16371:                              } else {
16372:                                  $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
16373:                              }
16374:                          } else {
16375:                              $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
16376:                          }
16377:                      }
16378:                      if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
16379:                          if (@{$newltisec{'rules'}{'chars'}} > 0) {
16380:                              my %rulenames = &Apache::lonlocal::texthash(
16381:                                                  uc => 'At least one upper case letter',
16382:                                                  lc => 'At least one lower case letter',
16383:                                                  num => 'At least one number',
16384:                                                  spec => 'At least one non-alphanumeric',
16385:                                              );
16386:                              my $needed = '<ul><li>'.
16387:                                           join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
16388:                                           '</li></ul>';
16389:                              $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
16390:                          } else {
16391:                              $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16392:                          }
16393:                      } else {
16394:                          $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16395:                      }
16396:                 } elsif ($item eq 'private') {
16397:                     if (keys(%newkeyset)) {
16398:                         foreach my $hostid (sort(keys(%newkeyset))) {
16399:                             if ($keystore{$hostid} eq 'ok') {
16400:                                 $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
16401:                             }
16402:                         }
16403:                     }
16404:                 } elsif ($item eq 'linkprot') {
16405:                     $resulttext .= $linkprotoutput;
16406:                 }
16407:             }
16408:         }
16409:         if (keys(%changes) > 0) {
16410:             my $cachetime = 24*60*60;
16411:             my %ltiall = %confhash;
16412:             foreach my $id (keys(%ltiall)) {
16413:                 if (ref($encconfig{$id}) eq 'HASH') {
16414:                     foreach my $item ('key','secret') {
16415:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
16416:                     }
16417:                 }
16418:             }
16419:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
16420:             if (ref($lastactref) eq 'HASH') {
16421:                 $lastactref->{'lti'} = 1;
16422:             }
16423:             my %bynum;
16424:             foreach my $itemid (sort(keys(%changes))) {
16425:                 my $position = $confhash{$itemid}{'order'};
16426:                 $bynum{$position} = $itemid;
16427:             }
16428:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
16429:                 my $itemid = $bynum{$pos};
16430:                 if (ref($confhash{$itemid}) ne 'HASH') {
16431:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
16432:                 } else {
16433:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b><ul>';
16434:                     my $position = $pos + 1;
16435:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
16436:                     foreach my $item ('version','lifetime') {
16437:                         if ($confhash{$itemid}{$item} ne '') {
16438:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
16439:                         }
16440:                     }
16441:                     if ($encconfig{$itemid}{'key'} ne '') {
16442:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
16443:                     }
16444:                     if ($encconfig{$itemid}{'secret'} ne '') {
16445:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
16446:                         my $num = length($encconfig{$itemid}{'secret'});
16447:                         $resulttext .= ('*'x$num).'</li>';
16448:                     }
16449:                     if ($confhash{$itemid}{'requser'}) {
16450:                         if ($confhash{$itemid}{'callback'}) {
16451:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
16452:                         } else {
16453:                             $resulttext .= '<li>'.&mt('Callback to logout LON-CAPA on log out from Consumer').'</li>';
16454:                         }
16455:                         if ($confhash{$itemid}{'mapuser'}) {
16456:                             my $shownmapuser;
16457:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
16458:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
16459:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
16460:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
16461:                             } else {
16462:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
16463:                             }
16464:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
16465:                         }
16466:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
16467:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
16468:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
16469:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
16470:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
16471:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
16472:                                 } else {
16473:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
16474:                                                        $confhash{$itemid}{'lcauth'});
16475:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
16476:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
16477:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
16478:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
16479:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
16480:                                         }
16481:                                     } else {
16482:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
16483:                                     }
16484:                                 }
16485:                                 $resulttext .= '</li>';
16486:                             } else {
16487:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
16488:                             }
16489:                         }
16490:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
16491:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
16492:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
16493:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
16494:                             } else {
16495:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
16496:                             }
16497:                         }
16498:                         foreach my $item ('topmenu','inlinemenu') {
16499:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16500:                             if ($confhash{$itemid}{$item}) {
16501:                                 $resulttext .= &mt('Yes');
16502:                             } else {
16503:                                 $resulttext .= &mt('No');
16504:                             }
16505:                             $resulttext .= '</li>';
16506:                         }
16507:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16508:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16509:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
16510:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
16511:                             } else {
16512:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
16513:                             }
16514:                         }
16515:                         if ($confhash{$itemid}{'crsinc'}) {
16516:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16517:                                 my $rolemaps;
16518:                                 foreach my $role (@ltiroles) {
16519:                                     if ($confhash{$itemid}{'maproles'}{$role}) {
16520:                                         $rolemaps .= ('&nbsp;'x2).$role.'='.
16521:                                                      &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
16522:                                                                                 'Course').',';
16523:                                     }
16524:                                 }
16525:                                 if ($rolemaps) {
16526:                                     $rolemaps =~ s/,$//;
16527:                                     $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
16528:                                 }
16529:                             }
16530:                             if ($confhash{$itemid}{'mapcrs'}) {
16531:                                 $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
16532:                             }
16533:                             if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
16534:                                 if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
16535:                                     $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
16536:                                                    join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
16537:                                                    '</li>';
16538:                                 } else {
16539:                                     $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
16540:                                 }
16541:                             }
16542:                             if ($confhash{$itemid}{'storecrs'}) {
16543:                                 $resulttext .= '<li>'.&mt('Store mapping of course identifier to LON-CAPA CourseID').': '.$confhash{$itemid}{'storecrs'}.'</li>';
16544:                             }
16545:                             if ($confhash{$itemid}{'makecrs'}) {
16546:                                 $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
16547:                             } else {
16548:                                 $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
16549:                             }
16550:                             if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
16551:                                 if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
16552:                                     $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
16553:                                                               join(', ',@{$confhash{$itemid}{'selfenroll'}})).
16554:                                                    '</li>';
16555:                                 } else {
16556:                                     $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
16557:                                 }
16558:                             }
16559:                             if ($confhash{$itemid}{'section'}) {
16560:                                 if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
16561:                                     $resulttext .= '<li>'.&mt('User section from standard field:').
16562:                                                          ' (course_section_sourcedid)'.'</li>';  
16563:                                 } else {
16564:                                     $resulttext .= '<li>'.&mt('User section from:').' '.
16565:                                                           $confhash{$itemid}{'section'}.'</li>';
16566:                                 }
16567:                             } else {
16568:                                 $resulttext .= '<li>'.&mt('No section assignment').'</li>';
16569:                             }
16570:                             foreach my $item ('passback','roster','topmenu','inlinemenu') {
16571:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16572:                                 if ($confhash{$itemid}{$item}) {
16573:                                     $resulttext .= &mt('Yes');
16574:                                     if ($item eq 'passback') {
16575:                                         if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
16576:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
16577:                                         } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
16578:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
16579:                                         }
16580:                                     }
16581:                                 } else {
16582:                                     $resulttext .= &mt('No');
16583:                                 }
16584:                                 $resulttext .= '</li>';
16585:                             }
16586:                             if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16587:                                 if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16588:                                     $resulttext .= '<li>'.&mt('Menu items:').' '.
16589:                                                    join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
16590:                                 } else {
16591:                                     $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
16592:                                 }
16593:                             }
16594:                         }
16595:                     }
16596:                     $resulttext .= '</ul></li>';
16597:                 }
16598:             }
16599:         }
16600:         $resulttext .= '</ul>';
16601:     } else {
16602:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
16603:     }
16604:     if ($errors) {
16605:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
16606:                        $errors.'</ul>';
16607:     }
16608:     return $resulttext;
16609: }
16610: 
16611: sub get_lti_id {
16612:     my ($domain,$consumer) = @_;
16613:     # get lock on lti db
16614:     my $lockhash = {
16615:                       lock => $env{'user.name'}.
16616:                               ':'.$env{'user.domain'},
16617:                    };
16618:     my $tries = 0;
16619:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16620:     my ($id,$error);
16621: 
16622:     while (($gotlock ne 'ok') && ($tries<10)) {
16623:         $tries ++;
16624:         sleep (0.1);
16625:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16626:     }
16627:     if ($gotlock eq 'ok') {
16628:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
16629:         if ($currids{'lock'}) {
16630:             delete($currids{'lock'});
16631:             if (keys(%currids)) {
16632:                 my @curr = sort { $a <=> $b } keys(%currids);
16633:                 if ($curr[-1] =~ /^\d+$/) {
16634:                     $id = 1 + $curr[-1];
16635:                 }
16636:             } else {
16637:                 $id = 1;
16638:             }
16639:             if ($id) {
16640:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
16641:                     $error = 'nostore';
16642:                 }
16643:             } else {
16644:                 $error = 'nonumber';
16645:             }
16646:         }
16647:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
16648:     } else {
16649:         $error = 'nolock';
16650:     }
16651:     return ($id,$error);
16652: }
16653: 
16654: sub modify_autoenroll {
16655:     my ($dom,$lastactref,%domconfig) = @_;
16656:     my ($resulttext,%changes);
16657:     my %currautoenroll;
16658:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
16659:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
16660:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
16661:         }
16662:     }
16663:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
16664:     my %title = ( run => 'Auto-enrollment active',
16665:                   sender => 'Sender for notification messages',
16666:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
16667:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
16668:     my @offon = ('off','on');
16669:     my $sender_uname = $env{'form.sender_uname'};
16670:     my $sender_domain = $env{'form.sender_domain'};
16671:     if ($sender_domain eq '') {
16672:         $sender_uname = '';
16673:     } elsif ($sender_uname eq '') {
16674:         $sender_domain = '';
16675:     }
16676:     my $coowners = $env{'form.autoassign_coowners'};
16677:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
16678:     $autofailsafe =~ s{^\s+|\s+$}{}g;
16679:     if ($autofailsafe =~ /\D/) {
16680:         undef($autofailsafe);
16681:     }
16682:     my $failsafe = $env{'form.autoenroll_failsafe'};
16683:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
16684:         $failsafe = 'off';
16685:         undef($autofailsafe);
16686:     }
16687:     my %autoenrollhash =  (
16688:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
16689:                                        'sender_uname' => $sender_uname,
16690:                                        'sender_domain' => $sender_domain,
16691:                                        'co-owners' => $coowners,
16692:                                        'autofailsafe' => $autofailsafe,
16693:                                        'failsafe' => $failsafe,
16694:                                 }
16695:                      );
16696:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
16697:                                              $dom);
16698:     if ($putresult eq 'ok') {
16699:         if (exists($currautoenroll{'run'})) {
16700:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
16701:                  $changes{'run'} = 1;
16702:              }
16703:         } elsif ($autorun) {
16704:             if ($env{'form.autoenroll_run'} ne '1') {
16705:                  $changes{'run'} = 1;
16706:             }
16707:         }
16708:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
16709:             $changes{'sender'} = 1;
16710:         }
16711:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
16712:             $changes{'sender'} = 1;
16713:         }
16714:         if ($currautoenroll{'co-owners'} ne '') {
16715:             if ($currautoenroll{'co-owners'} ne $coowners) {
16716:                 $changes{'coowners'} = 1;
16717:             }
16718:         } elsif ($coowners) {
16719:             $changes{'coowners'} = 1;
16720:         }
16721:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
16722:             $changes{'autofailsafe'} = 1;
16723:         }
16724:         if ($currautoenroll{'failsafe'} ne $failsafe) {
16725:             $changes{'failsafe'} = 1;
16726:         }
16727:         if (keys(%changes) > 0) {
16728:             $resulttext = &mt('Changes made:').'<ul>';
16729:             if ($changes{'run'}) {
16730:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
16731:             }
16732:             if ($changes{'sender'}) {
16733:                 if ($sender_uname eq '' || $sender_domain eq '') {
16734:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
16735:                 } else {
16736:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
16737:                 }
16738:             }
16739:             if ($changes{'coowners'}) {
16740:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
16741:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16742:                 if (ref($lastactref) eq 'HASH') {
16743:                     $lastactref->{'domainconfig'} = 1;
16744:                 }
16745:             }
16746:             if ($changes{'autofailsafe'}) {
16747:                 if ($autofailsafe ne '') {
16748:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
16749:                 } else {
16750:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16751:                 }
16752:             }
16753:             if ($changes{'failsafe'}) {
16754:                 if ($failsafe eq 'off') {
16755:                     unless ($changes{'autofailsafe'}) {
16756:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16757:                     }
16758:                 } elsif ($failsafe eq 'zero') {
16759:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
16760:                 } else {
16761:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
16762:                 }
16763:             }
16764:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
16765:                 &Apache::lonnet::get_domain_defaults($dom,1);
16766:                 if (ref($lastactref) eq 'HASH') {
16767:                     $lastactref->{'domdefaults'} = 1;
16768:                 }
16769:             }
16770:             $resulttext .= '</ul>';
16771:         } else {
16772:             $resulttext = &mt('No changes made to auto-enrollment settings');
16773:         }
16774:     } else {
16775:         $resulttext = '<span class="LC_error">'.
16776: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16777:     }
16778:     return $resulttext;
16779: }
16780: 
16781: sub modify_autoupdate {
16782:     my ($dom,%domconfig) = @_;
16783:     my ($resulttext,%currautoupdate,%fields,%changes);
16784:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
16785:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
16786:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
16787:         }
16788:     }
16789:     my @offon = ('off','on');
16790:     my %title = &Apache::lonlocal::texthash (
16791:                     run        => 'Auto-update:',
16792:                     classlists => 'Updates to user information in classlists?',
16793:                     unexpired  => 'Skip updates for users without active or future roles?',
16794:                     lastactive => 'Skip updates for inactive users?',
16795:                 );
16796:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16797:     my %fieldtitles = &Apache::lonlocal::texthash (
16798:                         id => 'Student/Employee ID',
16799:                         permanentemail => 'E-mail address',
16800:                         lastname => 'Last Name',
16801:                         firstname => 'First Name',
16802:                         middlename => 'Middle Name',
16803:                         generation => 'Generation',
16804:                       );
16805:     $othertitle = &mt('All users');
16806:     if (keys(%{$usertypes}) >  0) {
16807:         $othertitle = &mt('Other users');
16808:     }
16809:     foreach my $key (keys(%env)) {
16810:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
16811:             my ($usertype,$item) = ($1,$2);
16812:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
16813:                 if ($usertype eq 'default') {   
16814:                     push(@{$fields{$1}},$2);
16815:                 } elsif (ref($types) eq 'ARRAY') {
16816:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
16817:                         push(@{$fields{$1}},$2);
16818:                     }
16819:                 }
16820:             }
16821:         }
16822:     }
16823:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
16824:     @lockablenames = sort(@lockablenames);
16825:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
16826:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16827:         if (@changed) {
16828:             $changes{'lockablenames'} = 1;
16829:         }
16830:     } else {
16831:         if (@lockablenames) {
16832:             $changes{'lockablenames'} = 1;
16833:         }
16834:     }
16835:     my %updatehash = (
16836:                       autoupdate => { run => $env{'form.autoupdate_run'},
16837:                                       classlists => $env{'form.classlists'},
16838:                                       unexpired  => $env{'form.unexpired'},
16839:                                       fields => {%fields},
16840:                                       lockablenames => \@lockablenames,
16841:                                     }
16842:                      );
16843:     my $lastactivedays;
16844:     if ($env{'form.lastactive'}) {
16845:         $lastactivedays = $env{'form.lastactivedays'};
16846:         $lastactivedays =~ s/^\s+|\s+$//g;
16847:         unless ($lastactivedays =~ /^\d+$/) {
16848:             undef($lastactivedays);
16849:             $env{'form.lastactive'} = 0;
16850:         }
16851:     }
16852:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
16853:     foreach my $key (keys(%currautoupdate)) {
16854:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
16855:             if (exists($updatehash{autoupdate}{$key})) {
16856:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
16857:                     $changes{$key} = 1;
16858:                 }
16859:             }
16860:         } elsif ($key eq 'fields') {
16861:             if (ref($currautoupdate{$key}) eq 'HASH') {
16862:                 foreach my $item (@{$types},'default') {
16863:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
16864:                         my $change = 0;
16865:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
16866:                             if (!exists($fields{$item})) {
16867:                                 $change = 1;
16868:                                 last;
16869:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
16870:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
16871:                                     $change = 1;
16872:                                     last;
16873:                                 }
16874:                             }
16875:                         }
16876:                         if ($change) {
16877:                             push(@{$changes{$key}},$item);
16878:                         }
16879:                     } 
16880:                 }
16881:             }
16882:         } elsif ($key eq 'lockablenames') {
16883:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
16884:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16885:                 if (@changed) {
16886:                     $changes{'lockablenames'} = 1;
16887:                 }
16888:             } else {
16889:                 if (@lockablenames) {
16890:                     $changes{'lockablenames'} = 1;
16891:                 }
16892:             }
16893:         }
16894:     }
16895:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
16896:         if (@lockablenames) {
16897:             $changes{'lockablenames'} = 1;
16898:         }
16899:     }
16900:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
16901:         if ($updatehash{'autoupdate'}{'unexpired'}) {
16902:             $changes{'unexpired'} = 1;
16903:         }
16904:     }
16905:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
16906:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
16907:             $changes{'lastactive'} = 1;
16908:         }
16909:     }
16910:     foreach my $item (@{$types},'default') {
16911:         if (defined($fields{$item})) {
16912:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
16913:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
16914:                     my $change = 0;
16915:                     if (ref($fields{$item}) eq 'ARRAY') {
16916:                         foreach my $type (@{$fields{$item}}) {
16917:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
16918:                                 $change = 1;
16919:                                 last;
16920:                             }
16921:                         }
16922:                     }
16923:                     if ($change) {
16924:                         push(@{$changes{'fields'}},$item);
16925:                     }
16926:                 } else {
16927:                     push(@{$changes{'fields'}},$item);
16928:                 }
16929:             } else {
16930:                 push(@{$changes{'fields'}},$item);
16931:             }
16932:         }
16933:     }
16934:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
16935:                                              $dom);
16936:     if ($putresult eq 'ok') {
16937:         if (keys(%changes) > 0) {
16938:             $resulttext = &mt('Changes made:').'<ul>';
16939:             foreach my $key (sort(keys(%changes))) {
16940:                 if ($key eq 'lockablenames') {
16941:                     $resulttext .= '<li>';
16942:                     if (@lockablenames) {
16943:                         $usertypes->{'default'} = $othertitle;
16944:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
16945:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
16946:                     } else {
16947:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
16948:                     }
16949:                     $resulttext .= '</li>';
16950:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
16951:                     foreach my $item (@{$changes{$key}}) {
16952:                         my @newvalues;
16953:                         foreach my $type (@{$fields{$item}}) {
16954:                             push(@newvalues,$fieldtitles{$type});
16955:                         }
16956:                         my $newvaluestr;
16957:                         if (@newvalues > 0) {
16958:                             $newvaluestr = join(', ',@newvalues);
16959:                         } else {
16960:                             $newvaluestr = &mt('none');
16961:                         }
16962:                         if ($item eq 'default') {
16963:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
16964:                         } else {
16965:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
16966:                         }
16967:                     }
16968:                 } else {
16969:                     my $newvalue;
16970:                     if ($key eq 'run') {
16971:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
16972:                     } elsif ($key eq 'lastactive') {
16973:                         $newvalue = $offon[$env{'form.lastactive'}];
16974:                         unless ($lastactivedays eq '') {
16975:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
16976:                         }
16977:                     } else {
16978:                         $newvalue = $offon[$env{'form.'.$key}];
16979:                     }
16980:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
16981:                 }
16982:             }
16983:             $resulttext .= '</ul>';
16984:         } else {
16985:             $resulttext = &mt('No changes made to autoupdates');
16986:         }
16987:     } else {
16988:         $resulttext = '<span class="LC_error">'.
16989: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16990:     }
16991:     return $resulttext;
16992: }
16993: 
16994: sub modify_autocreate {
16995:     my ($dom,%domconfig) = @_;
16996:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
16997:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
16998:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
16999:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
17000:         }
17001:     }
17002:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
17003:                  req => 'Auto-creation of validated requests for official courses',
17004:                  xmldc => 'Identity of course creator of courses from XML files',
17005:                );
17006:     my @types = ('xml','req');
17007:     foreach my $item (@types) {
17008:         $newvals{$item} = $env{'form.autocreate_'.$item};
17009:         $newvals{$item} =~ s/\D//g;
17010:         $newvals{$item} = 0 if ($newvals{$item} eq '');
17011:     }
17012:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
17013:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
17014:     unless (exists($domcoords{$newvals{'xmldc'}})) {
17015:         $newvals{'xmldc'} = '';
17016:     } 
17017:     %autocreatehash =  (
17018:                         autocreate => { xml => $newvals{'xml'},
17019:                                         req => $newvals{'req'},
17020:                                       }
17021:                        );
17022:     if ($newvals{'xmldc'} ne '') {
17023:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
17024:     }
17025:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
17026:                                              $dom);
17027:     if ($putresult eq 'ok') {
17028:         my @items = @types;
17029:         if ($newvals{'xml'}) {
17030:             push(@items,'xmldc');
17031:         }
17032:         foreach my $item (@items) {
17033:             if (exists($currautocreate{$item})) {
17034:                 if ($currautocreate{$item} ne $newvals{$item}) {
17035:                     $changes{$item} = 1;
17036:                 }
17037:             } elsif ($newvals{$item}) {
17038:                 $changes{$item} = 1;
17039:             }
17040:         }
17041:         if (keys(%changes) > 0) {
17042:             my @offon = ('off','on'); 
17043:             $resulttext = &mt('Changes made:').'<ul>';
17044:             foreach my $item (@types) {
17045:                 if ($changes{$item}) {
17046:                     my $newtxt = $offon[$newvals{$item}];
17047:                     $resulttext .= '<li>'.
17048:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
17049:                                        '<b>','</b>').
17050:                                    '</li>';
17051:                 }
17052:             }
17053:             if ($changes{'xmldc'}) {
17054:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
17055:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
17056:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
17057:             }
17058:             $resulttext .= '</ul>';
17059:         } else {
17060:             $resulttext = &mt('No changes made to auto-creation settings');
17061:         }
17062:     } else {
17063:         $resulttext = '<span class="LC_error">'.
17064:             &mt('An error occurred: [_1]',$putresult).'</span>';
17065:     }
17066:     return $resulttext;
17067: }
17068: 
17069: sub modify_directorysrch {
17070:     my ($dom,$lastactref,%domconfig) = @_;
17071:     my ($resulttext,%changes);
17072:     my %currdirsrch;
17073:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
17074:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
17075:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
17076:         }
17077:     }
17078:     my %title = ( available => 'Institutional directory search available',
17079:                   localonly => 'Other domains can search institution',
17080:                   lcavailable => 'LON-CAPA directory search available',
17081:                   lclocalonly => 'Other domains can search LON-CAPA domain',
17082:                   searchby => 'Search types',
17083:                   searchtypes => 'Search latitude');
17084:     my @offon = ('off','on');
17085:     my @otherdoms = ('Yes','No');
17086: 
17087:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
17088:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
17089:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
17090: 
17091:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17092:     if (keys(%{$usertypes}) == 0) {
17093:         @cansearch = ('default');
17094:     } else {
17095:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
17096:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
17097:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
17098:                     push(@{$changes{'cansearch'}},$type);
17099:                 }
17100:             }
17101:             foreach my $type (@cansearch) {
17102:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
17103:                     push(@{$changes{'cansearch'}},$type);
17104:                 }
17105:             }
17106:         } else {
17107:             push(@{$changes{'cansearch'}},@cansearch);
17108:         }
17109:     }
17110: 
17111:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
17112:         foreach my $by (@{$currdirsrch{'searchby'}}) {
17113:             if (!grep(/^\Q$by\E$/,@searchby)) {
17114:                 push(@{$changes{'searchby'}},$by);
17115:             }
17116:         }
17117:         foreach my $by (@searchby) {
17118:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
17119:                 push(@{$changes{'searchby'}},$by);
17120:             }
17121:         }
17122:     } else {
17123:         push(@{$changes{'searchby'}},@searchby);
17124:     }
17125: 
17126:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
17127:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
17128:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
17129:                 push(@{$changes{'searchtypes'}},$type);
17130:             }
17131:         }
17132:         foreach my $type (@searchtypes) {
17133:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
17134:                 push(@{$changes{'searchtypes'}},$type);
17135:             }
17136:         }
17137:     } else {
17138:         if (exists($currdirsrch{'searchtypes'})) {
17139:             foreach my $type (@searchtypes) {  
17140:                 if ($type ne $currdirsrch{'searchtypes'}) { 
17141:                     push(@{$changes{'searchtypes'}},$type);
17142:                 }
17143:             }
17144:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
17145:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
17146:             }   
17147:         } else {
17148:             push(@{$changes{'searchtypes'}},@searchtypes); 
17149:         }
17150:     }
17151: 
17152:     my %dirsrch_hash =  (
17153:             directorysrch => { available => $env{'form.dirsrch_available'},
17154:                                cansearch => \@cansearch,
17155:                                localonly => $env{'form.dirsrch_instlocalonly'},
17156:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
17157:                                lcavailable => $env{'form.dirsrch_domavailable'},
17158:                                searchby => \@searchby,
17159:                                searchtypes => \@searchtypes,
17160:                              }
17161:             );
17162:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
17163:                                              $dom);
17164:     if ($putresult eq 'ok') {
17165:         if (exists($currdirsrch{'available'})) {
17166:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
17167:                  $changes{'available'} = 1;
17168:              }
17169:         } else {
17170:             if ($env{'form.dirsrch_available'} eq '1') {
17171:                 $changes{'available'} = 1;
17172:             }
17173:         }
17174:         if (exists($currdirsrch{'lcavailable'})) {
17175:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
17176:                 $changes{'lcavailable'} = 1;
17177:             }
17178:         } else {
17179:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
17180:                 $changes{'lcavailable'} = 1;
17181:             }
17182:         }
17183:         if (exists($currdirsrch{'localonly'})) {
17184:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
17185:                 $changes{'localonly'} = 1;
17186:             }
17187:         } else {
17188:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
17189:                 $changes{'localonly'} = 1;
17190:             }
17191:         }
17192:         if (exists($currdirsrch{'lclocalonly'})) {
17193:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
17194:                 $changes{'lclocalonly'} = 1;
17195:             }
17196:         } else {
17197:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
17198:                 $changes{'lclocalonly'} = 1;
17199:             }
17200:         }
17201:         if (keys(%changes) > 0) {
17202:             $resulttext = &mt('Changes made:').'<ul>';
17203:             if ($changes{'available'}) {
17204:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
17205:             }
17206:             if ($changes{'lcavailable'}) {
17207:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
17208:             }
17209:             if ($changes{'localonly'}) {
17210:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
17211:             }
17212:             if ($changes{'lclocalonly'}) {
17213:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
17214:             }
17215:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
17216:                 my $chgtext;
17217:                 if (ref($usertypes) eq 'HASH') {
17218:                     if (keys(%{$usertypes}) > 0) {
17219:                         foreach my $type (@{$types}) {
17220:                             if (grep(/^\Q$type\E$/,@cansearch)) {
17221:                                 $chgtext .= $usertypes->{$type}.'; ';
17222:                             }
17223:                         }
17224:                         if (grep(/^default$/,@cansearch)) {
17225:                             $chgtext .= $othertitle;
17226:                         } else {
17227:                             $chgtext =~ s/\; $//;
17228:                         }
17229:                         $resulttext .=
17230:                             '<li>'.
17231:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
17232:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
17233:                             '</li>';
17234:                     }
17235:                 }
17236:             }
17237:             if (ref($changes{'searchby'}) eq 'ARRAY') {
17238:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
17239:                 my $chgtext;
17240:                 foreach my $type (@{$titleorder}) {
17241:                     if (grep(/^\Q$type\E$/,@searchby)) {
17242:                         if (defined($searchtitles->{$type})) {
17243:                             $chgtext .= $searchtitles->{$type}.'; ';
17244:                         }
17245:                     }
17246:                 }
17247:                 $chgtext =~ s/\; $//;
17248:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
17249:             }
17250:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
17251:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
17252:                 my $chgtext;
17253:                 foreach my $type (@{$srchtypeorder}) {
17254:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
17255:                         if (defined($srchtypes_desc->{$type})) {
17256:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
17257:                         }
17258:                     }
17259:                 }
17260:                 $chgtext =~ s/\; $//;
17261:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
17262:             }
17263:             $resulttext .= '</ul>';
17264:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
17265:             if (ref($lastactref) eq 'HASH') {
17266:                 $lastactref->{'directorysrch'} = 1;
17267:             }
17268:         } else {
17269:             $resulttext = &mt('No changes made to directory search settings');
17270:         }
17271:     } else {
17272:         $resulttext = '<span class="LC_error">'.
17273:                       &mt('An error occurred: [_1]',$putresult).'</span>';
17274:     }
17275:     return $resulttext;
17276: }
17277: 
17278: sub modify_contacts {
17279:     my ($dom,$lastactref,%domconfig) = @_;
17280:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
17281:     if (ref($domconfig{'contacts'}) eq 'HASH') {
17282:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
17283:             $currsetting{$key} = $domconfig{'contacts'}{$key};
17284:         }
17285:     }
17286:     my (%others,%to,%bcc,%includestr,%includeloc);
17287:     my @contacts = ('supportemail','adminemail');
17288:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
17289:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
17290:     my @toggles = ('reporterrors','reportupdates','reportstatus');
17291:     my @lonstatus = ('threshold','sysmail','weights','excluded');
17292:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
17293:     foreach my $type (@mailings) {
17294:         @{$newsetting{$type}} = 
17295:             &Apache::loncommon::get_env_multiple('form.'.$type);
17296:         foreach my $item (@contacts) {
17297:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
17298:                 $contacts_hash{contacts}{$type}{$item} = 1;
17299:             } else {
17300:                 $contacts_hash{contacts}{$type}{$item} = 0;
17301:             }
17302:         }
17303:         $others{$type} = $env{'form.'.$type.'_others'};
17304:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
17305:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17306:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
17307:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
17308:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
17309:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
17310:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
17311:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17312:             }
17313:         }
17314:     }
17315:     foreach my $item (@contacts) {
17316:         $to{$item} = $env{'form.'.$item};
17317:         $contacts_hash{'contacts'}{$item} = $to{$item};
17318:     }
17319:     foreach my $item (@toggles) {
17320:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
17321:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
17322:         }
17323:     }
17324:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
17325:     foreach my $item (@lonstatus) {
17326:         if ($item eq 'excluded') {
17327:             my (%serverhomes,@excluded);
17328:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
17329:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
17330:             if (@possexcluded) {
17331:                 foreach my $id (sort(@possexcluded)) {
17332:                     if ($serverhomes{$id}) {
17333:                         push(@excluded,$id);
17334:                     }
17335:                 }
17336:             }
17337:             if (@excluded) {
17338:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
17339:             }
17340:         } elsif ($item eq 'weights') {
17341:             foreach my $type ('E','W','N','U') {
17342:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
17343:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
17344:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
17345:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
17346:                             $env{'form.error'.$item.'_'.$type};
17347:                     }
17348:                 }
17349:             }
17350:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
17351:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
17352:             if ($env{'form.error'.$item} =~ /^\d+$/) {
17353:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
17354:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
17355:                 }
17356:             }
17357:         }
17358:     }
17359:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
17360:         foreach my $field (@{$fields}) {
17361:             if (ref($possoptions->{$field}) eq 'ARRAY') {
17362:                 my $value = $env{'form.helpform_'.$field};
17363:                 $value =~ s/^\s+|\s+$//g;
17364:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
17365:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
17366:                     if ($field eq 'screenshot') {
17367:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
17368:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
17369:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
17370:                         }
17371:                     }
17372:                 }
17373:             }
17374:         }
17375:     }
17376:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17377:     my (@statuses,%usertypeshash,@overrides);
17378:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
17379:         @statuses = @{$types};
17380:         if (ref($usertypes) eq 'HASH') {
17381:             %usertypeshash = %{$usertypes};
17382:         }
17383:     }
17384:     if (@statuses) {
17385:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
17386:         foreach my $type (@possoverrides) {
17387:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
17388:                 push(@overrides,$type);
17389:             }
17390:         }
17391:         if (@overrides) {
17392:             foreach my $type (@overrides) {
17393:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
17394:                 foreach my $item (@contacts) {
17395:                     if (grep(/^\Q$item\E$/,@standard)) {
17396:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
17397:                         $newsetting{'override_'.$type}{$item} = 1;
17398:                     } else {
17399:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
17400:                         $newsetting{'override_'.$type}{$item} = 0;
17401:                     }
17402:                 }
17403:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
17404:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17405:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
17406:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17407:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
17408:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
17409:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
17410:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17411:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
17412:                 }
17413:             }     
17414:         }
17415:     }
17416:     if (keys(%currsetting) > 0) {
17417:         foreach my $item (@contacts) {
17418:             if ($to{$item} ne $currsetting{$item}) {
17419:                 $changes{$item} = 1;
17420:             }
17421:         }
17422:         foreach my $type (@mailings) {
17423:             foreach my $item (@contacts) {
17424:                 if (ref($currsetting{$type}) eq 'HASH') {
17425:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
17426:                         push(@{$changes{$type}},$item);
17427:                     }
17428:                 } else {
17429:                     push(@{$changes{$type}},@{$newsetting{$type}});
17430:                 }
17431:             }
17432:             if ($others{$type} ne $currsetting{$type}{'others'}) {
17433:                 push(@{$changes{$type}},'others');
17434:             }
17435:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17436:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
17437:                     push(@{$changes{$type}},'bcc'); 
17438:                 }
17439:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
17440:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
17441:                     push(@{$changes{$type}},'include');
17442:                 }
17443:             }
17444:         }
17445:         if (ref($fields) eq 'ARRAY') {
17446:             if (ref($currsetting{'helpform'}) eq 'HASH') {
17447:                 foreach my $field (@{$fields}) {
17448:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
17449:                         push(@{$changes{'helpform'}},$field);
17450:                     }
17451:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17452:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
17453:                             push(@{$changes{'helpform'}},'maxsize');
17454:                         }
17455:                     }
17456:                 }
17457:             } else {
17458:                 foreach my $field (@{$fields}) {
17459:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17460:                         push(@{$changes{'helpform'}},$field);
17461:                     }
17462:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17463:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17464:                             push(@{$changes{'helpform'}},'maxsize');
17465:                         }
17466:                     }
17467:                 }
17468:             }
17469:         }
17470:         if (@statuses) {
17471:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
17472:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
17473:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
17474:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
17475:                             foreach my $item (@contacts,'bcc','others','include') {
17476:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
17477:                                     push(@{$changes{'overrides'}},$key);
17478:                                     last;
17479:                                 }
17480:                             }
17481:                         } else {
17482:                             push(@{$changes{'overrides'}},$key);
17483:                         }
17484:                     }
17485:                 }
17486:                 foreach my $key (@overrides) {
17487:                     unless (exists($currsetting{'overrides'}{$key})) {
17488:                         push(@{$changes{'overrides'}},$key);
17489:                     }
17490:                 }
17491:             } else {
17492:                 foreach my $key (@overrides) {
17493:                     push(@{$changes{'overrides'}},$key); 
17494:                 }
17495:             }
17496:         }
17497:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
17498:             foreach my $key ('excluded','weights','threshold','sysmail') {
17499:                 if ($key eq 'excluded') {
17500:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17501:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
17502:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17503:                             (@{$currsetting{'lonstatus'}{$key}})) {
17504:                             my @diffs =
17505:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
17506:                                                                    $currsetting{'lonstatus'}{$key});
17507:                             if (@diffs) {
17508:                                 push(@{$changes{'lonstatus'}},$key);
17509:                             }
17510:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
17511:                             push(@{$changes{'lonstatus'}},$key);
17512:                         }
17513:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17514:                              (@{$currsetting{'lonstatus'}{$key}})) {
17515:                         push(@{$changes{'lonstatus'}},$key);
17516:                     }
17517:                 } elsif ($key eq 'weights') {
17518:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17519:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
17520:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17521:                             foreach my $type ('E','W','N','U') {
17522:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
17523:                                         $currsetting{'lonstatus'}{$key}{$type}) {
17524:                                     push(@{$changes{'lonstatus'}},$key);
17525:                                     last;
17526:                                 }
17527:                             }
17528:                         } else {
17529:                             foreach my $type ('E','W','N','U') {
17530:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
17531:                                     push(@{$changes{'lonstatus'}},$key);
17532:                                     last;
17533:                                 }
17534:                             }
17535:                         }
17536:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17537:                         foreach my $type ('E','W','N','U') {
17538:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
17539:                                 push(@{$changes{'lonstatus'}},$key);
17540:                                 last;
17541:                             }
17542:                         }
17543:                     }
17544:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
17545:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17546:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17547:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
17548:                                 push(@{$changes{'lonstatus'}},$key);
17549:                             }
17550:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
17551:                             push(@{$changes{'lonstatus'}},$key);
17552:                         }
17553:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17554:                         push(@{$changes{'lonstatus'}},$key);
17555:                     }
17556:                 }
17557:             }
17558:         } else {
17559:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17560:                 foreach my $key ('excluded','weights','threshold','sysmail') {
17561:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17562:                         push(@{$changes{'lonstatus'}},$key);
17563:                     }
17564:                 }
17565:             }
17566:         }
17567:     } else {
17568:         my %default;
17569:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
17570:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
17571:         $default{'errormail'} = 'adminemail';
17572:         $default{'packagesmail'} = 'adminemail';
17573:         $default{'helpdeskmail'} = 'supportemail';
17574:         $default{'otherdomsmail'} = 'supportemail';
17575:         $default{'lonstatusmail'} = 'adminemail';
17576:         $default{'requestsmail'} = 'adminemail';
17577:         $default{'updatesmail'} = 'adminemail';
17578:         $default{'hostipmail'} = 'adminemail';
17579:         foreach my $item (@contacts) {
17580:            if ($to{$item} ne $default{$item}) {
17581:                $changes{$item} = 1;
17582:            }
17583:         }
17584:         foreach my $type (@mailings) {
17585:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
17586:                 push(@{$changes{$type}},@{$newsetting{$type}});
17587:             }
17588:             if ($others{$type} ne '') {
17589:                 push(@{$changes{$type}},'others');
17590:             }
17591:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17592:                 if ($bcc{$type} ne '') {
17593:                     push(@{$changes{$type}},'bcc');
17594:                 }
17595:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
17596:                     push(@{$changes{$type}},'include');
17597:                 }
17598:             }
17599:         }
17600:         if (ref($fields) eq 'ARRAY') {
17601:             foreach my $field (@{$fields}) {
17602:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17603:                     push(@{$changes{'helpform'}},$field);
17604:                 }
17605:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17606:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17607:                         push(@{$changes{'helpform'}},'maxsize');
17608:                     }
17609:                 }
17610:             }
17611:         }
17612:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17613:             foreach my $key ('excluded','weights','threshold','sysmail') {
17614:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17615:                     push(@{$changes{'lonstatus'}},$key);
17616:                 }
17617:             }
17618:         }
17619:     }
17620:     foreach my $item (@toggles) {
17621:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
17622:             $changes{$item} = 1;
17623:         } elsif ((!$env{'form.'.$item}) &&
17624:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
17625:             $changes{$item} = 1;
17626:         }
17627:     }
17628:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
17629:                                              $dom);
17630:     if ($putresult eq 'ok') {
17631:         if (keys(%changes) > 0) {
17632:             &Apache::loncommon::devalidate_domconfig_cache($dom);
17633:             if (ref($lastactref) eq 'HASH') {
17634:                 $lastactref->{'domainconfig'} = 1;
17635:             }
17636:             my ($titles,$short_titles)  = &contact_titles();
17637:             $resulttext = &mt('Changes made:').'<ul>';
17638:             foreach my $item (@contacts) {
17639:                 if ($changes{$item}) {
17640:                     $resulttext .= '<li>'.$titles->{$item}.
17641:                                     &mt(' set to: ').
17642:                                     '<span class="LC_cusr_emph">'.
17643:                                     $to{$item}.'</span></li>';
17644:                 }
17645:             }
17646:             foreach my $type (@mailings) {
17647:                 if (ref($changes{$type}) eq 'ARRAY') {
17648:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17649:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
17650:                     } else {
17651:                         $resulttext .= '<li>'.$titles->{$type}.': ';
17652:                     }
17653:                     my @text;
17654:                     foreach my $item (@{$newsetting{$type}}) {
17655:                         push(@text,$short_titles->{$item});
17656:                     }
17657:                     if ($others{$type} ne '') {
17658:                         push(@text,$others{$type});
17659:                     }
17660:                     if (@text) {
17661:                         $resulttext .= '<span class="LC_cusr_emph">'.
17662:                                        join(', ',@text).'</span>';
17663:                     }
17664:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17665:                         if ($bcc{$type} ne '') {
17666:                             my $bcctext;
17667:                             if (@text) {
17668:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
17669:                             } else {
17670:                                 $bcctext = '(Bcc)';
17671:                             }
17672:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
17673:                         } elsif (!@text) {
17674:                             $resulttext .= &mt('No one');
17675:                         }   
17676:                         if ($includestr{$type} ne '') {
17677:                             if ($includeloc{$type} eq 'b') {
17678:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
17679:                             } elsif ($includeloc{$type} eq 's') {
17680:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
17681:                             }
17682:                         }
17683:                     } elsif (!@text) {
17684:                         $resulttext .= &mt('No recipients');
17685:                     }
17686:                     $resulttext .= '</li>';
17687:                 }
17688:             }
17689:             if (ref($changes{'overrides'}) eq 'ARRAY') {
17690:                 my @deletions;
17691:                 foreach my $type (@{$changes{'overrides'}}) {
17692:                     if ($usertypeshash{$type}) {
17693:                         if (grep(/^\Q$type\E/,@overrides)) {
17694:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
17695:                                                       $usertypeshash{$type}).'<ul><li>';
17696:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
17697:                                 my @text;
17698:                                 foreach my $item (@contacts) {
17699:                                     if ($newsetting{'override_'.$type}{$item}) { 
17700:                                         push(@text,$short_titles->{$item});
17701:                                     }
17702:                                 }
17703:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
17704:                                     push(@text,$newsetting{'override_'.$type}{'others'});
17705:                                 }
17706:   
17707:                                 if (@text) {
17708:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
17709:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
17710:                                 }
17711:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
17712:                                     my $bcctext;
17713:                                     if (@text) {
17714:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
17715:                                     } else {
17716:                                         $bcctext = '(Bcc)';
17717:                                     }
17718:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
17719:                                 } elsif (!@text) {
17720:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
17721:                                 }
17722:                                 $resulttext .= '</li>';
17723:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
17724:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
17725:                                     if ($loc eq 'b') {
17726:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
17727:                                     } elsif ($loc eq 's') {
17728:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
17729:                                     }
17730:                                 }
17731:                             }
17732:                             $resulttext .= '</li></ul></li>';
17733:                         } else {
17734:                             push(@deletions,$usertypeshash{$type});
17735:                         }
17736:                     }
17737:                 }
17738:                 if (@deletions) {
17739:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
17740:                                               join(', ',@deletions)).'</li>';
17741:                 }
17742:             }
17743:             my @offon = ('off','on');
17744:             my $corelink = &core_link_msu();
17745:             if ($changes{'reporterrors'}) {
17746:                 $resulttext .= '<li>'.
17747:                                &mt('E-mail error reports to [_1] set to "'.
17748:                                    $offon[$env{'form.reporterrors'}].'".',
17749:                                    $corelink).
17750:                                '</li>';
17751:             }
17752:             if ($changes{'reportupdates'}) {
17753:                 $resulttext .= '<li>'.
17754:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
17755:                                     $offon[$env{'form.reportupdates'}].'".',
17756:                                     $corelink).
17757:                                 '</li>';
17758:             }
17759:             if ($changes{'reportstatus'}) {
17760:                 $resulttext .= '<li>'.
17761:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
17762:                                     $offon[$env{'form.reportstatus'}].'".',
17763:                                     $corelink).
17764:                                 '</li>';
17765:             }
17766:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
17767:                 $resulttext .= '<li>'.
17768:                                &mt('Nightly status check e-mail settings').':<ul>';
17769:                 my (%defval,%use_def,%shown);
17770:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
17771:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
17772:                 $defval{'weights'} =
17773:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
17774:                 $defval{'excluded'} = &mt('None');
17775:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
17776:                     foreach my $item ('threshold','sysmail','weights','excluded') {
17777:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
17778:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
17779:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
17780:                             } elsif ($item eq 'weights') {
17781:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
17782:                                     foreach my $type ('E','W','N','U') {
17783:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
17784:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
17785:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
17786:                                         } else {
17787:                                             $shown{$item} .= $lonstatus_defs->{$type};
17788:                                         }
17789:                                         $shown{$item} .= ', ';
17790:                                     }
17791:                                     $shown{$item} =~ s/, $//;
17792:                                 } else {
17793:                                     $shown{$item} = $defval{$item};
17794:                                 }
17795:                             } elsif ($item eq 'excluded') {
17796:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
17797:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
17798:                                 } else {
17799:                                     $shown{$item} = $defval{$item};
17800:                                 }
17801:                             }
17802:                         } else {
17803:                             $shown{$item} = $defval{$item};
17804:                         }
17805:                     }
17806:                 } else {
17807:                     foreach my $item ('threshold','weights','excluded','sysmail') {
17808:                         $shown{$item} = $defval{$item};
17809:                     }
17810:                 }
17811:                 foreach my $item ('threshold','weights','excluded','sysmail') {
17812:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
17813:                                           $shown{$item}).'</li>';
17814:                 }
17815:                 $resulttext .= '</ul></li>';
17816:             }
17817:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
17818:                 my (@optional,@required,@unused,$maxsizechg);
17819:                 foreach my $field (@{$changes{'helpform'}}) {
17820:                     if ($field eq 'maxsize') {
17821:                         $maxsizechg = 1;
17822:                         next;
17823:                     }
17824:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
17825:                         push(@optional,$field);
17826:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
17827:                         push(@unused,$field);
17828:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
17829:                         push(@required,$field);
17830:                     }
17831:                 }
17832:                 if (@optional) {
17833:                     $resulttext .= '<li>'.
17834:                                    &mt('Help form fields changed to "Optional": [_1].',
17835:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
17836:                                    '</li>';
17837:                 }
17838:                 if (@required) {
17839:                     $resulttext .= '<li>'.
17840:                                    &mt('Help form fields changed to "Required": [_1].',
17841:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
17842:                                    '</li>';
17843:                 }
17844:                 if (@unused) {
17845:                     $resulttext .= '<li>'.
17846:                                    &mt('Help form fields changed to "Not shown": [_1].',
17847:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
17848:                                    '</li>';
17849:                 }
17850:                 if ($maxsizechg) {
17851:                     $resulttext .= '<li>'.
17852:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
17853:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
17854:                                    '</li>';
17855:                 }
17856:             }
17857:             $resulttext .= '</ul>';
17858:         } else {
17859:             $resulttext = &mt('No changes made to contacts and form settings');
17860:         }
17861:     } else {
17862:         $resulttext = '<span class="LC_error">'.
17863:             &mt('An error occurred: [_1].',$putresult).'</span>';
17864:     }
17865:     return $resulttext;
17866: }
17867: 
17868: sub modify_privacy {
17869:     my ($dom,%domconfig) = @_;
17870:     my ($resulttext,%current,%changes);
17871:     if (ref($domconfig{'privacy'}) eq 'HASH') {
17872:         %current = %{$domconfig{'privacy'}};
17873:     }
17874:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
17875:     my @items = ('domain','author','course','community');
17876:     my %names = &Apache::lonlocal::texthash (
17877:                    domain => 'Assigned domain role(s)',
17878:                    author => 'Assigned co-author role(s)',
17879:                    course => 'Assigned course role(s)',
17880:                    community => 'Assigned community role',
17881:                 );
17882:     my %roles = &Apache::lonlocal::texthash (
17883:                    domain => 'Domain role',
17884:                    author => 'Co-author role',
17885:                    course => 'Course role',
17886:                    community => 'Community role',
17887:                 );
17888:     my %titles = &Apache::lonlocal::texthash (
17889:                   approval => 'Approval for role in different domain',
17890:                   othdom   => 'User information available in other domain',
17891:                   priv     => 'Information viewable by privileged user in same domain',
17892:                   unpriv   => 'Information viewable by unprivileged user in same domain',
17893:                   instdom  => 'Other domain shares institution/provider',
17894:                   extdom   => 'Other domain has different institution/provider',
17895:                   none     => 'Not allowed',
17896:                   user     => 'User authorizes',
17897:                   domain   => 'Domain Coordinator authorizes',
17898:                   auto     => 'Unrestricted',
17899:     );
17900:     my %fieldnames = &Apache::lonlocal::texthash (
17901:                         id => 'Student/Employee ID',
17902:                         permanentemail => 'E-mail address',
17903:                         lastname => 'Last Name',
17904:                         firstname => 'First Name',
17905:                         middlename => 'Middle Name',
17906:                         generation => 'Generation',
17907:     );
17908:     my ($othertitle,$usertypes,$types) =
17909:         &Apache::loncommon::sorted_inst_types($dom);
17910:     my (%by_ip,%by_location,@intdoms,@instdoms);
17911:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
17912: 
17913:     my %privacyhash = (
17914:                        'approval' => {
17915:                                        instdom => {},
17916:                                        extdom  => {},
17917:                                      },
17918:                        'othdom'   => {},
17919:                        'priv'     => {},
17920:                        'unpriv'   => {},
17921:                       );
17922:     foreach my $item (@items) {
17923:         if (@instdoms > 1) {
17924:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
17925:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
17926:             }
17927:             if (ref($current{'approval'}) eq 'HASH') {
17928:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
17929:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
17930:                         $changes{'approval'} = 1;
17931:                     }
17932:                 }
17933:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
17934:                 $changes{'approval'} = 1;
17935:             }
17936:         }
17937:         if (keys(%by_location) > 0) {
17938:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
17939:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
17940:             }
17941:             if (ref($current{'approval'}) eq 'HASH') {
17942:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
17943:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
17944:                         $changes{'approval'} = 1;
17945:                     }
17946:                 }
17947:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
17948:                 $changes{'approval'} = 1;
17949:             }
17950:         }
17951:         foreach my $status ('priv','unpriv') {
17952:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
17953:             my @newvalues;
17954:             foreach my $field (@possibles) {
17955:                 if (grep(/^\Q$field\E$/,@fields)) {
17956:                     $privacyhash{$status}{$item}{$field} = 1;
17957:                     push(@newvalues,$field);
17958:                 }
17959:             }
17960:             @newvalues = sort(@newvalues);
17961:             if (ref($current{$status}) eq 'HASH') {
17962:                 if (ref($current{$status}{$item}) eq 'HASH') {
17963:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
17964:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17965:                     if (@diffs > 0) {
17966:                         $changes{$status} = 1;
17967:                     }
17968:                 }
17969:             } else {
17970:                 my @stdfields;
17971:                 foreach my $field (@fields) {
17972:                     if ($field eq 'id') {
17973:                         next if ($status eq 'unpriv');
17974:                         next if (($status eq 'priv') && ($item eq 'community'));
17975:                     }
17976:                     push(@stdfields,$field);
17977:                 }
17978:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
17979:                 if (@diffs > 0) {
17980:                     $changes{$status} = 1;
17981:                 }
17982:             }
17983:         }
17984:     }
17985:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
17986:         my @statuses;
17987:         if (ref($types) eq 'ARRAY') {
17988:             @statuses = @{$types};
17989:         }
17990:         foreach my $type (@statuses,'default') {
17991:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
17992:             my @newvalues;
17993:             foreach my $field (sort(@possfields)) {
17994:                 if (grep(/^\Q$field\E$/,@fields)) {
17995:                     $privacyhash{'othdom'}{$type}{$field} = 1;
17996:                     push(@newvalues,$field);
17997:                 }
17998:             }
17999:             @newvalues = sort(@newvalues);
18000:             if (ref($current{'othdom'}) eq 'HASH') {
18001:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
18002:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
18003:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
18004:                     if (@diffs > 0) {
18005:                         $changes{'othdom'} = 1;
18006:                     }
18007:                 }
18008:             } else {
18009:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
18010:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
18011:                 if (@diffs > 0) {
18012:                     $changes{'othdom'} = 1;
18013:                 }
18014:             }
18015:         }
18016:     }
18017:     my %confighash = (
18018:                         privacy => \%privacyhash,
18019:                      );
18020:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18021:     if ($putresult eq 'ok') {
18022:         if (keys(%changes) > 0) {
18023:             $resulttext = &mt('Changes made: ').'<ul>';
18024:             foreach my $key ('approval','othdom','priv','unpriv') {
18025:                 if ($changes{$key}) {
18026:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18027:                     if ($key eq 'approval') {
18028:                         if (keys(%{$privacyhash{$key}{instdom}})) {
18029:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
18030:                             foreach my $item (@items) {
18031:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
18032:                             }
18033:                             $resulttext .= '</ul></li>';
18034:                         }
18035:                         if (keys(%{$privacyhash{$key}{extdom}})) {
18036:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
18037:                             foreach my $item (@items) {
18038:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
18039:                             }
18040:                             $resulttext .= '</ul></li>';
18041:                         }
18042:                     } elsif ($key eq 'othdom') {
18043:                         my @statuses;
18044:                         if (ref($types) eq 'ARRAY') {
18045:                             @statuses = @{$types};
18046:                         }
18047:                         if (ref($privacyhash{$key}) eq 'HASH') {
18048:                             foreach my $status (@statuses,'default') {
18049:                                 if ($status eq 'default') {
18050:                                     $resulttext .= '<li>'.$othertitle.': ';
18051:                                 } elsif (ref($usertypes) eq 'HASH') {
18052:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
18053:                                 } else {
18054:                                     next;
18055:                                 }
18056:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
18057:                                     if (keys(%{$privacyhash{$key}{$status}})) {
18058:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
18059:                                     } else {
18060:                                         $resulttext .= &mt('none');
18061:                                     }
18062:                                 }
18063:                                 $resulttext .= '</li>';
18064:                             }
18065:                         }
18066:                     } else {
18067:                         foreach my $item (@items) {
18068:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
18069:                                 $resulttext .= '<li>'.$names{$item}.': ';
18070:                                 if (keys(%{$privacyhash{$key}{$item}})) {
18071:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
18072:                                 } else {
18073:                                     $resulttext .= &mt('none');
18074:                                 }
18075:                                 $resulttext .= '</li>';
18076:                             }
18077:                         }
18078:                     }
18079:                     $resulttext .= '</ul></li>';
18080:                 }
18081:             }
18082:         } else {
18083:             $resulttext = &mt('No changes made to user information settings');
18084:         }
18085:     } else {
18086:         $resulttext = '<span class="LC_error">'.
18087:             &mt('An error occurred: [_1]',$putresult).'</span>';
18088:     }
18089:     return $resulttext;
18090: }
18091: 
18092: sub modify_passwords {
18093:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
18094:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
18095:         $updatedefaults,$updateconf);
18096:     my $customfn = 'resetpw.html';
18097:     if (ref($domconfig{'passwords'}) eq 'HASH') {
18098:         %current = %{$domconfig{'passwords'}};
18099:     }
18100:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18101:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
18102:     if (ref($types) eq 'ARRAY') {
18103:         @oktypes = @{$types};
18104:     }
18105:     push(@oktypes,'default');
18106: 
18107:     my %titles = &Apache::lonlocal::texthash (
18108:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
18109:         intauth_check  => 'Check bcrypt cost if authenticated',
18110:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
18111:         permanent      => 'Permanent e-mail address',
18112:         critical       => 'Critical notification address',
18113:         notify         => 'Notification address',
18114:         min            => 'Minimum password length',
18115:         max            => 'Maximum password length',
18116:         chars          => 'Required characters',
18117:         expire         => 'Password expiration (days)',
18118:         numsaved       => 'Number of previous passwords to save',
18119:         reset          => 'Resetting Forgotten Password',
18120:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
18121:         rules          => 'Rules for LON-CAPA Passwords',
18122:         crsownerchg    => 'Course Owner Changing Student Passwords',
18123:         username       => 'Username',
18124:         email          => 'E-mail address',
18125:     );
18126: 
18127: #
18128: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
18129: #
18130:     my (%curr_defaults,%save_defaults);
18131:     if (ref($domconfig{'defaults'}) eq 'HASH') {
18132:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
18133:             if ($key =~ /^intauth_(cost|check|switch)$/) {
18134:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
18135:             } else {
18136:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
18137:             }
18138:         }
18139:     }
18140:     my %staticdefaults = (
18141:         'resetlink'      => 2,
18142:         'resetcase'      => \@oktypes,
18143:         'resetprelink'   => 'both',
18144:         'resetemail'     => ['critical','notify','permanent'],
18145:         'intauth_cost'   => 10,
18146:         'intauth_check'  => 0,
18147:         'intauth_switch' => 0,
18148:     );
18149:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18150:     foreach my $type (@oktypes) {
18151:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
18152:     }
18153:     my $linklife = $env{'form.passwords_link'};
18154:     $linklife =~ s/^\s+|\s+$//g;
18155:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
18156:         $newvalues{'resetlink'} = $linklife;
18157:         if ($current{'resetlink'}) {
18158:             if ($current{'resetlink'} ne $linklife) {
18159:                 $changes{'reset'} = 1;
18160:             }
18161:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18162:             if ($staticdefaults{'resetlink'} ne $linklife) {
18163:                 $changes{'reset'} = 1;
18164:             }
18165:         }
18166:     } elsif ($current{'resetlink'}) {
18167:         $changes{'reset'} = 1;
18168:     }
18169:     my @casesens;
18170:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
18171:     foreach my $case (sort(@posscase)) {
18172:         if (grep(/^\Q$case\E$/,@oktypes)) {
18173:             push(@casesens,$case);
18174:         }
18175:     }
18176:     $newvalues{'resetcase'} = \@casesens;
18177:     if (ref($current{'resetcase'}) eq 'ARRAY') {
18178:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
18179:         if (@diffs > 0) {
18180:             $changes{'reset'} = 1;
18181:         }
18182:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18183:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
18184:         if (@diffs > 0) {
18185:             $changes{'reset'} = 1;
18186:         }
18187:     }
18188:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
18189:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
18190:         if (exists($current{'resetprelink'})) {
18191:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
18192:                 $changes{'reset'} = 1;
18193:             }
18194:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18195:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
18196:                 $changes{'reset'} = 1;
18197:             }
18198:         }
18199:     } elsif ($current{'resetprelink'}) {
18200:         $changes{'reset'} = 1;
18201:     }
18202:     foreach my $type (@oktypes) {
18203:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
18204:         my @postlink;
18205:         foreach my $item (sort(@possplink)) {
18206:             if ($item =~ /^(email|username)$/) {
18207:                 push(@postlink,$item);
18208:             }
18209:         }
18210:         $newvalues{'resetpostlink'}{$type} = \@postlink;
18211:         unless ($changes{'reset'}) {
18212:             if (ref($current{'resetpostlink'}) eq 'HASH') {
18213:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
18214:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
18215:                     if (@diffs > 0) {
18216:                         $changes{'reset'} = 1;
18217:                     }
18218:                 } else {
18219:                     $changes{'reset'} = 1;
18220:                 }
18221:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18222:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
18223:                 if (@diffs > 0) {
18224:                     $changes{'reset'} = 1;
18225:                 }
18226:             }
18227:         }
18228:     }
18229:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
18230:     my @resetemail;
18231:     foreach my $item (sort(@possemailsrc)) {
18232:         if ($item =~ /^(permanent|critical|notify)$/) {
18233:             push(@resetemail,$item);
18234:         }
18235:     }
18236:     $newvalues{'resetemail'} = \@resetemail;
18237:     unless ($changes{'reset'}) {
18238:         if (ref($current{'resetemail'}) eq 'ARRAY') {
18239:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
18240:             if (@diffs > 0) {
18241:                 $changes{'reset'} = 1;
18242:             }
18243:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18244:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
18245:             if (@diffs > 0) {
18246:                 $changes{'reset'} = 1;
18247:             }
18248:         }
18249:     }
18250:     if ($env{'form.passwords_stdtext'} == 0) {
18251:         $newvalues{'resetremove'} = 1;
18252:         unless ($current{'resetremove'}) {
18253:             $changes{'reset'} = 1;
18254:         }
18255:     } elsif ($current{'resetremove'}) {
18256:         $changes{'reset'} = 1;
18257:     }
18258:     if ($env{'form.passwords_customfile.filename'} ne '') {
18259:         my $servadm = $r->dir_config('lonAdmEMail');
18260:         my ($configuserok,$author_ok,$switchserver) =
18261:             &config_check($dom,$confname,$servadm);
18262:         my $error;
18263:         if ($configuserok eq 'ok') {
18264:             if ($switchserver) {
18265:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
18266:             } else {
18267:                 if ($author_ok eq 'ok') {
18268:                     my ($result,$customurl) =
18269:                         &publishlogo($r,'upload','passwords_customfile',$dom,
18270:                                      $confname,'customtext/resetpw','','',$customfn);
18271:                     if ($result eq 'ok') {
18272:                         $newvalues{'resetcustom'} = $customurl;
18273:                         $changes{'reset'} = 1;
18274:                     } else {
18275:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
18276:                     }
18277:                 } else {
18278:                     $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);
18279:                 }
18280:             }
18281:         } else {
18282:             $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);
18283:         }
18284:         if ($error) {
18285:             &Apache::lonnet::logthis($error);
18286:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18287:         }
18288:     } elsif ($current{'resetcustom'}) {
18289:         if ($env{'form.passwords_custom_del'}) {
18290:             $changes{'reset'} = 1;
18291:         } else {
18292:             $newvalues{'resetcustom'} = $current{'resetcustom'};
18293:         }
18294:     }
18295:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
18296:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
18297:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
18298:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
18299:             $changes{'intauth'} = 1;
18300:         }
18301:     } else {
18302:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
18303:     }
18304:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
18305:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
18306:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
18307:             $changes{'intauth'} = 1;
18308:         }
18309:     } else {
18310:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18311:     }
18312:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
18313:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
18314:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
18315:             $changes{'intauth'} = 1;
18316:         }
18317:     } else {
18318:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18319:     }
18320:     foreach my $item ('cost','check','switch') {
18321:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
18322:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
18323:             $updatedefaults = 1;
18324:         }
18325:     }
18326:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
18327:     my %crsownerchg = (
18328:                         by => [],
18329:                         for => [],
18330:                       );
18331:     foreach my $item ('by','for') {
18332:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
18333:         foreach my $type (sort(@posstypes)) {
18334:             if (grep(/^\Q$type\E$/,@oktypes)) {
18335:                 push(@{$crsownerchg{$item}},$type);
18336:             }
18337:         }
18338:     }
18339:     $newvalues{'crsownerchg'} = \%crsownerchg;
18340:     if (ref($current{'crsownerchg'}) eq 'HASH') {
18341:         foreach my $item ('by','for') {
18342:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
18343:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
18344:                 if (@diffs > 0) {
18345:                     $changes{'crsownerchg'} = 1;
18346:                     last;
18347:                 }
18348:             }
18349:         }
18350:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
18351:         foreach my $item ('by','for') {
18352:             if (@{$crsownerchg{$item}} > 0) {
18353:                 $changes{'crsownerchg'} = 1;
18354:                 last;
18355:             }
18356:         }
18357:     }
18358: 
18359:     my %confighash = (
18360:                         defaults  => \%save_defaults,
18361:                         passwords => \%newvalues,
18362:                      );
18363:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
18364: 
18365:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18366:     if ($putresult eq 'ok') {
18367:         if (keys(%changes) > 0) {
18368:             $resulttext = &mt('Changes made: ').'<ul>';
18369:             foreach my $key ('reset','intauth','rules','crsownerchg') {
18370:                 if ($changes{$key}) {
18371:                     unless ($key eq 'intauth') {
18372:                         $updateconf = 1;
18373:                     }
18374:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18375:                     if ($key eq 'reset') {
18376:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
18377:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
18378:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
18379:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
18380:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
18381:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
18382:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
18383:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
18384:                             }
18385:                         } else {
18386:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
18387:                         }
18388:                         if ($confighash{'passwords'}{'resetlink'}) {
18389:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
18390:                         } else {
18391:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
18392:                                                   &mt('Will default to 2 hours').'</li>';
18393:                         }
18394:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
18395:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
18396:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
18397:                             } else {
18398:                                 my $casesens;
18399:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
18400:                                     if ($type eq 'default') {
18401:                                         $casesens .= $othertitle.', ';
18402:                                     } elsif ($usertypes->{$type} ne '') {
18403:                                         $casesens .= $usertypes->{$type}.', ';
18404:                                     }
18405:                                 }
18406:                                 $casesens =~ s/\Q, \E$//;
18407:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
18408:                             }
18409:                         } else {
18410:                             $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>';
18411:                         }
18412:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
18413:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
18414:                         } else {
18415:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
18416:                         }
18417:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
18418:                             my $output;
18419:                             if (ref($types) eq 'ARRAY') {
18420:                                 foreach my $type (@{$types}) {
18421:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
18422:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
18423:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
18424:                                         } else {
18425:                                             $output .= $usertypes->{$type}.' -- '.
18426:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
18427:                                         }
18428:                                     }
18429:                                 }
18430:                             }
18431:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
18432:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
18433:                                     $output .= $othertitle.' -- '.&mt('none');
18434:                                 } else {
18435:                                     $output .= $othertitle.' -- '.
18436:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
18437:                                 }
18438:                             }
18439:                             if ($output) {
18440:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
18441:                             } else {
18442:                                 $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>';
18443:                             }
18444:                         } else {
18445:                             $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>';
18446:                         }
18447:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
18448:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
18449:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
18450:                             } else {
18451:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18452:                             }
18453:                         } else {
18454:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18455:                         }
18456:                         if ($confighash{'passwords'}{'resetremove'}) {
18457:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
18458:                         } else {
18459:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
18460:                         }
18461:                         if ($confighash{'passwords'}{'resetcustom'}) {
18462:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
18463:                                                                             &mt('custom text'),600,500,undef,undef,
18464:                                                                             undef,undef,'background-color:#ffffff');
18465:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
18466:                         } else {
18467:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
18468:                         }
18469:                     } elsif ($key eq 'intauth') {
18470:                         foreach my $item ('cost','switch','check') {
18471:                             my $value = $save_defaults{$key.'_'.$item};
18472:                             if ($item eq 'switch') {
18473:                                 my %optiondesc = &Apache::lonlocal::texthash (
18474:                                                      0 => 'No',
18475:                                                      1 => 'Yes',
18476:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
18477:                                                  );
18478:                                 if ($value =~ /^(0|1|2)$/) {
18479:                                     $value = $optiondesc{$value};
18480:                                 } else {
18481:                                     $value = &mt('none -- defaults to No');
18482:                                 }
18483:                             } elsif ($item eq 'check') {
18484:                                 my %optiondesc = &Apache::lonlocal::texthash (
18485:                                                      0 => 'No',
18486:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
18487:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
18488:                                                  );
18489:                                 if ($value =~ /^(0|1|2)$/) {
18490:                                     $value = $optiondesc{$value};
18491:                                 } else {
18492:                                     $value = &mt('none -- defaults to No');
18493:                                 }
18494:                             }
18495:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
18496:                         }
18497:                     } elsif ($key eq 'rules') {
18498:                         foreach my $rule ('min','max','expire','numsaved') {
18499:                             if ($confighash{'passwords'}{$rule} eq '') {
18500:                                 if ($rule eq 'min') {
18501:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
18502:                                                    ' '.&mt('Default of [_1] will be used',
18503:                                                            $Apache::lonnet::passwdmin).'</li>';
18504:                                 } else {
18505:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
18506:                                 }
18507:                             } else {
18508:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
18509:                             }
18510:                         }
18511:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
18512:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
18513:                                 my %rulenames = &Apache::lonlocal::texthash(
18514:                                                      uc => 'At least one upper case letter',
18515:                                                      lc => 'At least one lower case letter',
18516:                                                      num => 'At least one number',
18517:                                                      spec => 'At least one non-alphanumeric',
18518:                                                    );
18519:                                 my $needed = '<ul><li>'.
18520:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
18521:                                              '</li></ul>'; 
18522:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
18523:                             } else {
18524:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18525:                             }
18526:                         } else {
18527:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18528:                         }
18529:                     } elsif ($key eq 'crsownerchg') {
18530:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
18531:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
18532:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
18533:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18534:                             } else {
18535:                                 my %crsownerstr;
18536:                                 foreach my $item ('by','for') {
18537:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
18538:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
18539:                                             if ($type eq 'default') {
18540:                                                 $crsownerstr{$item} .= $othertitle.', ';
18541:                                             } elsif ($usertypes->{$type} ne '') {
18542:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
18543:                                             }
18544:                                         }
18545:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
18546:                                     }
18547:                                 }
18548:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
18549:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
18550:                             }
18551:                         } else {
18552:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18553:                         }
18554:                     }
18555:                     $resulttext .= '</ul></li>';
18556:                 }
18557:             }
18558:             $resulttext .= '</ul>';
18559:         } else {
18560:             $resulttext = &mt('No changes made to password settings');
18561:         }
18562:         my $cachetime = 24*60*60;
18563:         if ($updatedefaults) {
18564:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18565:             if (ref($lastactref) eq 'HASH') {
18566:                 $lastactref->{'domdefaults'} = 1;
18567:             }
18568:         }
18569:         if ($updateconf) {
18570:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
18571:             if (ref($lastactref) eq 'HASH') {
18572:                 $lastactref->{'passwdconf'} = 1;
18573:             }
18574:         }
18575:     } else {
18576:         $resulttext = '<span class="LC_error">'.
18577:             &mt('An error occurred: [_1]',$putresult).'</span>';
18578:     }
18579:     if ($errors) {
18580:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18581:                        $errors.'</ul></p>';
18582:     }
18583:     return $resulttext;
18584: }
18585: 
18586: sub password_rule_changes {
18587:     my ($prefix,$newvalues,$current,$changes) = @_;
18588:     return unless ((ref($newvalues) eq 'HASH') &&
18589:                    (ref($current) eq 'HASH') &&
18590:                    (ref($changes) eq 'HASH'));
18591:     my (@rules,%staticdefaults);
18592:     if ($prefix eq 'passwords') {
18593:         @rules = ('min','max','expire','numsaved');
18594:     } elsif ($prefix eq 'secrets') {
18595:         @rules = ('min','max');
18596:     }
18597:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18598:     foreach my $rule (@rules) {
18599:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
18600:         my $ruleok;
18601:         if ($rule eq 'expire') {
18602:             if (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+(|\.\d*)$/) &&
18603:                 ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18604:                 $ruleok = 1;
18605:             }
18606:         } elsif ($rule eq 'min') {
18607:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
18608:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
18609:                     $ruleok = 1;
18610:                 }
18611:             }
18612:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
18613:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18614:             $ruleok = 1;
18615:         }
18616:         if ($ruleok) {
18617:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
18618:             if (exists($current->{$rule})) {
18619:                 if ($newvalues->{$rule} ne $current->{$rule}) {
18620:                     $changes->{'rules'} = 1;
18621:                 }
18622:             } elsif ($rule eq 'min') {
18623:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
18624:                     $changes->{'rules'} = 1;
18625:                 }
18626:             } else {
18627:                 $changes->{'rules'} = 1;
18628:             }
18629:         } elsif (exists($current->{$rule})) {
18630:             $changes->{'rules'} = 1;
18631:         }
18632:     }
18633:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
18634:     my @chars;
18635:     foreach my $item (sort(@posschars)) {
18636:         if ($item =~ /^(uc|lc|num|spec)$/) {
18637:             push(@chars,$item);
18638:         }
18639:     }
18640:     $newvalues->{'chars'} = \@chars;
18641:     unless ($changes->{'rules'}) {
18642:         if (ref($current->{'chars'}) eq 'ARRAY') {
18643:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
18644:             if (@diffs > 0) {
18645:                 $changes->{'rules'} = 1;
18646:             }
18647:         } else {
18648:             if (@chars > 0) {
18649:                 $changes->{'rules'} = 1;
18650:             }
18651:         }
18652:     }
18653:     return;
18654: }
18655: 
18656: sub modify_usercreation {
18657:     my ($dom,%domconfig) = @_;
18658:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
18659:     my $warningmsg;
18660:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18661:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18662:             if ($key eq 'cancreate') {
18663:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18664:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18665:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
18666:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18667:                         } else {
18668:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18669:                         }
18670:                     }
18671:                 }
18672:             } elsif ($key eq 'email_rule') {
18673:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18674:             } else {
18675:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18676:             }
18677:         }
18678:     }
18679:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
18680:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
18681:     my @contexts = ('author','course','requestcrs');
18682:     foreach my $item(@contexts) {
18683:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
18684:     }
18685:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
18686:         foreach my $item (@contexts) {
18687:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
18688:                 push(@{$changes{'cancreate'}},$item);
18689:             }
18690:         }
18691:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
18692:         foreach my $item (@contexts) {
18693:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
18694:                 if ($cancreate{$item} ne 'any') {
18695:                     push(@{$changes{'cancreate'}},$item);
18696:                 }
18697:             } else {
18698:                 if ($cancreate{$item} ne 'none') {
18699:                     push(@{$changes{'cancreate'}},$item);
18700:                 }
18701:             }
18702:         }
18703:     } else {
18704:         foreach my $item (@contexts)  {
18705:             push(@{$changes{'cancreate'}},$item);
18706:         }
18707:     }
18708: 
18709:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
18710:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
18711:             if (!grep(/^\Q$type\E$/,@username_rule)) {
18712:                 push(@{$changes{'username_rule'}},$type);
18713:             }
18714:         }
18715:         foreach my $type (@username_rule) {
18716:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
18717:                 push(@{$changes{'username_rule'}},$type);
18718:             }
18719:         }
18720:     } else {
18721:         push(@{$changes{'username_rule'}},@username_rule);
18722:     }
18723: 
18724:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
18725:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
18726:             if (!grep(/^\Q$type\E$/,@id_rule)) {
18727:                 push(@{$changes{'id_rule'}},$type);
18728:             }
18729:         }
18730:         foreach my $type (@id_rule) {
18731:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
18732:                 push(@{$changes{'id_rule'}},$type);
18733:             }
18734:         }
18735:     } else {
18736:         push(@{$changes{'id_rule'}},@id_rule);
18737:     }
18738: 
18739:     my @authen_contexts = ('author','course','domain');
18740:     my @authtypes = ('int','krb4','krb5','loc','lti');
18741:     my %authhash;
18742:     foreach my $item (@authen_contexts) {
18743:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
18744:         foreach my $auth (@authtypes) {
18745:             if (grep(/^\Q$auth\E$/,@authallowed)) {
18746:                 $authhash{$item}{$auth} = 1;
18747:             } else {
18748:                 $authhash{$item}{$auth} = 0;
18749:             }
18750:         }
18751:     }
18752:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
18753:         foreach my $item (@authen_contexts) {
18754:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
18755:                 foreach my $auth (@authtypes) {
18756:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
18757:                         push(@{$changes{'authtypes'}},$item);
18758:                         last;
18759:                     }
18760:                 }
18761:             }
18762:         }
18763:     } else {
18764:         foreach my $item (@authen_contexts) {
18765:             push(@{$changes{'authtypes'}},$item);
18766:         }
18767:     }
18768: 
18769:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
18770:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
18771:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
18772:     $save_usercreate{'id_rule'} = \@id_rule;
18773:     $save_usercreate{'username_rule'} = \@username_rule,
18774:     $save_usercreate{'authtypes'} = \%authhash;
18775: 
18776:     my %usercreation_hash =  (
18777:         usercreation     => \%save_usercreate,
18778:     );
18779: 
18780:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
18781:                                              $dom);
18782: 
18783:     if ($putresult eq 'ok') {
18784:         if (keys(%changes) > 0) {
18785:             $resulttext = &mt('Changes made:').'<ul>';
18786:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
18787:                 my %lt = &usercreation_types();
18788:                 foreach my $type (@{$changes{'cancreate'}}) {
18789:                     my $chgtext = $lt{$type}.', ';
18790:                     if ($cancreate{$type} eq 'none') {
18791:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
18792:                     } elsif ($cancreate{$type} eq 'any') {
18793:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
18794:                     } elsif ($cancreate{$type} eq 'official') {
18795:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
18796:                     } elsif ($cancreate{$type} eq 'unofficial') {
18797:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
18798:                     }
18799:                     $resulttext .= '<li>'.$chgtext.'</li>';
18800:                 }
18801:             }
18802:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
18803:                 my ($rules,$ruleorder) = 
18804:                     &Apache::lonnet::inst_userrules($dom,'username');
18805:                 my $chgtext = '<ul>';
18806:                 foreach my $type (@username_rule) {
18807:                     if (ref($rules->{$type}) eq 'HASH') {
18808:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
18809:                     }
18810:                 }
18811:                 $chgtext .= '</ul>';
18812:                 if (@username_rule > 0) {
18813:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
18814:                 } else {
18815:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
18816:                 }
18817:             }
18818:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
18819:                 my ($idrules,$idruleorder) = 
18820:                     &Apache::lonnet::inst_userrules($dom,'id');
18821:                 my $chgtext = '<ul>';
18822:                 foreach my $type (@id_rule) {
18823:                     if (ref($idrules->{$type}) eq 'HASH') {
18824:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
18825:                     }
18826:                 }
18827:                 $chgtext .= '</ul>';
18828:                 if (@id_rule > 0) {
18829:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
18830:                 } else {
18831:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
18832:                 }
18833:             }
18834:             my %authname = &authtype_names();
18835:             my %context_title = &context_names();
18836:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
18837:                 my $chgtext = '<ul>';
18838:                 foreach my $type (@{$changes{'authtypes'}}) {
18839:                     my @allowed;
18840:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
18841:                     foreach my $auth (@authtypes) {
18842:                         if ($authhash{$type}{$auth}) {
18843:                             push(@allowed,$authname{$auth});
18844:                         }
18845:                     }
18846:                     if (@allowed > 0) {
18847:                         $chgtext .= join(', ',@allowed).'</li>';
18848:                     } else {
18849:                         $chgtext .= &mt('none').'</li>';
18850:                     }
18851:                 }
18852:                 $chgtext .= '</ul>';
18853:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
18854:                 $resulttext .= '</li>';
18855:             }
18856:             $resulttext .= '</ul>';
18857:         } else {
18858:             $resulttext = &mt('No changes made to user creation settings');
18859:         }
18860:     } else {
18861:         $resulttext = '<span class="LC_error">'.
18862:             &mt('An error occurred: [_1]',$putresult).'</span>';
18863:     }
18864:     if ($warningmsg ne '') {
18865:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18866:     }
18867:     return $resulttext;
18868: }
18869: 
18870: sub modify_selfcreation {
18871:     my ($dom,$lastactref,%domconfig) = @_;
18872:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
18873:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
18874:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18875:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
18876:     if (ref($typesref) eq 'ARRAY') {
18877:         @types = @{$typesref};
18878:     }
18879:     if (ref($usertypesref) eq 'HASH') {
18880:         %usertypes = %{$usertypesref};
18881:     }
18882:     $usertypes{'default'} = $othertitle;
18883: #
18884: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
18885: #
18886:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18887:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18888:             if ($key eq 'cancreate') {
18889:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18890:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18891:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
18892:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
18893:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
18894:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
18895:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
18896:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
18897:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18898:                         } else {
18899:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18900:                         }
18901:                     }
18902:                 }
18903:             } elsif ($key eq 'email_rule') {
18904:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18905:             } else {
18906:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18907:             }
18908:         }
18909:     }
18910: #
18911: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
18912: #
18913:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
18914:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
18915:             if ($key eq 'selfcreate') {
18916:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
18917:             } else {
18918:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
18919:             }
18920:         }
18921:     }
18922: #
18923: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
18924: #
18925:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18926:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
18927:             if ($key eq 'inststatusguest') {
18928:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
18929:             } else {
18930:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
18931:             }
18932:         }
18933:     }
18934: 
18935:     my @contexts = ('selfcreate');
18936:     @{$cancreate{'selfcreate'}} = ();
18937:     %{$cancreate{'emailusername'}} = ();
18938:     if (@types) {
18939:         @{$cancreate{'statustocreate'}} = ();
18940:     }
18941:     %{$cancreate{'selfcreateprocessing'}} = ();
18942:     %{$cancreate{'shibenv'}} = ();
18943:     %{$cancreate{'emailverified'}} = ();
18944:     %{$cancreate{'emailoptions'}} = ();
18945:     %{$cancreate{'emaildomain'}} = ();
18946:     my %selfcreatetypes = (
18947:                              sso   => 'users authenticated by institutional single sign on',
18948:                              login => 'users authenticated by institutional log-in',
18949:                              email => 'users verified by e-mail',
18950:                           );
18951: #
18952: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
18953: # is permitted.
18954: #
18955:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
18956: 
18957:     my (@statuses,%email_rule);
18958:     foreach my $item ('login','sso','email') {
18959:         if ($item eq 'email') {
18960:             if ($env{'form.cancreate_email'}) {
18961:                 if (@types) {
18962:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
18963:                     foreach my $status (@poss_statuses) {
18964:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
18965:                             push(@statuses,$status);
18966:                         }
18967:                     }
18968:                     $save_inststatus{'inststatusguest'} = \@statuses;
18969:                 } else {
18970:                     push(@statuses,'default');
18971:                 }
18972:                 if (@statuses) {
18973:                     my %curr_rule;
18974:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
18975:                         foreach my $type (@statuses) {
18976:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
18977:                         }
18978:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
18979:                         foreach my $type (@statuses) {
18980:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
18981:                         }
18982:                     }
18983:                     push(@{$cancreate{'selfcreate'}},'email');
18984:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
18985:                     my %curremaildom;
18986:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
18987:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
18988:                     }
18989:                     foreach my $type (@statuses) {
18990:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
18991:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
18992:                         }
18993:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
18994:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
18995:                         }
18996:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
18997: #
18998: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
18999: #
19000:                             my $chosen = $1;
19001:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
19002:                                 my $emaildom;
19003:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
19004:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
19005:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
19006:                                     if (ref($curremaildom{$type}) eq 'HASH') {
19007:                                         if (exists($curremaildom{$type}{$chosen})) {
19008:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
19009:                                                 push(@{$changes{'cancreate'}},'emaildomain');
19010:                                             }
19011:                                         } elsif ($emaildom ne '') {
19012:                                             push(@{$changes{'cancreate'}},'emaildomain');
19013:                                         }
19014:                                     } elsif ($emaildom ne '') {
19015:                                         push(@{$changes{'cancreate'}},'emaildomain');
19016:                                     } 
19017:                                 }
19018:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19019:                             } elsif ($chosen eq 'custom') {
19020:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
19021:                                 $email_rule{$type} = [];
19022:                                 if (ref($emailrules) eq 'HASH') {
19023:                                     foreach my $rule (@possemail_rules) {
19024:                                         if (exists($emailrules->{$rule})) {
19025:                                             push(@{$email_rule{$type}},$rule);
19026:                                         }
19027:                                     }
19028:                                 }
19029:                                 if (@{$email_rule{$type}}) {
19030:                                     $cancreate{'emailoptions'}{$type} = 'custom';
19031:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
19032:                                         if (@{$curr_rule{$type}} > 0) {
19033:                                             foreach my $rule (@{$curr_rule{$type}}) {
19034:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
19035:                                                     push(@{$changes{'email_rule'}},$type);
19036:                                                 }
19037:                                             }
19038:                                         }
19039:                                         foreach my $type (@{$email_rule{$type}}) {
19040:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
19041:                                                 push(@{$changes{'email_rule'}},$type);
19042:                                             }
19043:                                         }
19044:                                     } else {
19045:                                         push(@{$changes{'email_rule'}},$type);
19046:                                     }
19047:                                 }
19048:                             } else {
19049:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
19050:                             }
19051:                         }
19052:                     }
19053:                     if (@types) {
19054:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19055:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
19056:                             if (@changed) {
19057:                                 push(@{$changes{'inststatus'}},'inststatusguest');
19058:                             }
19059:                         } else {
19060:                             push(@{$changes{'inststatus'}},'inststatusguest');
19061:                         }
19062:                     }
19063:                 } else {
19064:                     delete($env{'form.cancreate_email'});
19065:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19066:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19067:                             push(@{$changes{'inststatus'}},'inststatusguest');
19068:                         }
19069:                     }
19070:                 }
19071:             } else {
19072:                 $save_inststatus{'inststatusguest'} = [];
19073:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
19074:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
19075:                         push(@{$changes{'inststatus'}},'inststatusguest');
19076:                     }
19077:                 }
19078:             }
19079:         } else {
19080:             if ($env{'form.cancreate_'.$item}) {
19081:                 push(@{$cancreate{'selfcreate'}},$item);
19082:             }
19083:         }
19084:     }
19085:     my (%userinfo,%savecaptcha);
19086:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
19087: #
19088: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
19089: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
19090: #
19091: 
19092:     if ($env{'form.cancreate_email'}) {
19093:         push(@contexts,'emailusername');
19094:         if (@statuses) {
19095:             foreach my $type (@statuses) {
19096:                 if (ref($infofields) eq 'ARRAY') {
19097:                     foreach my $field (@{$infofields}) {
19098:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
19099:                             $cancreate{'emailusername'}{$type}{$field} = $1;
19100:                         }
19101:                     }
19102:                 }
19103:             }
19104:         }
19105: #
19106: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
19107: # queued requests for self-creation of account verified by e-mail.
19108: #
19109: 
19110:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
19111:         @approvalnotify = sort(@approvalnotify);
19112:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
19113:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19114:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
19115:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
19116:                     push(@{$changes{'cancreate'}},'notify');
19117:                 }
19118:             } else {
19119:                 if ($cancreate{'notify'}{'approval'}) {
19120:                     push(@{$changes{'cancreate'}},'notify');
19121:                 }
19122:             }
19123:         } elsif ($cancreate{'notify'}{'approval'}) {
19124:             push(@{$changes{'cancreate'}},'notify');
19125:         }
19126: 
19127:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
19128:     }
19129: #  
19130: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
19131: # institutional log-in.
19132: #
19133:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
19134:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
19135:                ($domdefaults{'auth_def'} eq 'localauth'))) {
19136:             $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.').' '.
19137:                           &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.');
19138:         }
19139:     }
19140:     my @fields = ('lastname','firstname','middlename','generation',
19141:                   'permanentemail','id');
19142:     my @shibfields = (@fields,'inststatus');
19143:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19144: #
19145: # Where usernames may created for institutional log-in and/or institutional single sign on:
19146: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
19147: # may self-create accounts 
19148: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
19149: # which the user may supply, if institutional data is unavailable.
19150: #
19151:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
19152:         if (@types) {
19153:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
19154:             push(@contexts,'statustocreate');
19155:             foreach my $type (@types) {
19156:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
19157:                 foreach my $field (@fields) {
19158:                     if (grep(/^\Q$field\E$/,@modifiable)) {
19159:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
19160:                     } else {
19161:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
19162:                     }
19163:                 }
19164:             }
19165:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
19166:                 foreach my $type (@types) {
19167:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
19168:                         foreach my $field (@fields) {
19169:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
19170:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
19171:                                 push(@{$changes{'selfcreate'}},$type);
19172:                                 last;
19173:                             }
19174:                         }
19175:                     }
19176:                 }
19177:             } else {
19178:                 foreach my $type (@types) {
19179:                     push(@{$changes{'selfcreate'}},$type);
19180:                 }
19181:             }
19182:         }
19183:         foreach my $field (@shibfields) {
19184:             if ($env{'form.shibenv_'.$field} ne '') {
19185:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
19186:             }
19187:         }
19188:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19189:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
19190:                 foreach my $field (@shibfields) {
19191:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
19192:                         push(@{$changes{'cancreate'}},'shibenv');
19193:                     }
19194:                 }
19195:             } else {
19196:                 foreach my $field (@shibfields) {
19197:                     if ($env{'form.shibenv_'.$field}) {
19198:                         push(@{$changes{'cancreate'}},'shibenv');
19199:                         last;
19200:                     }
19201:                 }
19202:             }
19203:         }
19204:     }
19205:     foreach my $item (@contexts) {
19206:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
19207:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
19208:                 if (ref($cancreate{$item}) eq 'ARRAY') {
19209:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
19210:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19211:                             push(@{$changes{'cancreate'}},$item);
19212:                         }
19213:                     }
19214:                 }
19215:             }
19216:             if (ref($cancreate{$item}) eq 'ARRAY') {
19217:                 foreach my $type (@{$cancreate{$item}}) {
19218:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
19219:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19220:                             push(@{$changes{'cancreate'}},$item);
19221:                         }
19222:                     }
19223:                 }
19224:             }
19225:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
19226:             if (ref($cancreate{$item}) eq 'HASH') {
19227:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
19228:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19229:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
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:                         }
19236:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19237:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19238:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19239:                                 push(@{$changes{'cancreate'}},$item);
19240:                             }
19241:                         }
19242:                     }
19243:                 }
19244:                 foreach my $type (keys(%{$cancreate{$item}})) {
19245:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19246:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19247:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19248:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19249:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19250:                                         push(@{$changes{'cancreate'}},$item);
19251:                                     }
19252:                                 }
19253:                             } else {
19254:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19255:                                     push(@{$changes{'cancreate'}},$item);
19256:                                 }
19257:                             }
19258:                         }
19259:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19260:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19261:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19262:                                 push(@{$changes{'cancreate'}},$item);
19263:                             }
19264:                         }
19265:                     }
19266:                 }
19267:             }
19268:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
19269:             if (ref($cancreate{$item}) eq 'ARRAY') {
19270:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
19271:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19272:                         push(@{$changes{'cancreate'}},$item);
19273:                     }
19274:                 }
19275:             }
19276:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19277:             if (ref($cancreate{$item}) eq 'HASH') {
19278:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19279:                     push(@{$changes{'cancreate'}},$item);
19280:                 }
19281:             }
19282:         } elsif ($item eq 'emailusername') {
19283:             if (ref($cancreate{$item}) eq 'HASH') {
19284:                 foreach my $type (keys(%{$cancreate{$item}})) {
19285:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19286:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19287:                             if ($cancreate{$item}{$type}{$field}) {
19288:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19289:                                     push(@{$changes{'cancreate'}},$item);
19290:                                 }
19291:                                 last;
19292:                             }
19293:                         }
19294:                     }
19295:                 }
19296:             }
19297:         }
19298:     }
19299: #
19300: # Populate %save_usercreate hash with updates to self-creation configuration.
19301: #
19302:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
19303:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
19304:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
19305:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
19306:     if (ref($cancreate{'notify'}) eq 'HASH') {
19307:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
19308:     }
19309:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
19310:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
19311:     }
19312:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
19313:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
19314:     }
19315:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
19316:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
19317:     }
19318:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
19319:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
19320:     }
19321:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19322:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
19323:     }
19324:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
19325:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
19326:     }
19327:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
19328:     $save_usercreate{'email_rule'} = \%email_rule;
19329: 
19330:     my %userconfig_hash = (
19331:             usercreation     => \%save_usercreate,
19332:             usermodification => \%save_usermodify,
19333:             inststatus       => \%save_inststatus,
19334:     );
19335: 
19336:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
19337:                                              $dom);
19338: #
19339: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
19340: #
19341:     if ($putresult eq 'ok') {
19342:         if (keys(%changes) > 0) {
19343:             $resulttext = &mt('Changes made:').'<ul>';
19344:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
19345:                 my %lt = &selfcreation_types();
19346:                 foreach my $type (@{$changes{'cancreate'}}) {
19347:                     my $chgtext = '';
19348:                     if ($type eq 'selfcreate') {
19349:                         if (@{$cancreate{$type}} == 0) {
19350:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
19351:                         } else {
19352:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
19353:                                         '<ul>';
19354:                             foreach my $case (@{$cancreate{$type}}) {
19355:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
19356:                             }
19357:                             $chgtext .= '</ul>';
19358:                             if (ref($cancreate{$type}) eq 'ARRAY') {
19359:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
19360:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19361:                                         if (@{$cancreate{'statustocreate'}} == 0) {
19362:                                             $chgtext .= '<span class="LC_warning">'.
19363:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
19364:                                                         '</span><br />';
19365:                                         }
19366:                                     }
19367:                                 }
19368:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
19369:                                     if (!@statuses) {
19370:                                         $chgtext .= '<span class="LC_warning">'.
19371:                                                     &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.").
19372:                                                     '</span><br />';
19373: 
19374:                                     }
19375:                                 }
19376:                             }
19377:                         }
19378:                     } elsif ($type eq 'shibenv') {
19379:                         if (keys(%{$cancreate{$type}}) == 0) {
19380:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
19381:                         } else {
19382:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
19383:                                         '<ul>';
19384:                             foreach my $field (@shibfields) {
19385:                                 next if ($cancreate{$type}{$field} eq '');
19386:                                 if ($field eq 'inststatus') {
19387:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
19388:                                 } else {
19389:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
19390:                                 }
19391:                             }
19392:                             $chgtext .= '</ul>';
19393:                         }
19394:                     } elsif ($type eq 'statustocreate') {
19395:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
19396:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
19397:                             if (@{$cancreate{'selfcreate'}} > 0) {
19398:                                 if (@{$cancreate{'statustocreate'}} == 0) {
19399:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
19400:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
19401:                                         $chgtext .= '<br />'.
19402:                                                     '<span class="LC_warning">'.
19403:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
19404:                                                     '</span>';
19405:                                     }
19406:                                 } elsif (keys(%usertypes) > 0) {
19407:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19408:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
19409:                                     } else {
19410:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
19411:                                     }
19412:                                     $chgtext .= '<ul>';
19413:                                     foreach my $case (@{$cancreate{$type}}) {
19414:                                         if ($case eq 'default') {
19415:                                             $chgtext .= '<li>'.$othertitle.'</li>';
19416:                                         } else {
19417:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
19418:                                         }
19419:                                     }
19420:                                     $chgtext .= '</ul>';
19421:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19422:                                         $chgtext .= '<span class="LC_warning">'.
19423:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
19424:                                                     '</span>';
19425:                                     }
19426:                                 }
19427:                             } else {
19428:                                 if (@{$cancreate{$type}} == 0) {
19429:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
19430:                                 } else {
19431:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
19432:                                 }
19433:                             }
19434:                             $chgtext .= '<br />';
19435:                         }
19436:                     } elsif ($type eq 'selfcreateprocessing') {
19437:                         my %choices = &Apache::lonlocal::texthash (
19438:                                                                     automatic => 'Automatic approval',
19439:                                                                     approval  => 'Queued for approval',
19440:                                                                   );
19441:                         if (@types) {
19442:                             if (@statuses) {
19443:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
19444:                                             '<ul>';
19445:                                 foreach my $status (@statuses) {
19446:                                     if ($status eq 'default') {
19447:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19448:                                     } else {
19449:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19450:                                     }
19451:                                 }
19452:                                 $chgtext .= '</ul>';
19453:                             }
19454:                         } else {
19455:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
19456:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
19457:                         }
19458:                     } elsif ($type eq 'emailverified') {
19459:                         my %options = &Apache::lonlocal::texthash (
19460:                                                                     all   => 'Same as e-mail',
19461:                                                                     first => 'Omit @domain',
19462:                                                                     free  => 'Free to choose',
19463:                                                                   );
19464:                         if (@types) {
19465:                             if (@statuses) {
19466:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
19467:                                             '<ul>';
19468:                                 foreach my $status (@statuses) {
19469:                                     if ($status eq 'default') {
19470:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19471:                                     } else {
19472:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19473:                                     }
19474:                                 }
19475:                                 $chgtext .= '</ul>';
19476:                             }
19477:                         } else {
19478:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
19479:                                             $options{$cancreate{'emailverified'}{'default'}});
19480:                         }
19481:                     } elsif ($type eq 'emailoptions') {
19482:                         my %options = &Apache::lonlocal::texthash (
19483:                                                                     any     => 'Any e-mail',
19484:                                                                     inst    => 'Institutional only',
19485:                                                                     noninst => 'Non-institutional only',
19486:                                                                     custom  => 'Custom restrictions',
19487:                                                                   );
19488:                         if (@types) {
19489:                             if (@statuses) {
19490:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
19491:                                             '<ul>';
19492:                                 foreach my $status (@statuses) {
19493:                                     if ($type eq 'default') {
19494:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19495:                                     } else {
19496:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19497:                                     }
19498:                                 }
19499:                                 $chgtext .= '</ul>';
19500:                             }
19501:                         } else {
19502:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
19503:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
19504:                             } else {
19505:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
19506:                                                 $options{$cancreate{'emailoptions'}{'default'}});
19507:                             }
19508:                         }
19509:                     } elsif ($type eq 'emaildomain') {
19510:                         my $output;
19511:                         if (@statuses) {
19512:                             foreach my $type (@statuses) {
19513:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
19514:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
19515:                                         if ($type eq 'default') {
19516:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19517:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} 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 needs to end: [_1]",
19521:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
19522:                                             }
19523:                                         } else {
19524:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19525:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} 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 needs to end: [_1]",
19529:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
19530:                                             }
19531:                                         }
19532:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
19533:                                         if ($type eq 'default') {
19534:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19535:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19536:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19537:                                             } else {
19538:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
19539:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
19540:                                             }
19541:                                         } else {
19542:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19543:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19544:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19545:                                             } else {
19546:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
19547:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
19548:                                             }
19549:                                         }
19550:                                     }
19551:                                 }
19552:                             }
19553:                         }
19554:                         if ($output ne '') {
19555:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
19556:                                         '<ul>'.$output.'</ul>';
19557:                         }
19558:                     } elsif ($type eq 'captcha') {
19559:                         if ($savecaptcha{$type} eq 'notused') {
19560:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
19561:                         } else {
19562:                             my %captchas = &captcha_phrases();
19563:                             if ($captchas{$savecaptcha{$type}}) {
19564:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
19565:                             } else {
19566:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
19567:                             }
19568:                         }
19569:                     } elsif ($type eq 'recaptchakeys') {
19570:                         my ($privkey,$pubkey);
19571:                         if (ref($savecaptcha{$type}) eq 'HASH') {
19572:                             $pubkey = $savecaptcha{$type}{'public'};
19573:                             $privkey = $savecaptcha{$type}{'private'};
19574:                         }
19575:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
19576:                         if (!$pubkey) {
19577:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
19578:                         } else {
19579:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
19580:                         }
19581:                         if (!$privkey) {
19582:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
19583:                         } else {
19584:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
19585:                         }
19586:                         $chgtext .= '</ul>';
19587:                     } elsif ($type eq 'recaptchaversion') {
19588:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
19589:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
19590:                         }
19591:                     } elsif ($type eq 'emailusername') {
19592:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
19593:                             if (@statuses) {
19594:                                 foreach my $type (@statuses) {
19595:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
19596:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
19597:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
19598:                                                     '<ul>';
19599:                                             foreach my $field (@{$infofields}) {
19600:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
19601:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
19602:                                                 }
19603:                                             }
19604:                                             $chgtext .= '</ul>';
19605:                                         } else {
19606:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19607:                                         }
19608:                                     } else {
19609:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19610:                                     }
19611:                                 }
19612:                             }
19613:                         }
19614:                     } elsif ($type eq 'notify') {
19615:                         my $numapprove = 0;
19616:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
19617:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
19618:                                 if ($cancreate{'notify'}{'approval'}) {
19619:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
19620:                                     $numapprove ++;
19621:                                 }
19622:                             }
19623:                         }
19624:                         unless ($numapprove) {
19625:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
19626:                         }
19627:                     }
19628:                     if ($chgtext) {
19629:                         $resulttext .= '<li>'.$chgtext.'</li>';
19630:                     }
19631:                 }
19632:             }
19633:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
19634:                 my ($emailrules,$emailruleorder) =
19635:                     &Apache::lonnet::inst_userrules($dom,'email');
19636:                 foreach my $type (@{$changes{'email_rule'}}) {
19637:                     if (ref($email_rule{$type}) eq 'ARRAY') {
19638:                         my $chgtext = '<ul>';
19639:                         foreach my $rule (@{$email_rule{$type}}) {
19640:                             if (ref($emailrules->{$rule}) eq 'HASH') {
19641:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
19642:                             }
19643:                         }
19644:                         $chgtext .= '</ul>';
19645:                         my $typename;
19646:                         if (@types) {
19647:                             if ($type eq 'default') {
19648:                                 $typename = $othertitle;
19649:                             } else {
19650:                                 $typename = $usertypes{$type};
19651:                             } 
19652:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
19653:                         }
19654:                         if (@{$email_rule{$type}} > 0) {
19655:                             $resulttext .= '<li>'.
19656:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
19657:                                                $usertypes{$type}).
19658:                                            $chgtext.
19659:                                            '</li>';
19660:                         } else {
19661:                             $resulttext .= '<li>'.
19662:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
19663:                                            '</li>'.
19664:                                            &mt('(Affiliation: [_1])',$typename);
19665:                         }
19666:                     }
19667:                 }
19668:             }
19669:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
19670:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
19671:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
19672:                         my $chgtext = '<ul>';
19673:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
19674:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
19675:                         }
19676:                         $chgtext .= '</ul>';
19677:                         $resulttext .= '<li>'.
19678:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
19679:                                           $chgtext.
19680:                                        '</li>';
19681:                     } else {
19682:                         $resulttext .= '<li>'.
19683:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
19684:                                        '</li>';
19685:                     }
19686:                 }
19687:             }
19688:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
19689:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
19690:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19691:                 foreach my $type (@{$changes{'selfcreate'}}) {
19692:                     my $typename = $type;
19693:                     if (keys(%usertypes) > 0) {
19694:                         if ($usertypes{$type} ne '') {
19695:                             $typename = $usertypes{$type};
19696:                         }
19697:                     }
19698:                     my @modifiable;
19699:                     $resulttext .= '<li>'.
19700:                                     &mt('Self-creation of account by users with status: [_1]',
19701:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
19702:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
19703:                     foreach my $field (@fields) {
19704:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
19705:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
19706:                         }
19707:                     }
19708:                     if (@modifiable > 0) {
19709:                         $resulttext .= join(', ',@modifiable);
19710:                     } else {
19711:                         $resulttext .= &mt('none');
19712:                     }
19713:                     $resulttext .= '</li>';
19714:                 }
19715:                 $resulttext .= '</ul></li>';
19716:             }
19717:             $resulttext .= '</ul>';
19718:             my $cachetime = 24*60*60;
19719:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
19720:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19721:             if (ref($lastactref) eq 'HASH') {
19722:                 $lastactref->{'domdefaults'} = 1;
19723:             }
19724:         } else {
19725:             $resulttext = &mt('No changes made to self-creation settings');
19726:         }
19727:     } else {
19728:         $resulttext = '<span class="LC_error">'.
19729:             &mt('An error occurred: [_1]',$putresult).'</span>';
19730:     }
19731:     if ($warningmsg ne '') {
19732:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
19733:     }
19734:     return $resulttext;
19735: }
19736: 
19737: sub process_captcha {
19738:     my ($container,$changes,$newsettings,$currsettings) = @_;
19739:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
19740:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
19741:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
19742:         $newsettings->{'captcha'} = 'original';
19743:     }
19744:     my %current;
19745:     if (ref($currsettings) eq 'HASH') {
19746:         %current = %{$currsettings};
19747:     }
19748:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
19749:         if ($container eq 'cancreate') {
19750:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19751:                 push(@{$changes->{'cancreate'}},'captcha');
19752:             } elsif (!defined($changes->{'cancreate'})) {
19753:                 $changes->{'cancreate'} = ['captcha'];
19754:             }
19755:         } elsif ($container eq 'passwords') {
19756:             $changes->{'reset'} = 1;
19757:         } else {
19758:             $changes->{'captcha'} = 1;
19759:         }
19760:     }
19761:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
19762:     if ($newsettings->{'captcha'} eq 'recaptcha') {
19763:         $newpub = $env{'form.'.$container.'_recaptchapub'};
19764:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
19765:         $newpub =~ s/[^\w\-]//g;
19766:         $newpriv =~ s/[^\w\-]//g;
19767:         $newsettings->{'recaptchakeys'} = {
19768:                                              public  => $newpub,
19769:                                              private => $newpriv,
19770:                                           };
19771:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
19772:         $newversion =~ s/\D//g;
19773:         if ($newversion ne '2') {
19774:             $newversion = 1;
19775:         }
19776:         $newsettings->{'recaptchaversion'} = $newversion;
19777:     }
19778:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
19779:         $currpub = $current{'recaptchakeys'}{'public'};
19780:         $currpriv = $current{'recaptchakeys'}{'private'};
19781:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
19782:             $newsettings->{'recaptchakeys'} = {
19783:                                                  public  => '',
19784:                                                  private => '',
19785:                                               }
19786:         }
19787:     }
19788:     if ($current{'captcha'} eq 'recaptcha') {
19789:         $currversion = $current{'recaptchaversion'};
19790:         if ($currversion ne '2') {
19791:             $currversion = 1;
19792:         }
19793:     }
19794:     if ($currversion ne $newversion) {
19795:         if ($container eq 'cancreate') {
19796:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19797:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
19798:             } elsif (!defined($changes->{'cancreate'})) {
19799:                 $changes->{'cancreate'} = ['recaptchaversion'];
19800:             }
19801:         } elsif ($container eq 'passwords') {
19802:             $changes->{'reset'} = 1;
19803:         } else {
19804:             $changes->{'recaptchaversion'} = 1;
19805:         }
19806:     }
19807:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
19808:         if ($container eq 'cancreate') {
19809:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19810:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
19811:             } elsif (!defined($changes->{'cancreate'})) {
19812:                 $changes->{'cancreate'} = ['recaptchakeys'];
19813:             }
19814:         } elsif ($container eq 'passwords') {
19815:             $changes->{'reset'} = 1;
19816:         } else {
19817:             $changes->{'recaptchakeys'} = 1;
19818:         }
19819:     }
19820:     return;
19821: }
19822: 
19823: sub modify_usermodification {
19824:     my ($dom,%domconfig) = @_;
19825:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
19826:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
19827:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
19828:             if ($key eq 'selfcreate') {
19829:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
19830:             } else {  
19831:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
19832:             }
19833:         }
19834:     }
19835:     my @contexts = ('author','course');
19836:     my %context_title = (
19837:                            author => 'In author context',
19838:                            course => 'In course context',
19839:                         );
19840:     my @fields = ('lastname','firstname','middlename','generation',
19841:                   'permanentemail','id');
19842:     my %roles = (
19843:                   author => ['ca','aa'],
19844:                   course => ['st','ep','ta','in','cr'],
19845:                 );
19846:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19847:     foreach my $context (@contexts) {
19848:         foreach my $role (@{$roles{$context}}) {
19849:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
19850:             foreach my $item (@fields) {
19851:                 if (grep(/^\Q$item\E$/,@modifiable)) {
19852:                     $modifyhash{$context}{$role}{$item} = 1;
19853:                 } else {
19854:                     $modifyhash{$context}{$role}{$item} = 0;
19855:                 }
19856:             }
19857:         }
19858:         if (ref($curr_usermodification{$context}) eq 'HASH') {
19859:             foreach my $role (@{$roles{$context}}) {
19860:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
19861:                     foreach my $field (@fields) {
19862:                         if ($modifyhash{$context}{$role}{$field} ne 
19863:                                 $curr_usermodification{$context}{$role}{$field}) {
19864:                             push(@{$changes{$context}},$role);
19865:                             last;
19866:                         }
19867:                     }
19868:                 }
19869:             }
19870:         } else {
19871:             foreach my $context (@contexts) {
19872:                 foreach my $role (@{$roles{$context}}) {
19873:                     push(@{$changes{$context}},$role);
19874:                 }
19875:             }
19876:         }
19877:     }
19878:     my %usermodification_hash =  (
19879:                                    usermodification => \%modifyhash,
19880:                                  );
19881:     my $putresult = &Apache::lonnet::put_dom('configuration',
19882:                                              \%usermodification_hash,$dom);
19883:     if ($putresult eq 'ok') {
19884:         if (keys(%changes) > 0) {
19885:             $resulttext = &mt('Changes made: ').'<ul>';
19886:             foreach my $context (@contexts) {
19887:                 if (ref($changes{$context}) eq 'ARRAY') {
19888:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
19889:                     if (ref($changes{$context}) eq 'ARRAY') {
19890:                         foreach my $role (@{$changes{$context}}) {
19891:                             my $rolename;
19892:                             if ($role eq 'cr') {
19893:                                 $rolename = &mt('Custom');
19894:                             } else {
19895:                                 $rolename = &Apache::lonnet::plaintext($role);
19896:                             }
19897:                             my @modifiable;
19898:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
19899:                             foreach my $field (@fields) {
19900:                                 if ($modifyhash{$context}{$role}{$field}) {
19901:                                     push(@modifiable,$fieldtitles{$field});
19902:                                 }
19903:                             }
19904:                             if (@modifiable > 0) {
19905:                                 $resulttext .= join(', ',@modifiable);
19906:                             } else {
19907:                                 $resulttext .= &mt('none'); 
19908:                             }
19909:                             $resulttext .= '</li>';
19910:                         }
19911:                         $resulttext .= '</ul></li>';
19912:                     }
19913:                 }
19914:             }
19915:             $resulttext .= '</ul>';
19916:         } else {
19917:             $resulttext = &mt('No changes made to user modification settings');
19918:         }
19919:     } else {
19920:         $resulttext = '<span class="LC_error">'.
19921:             &mt('An error occurred: [_1]',$putresult).'</span>';
19922:     }
19923:     return $resulttext;
19924: }
19925: 
19926: sub modify_defaults {
19927:     my ($dom,$lastactref,%domconfig) = @_;
19928:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
19929:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19930:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
19931:                  'portal_def');
19932:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
19933:     foreach my $item (@items) {
19934:         $newvalues{$item} = $env{'form.'.$item};
19935:         if ($item eq 'auth_def') {
19936:             if ($newvalues{$item} ne '') {
19937:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
19938:                     push(@errors,$item);
19939:                 }
19940:             }
19941:         } elsif ($item eq 'lang_def') {
19942:             if ($newvalues{$item} ne '') {
19943:                 if ($newvalues{$item} =~ /^(\w+)/) {
19944:                     my $langcode = $1;
19945:                     if ($langcode ne 'x_chef') {
19946:                         if (code2language($langcode) eq '') {
19947:                             push(@errors,$item);
19948:                         }
19949:                     }
19950:                 } else {
19951:                     push(@errors,$item);
19952:                 }
19953:             }
19954:         } elsif ($item eq 'timezone_def') {
19955:             if ($newvalues{$item} ne '') {
19956:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
19957:                     push(@errors,$item);   
19958:                 }
19959:             }
19960:         } elsif ($item eq 'datelocale_def') {
19961:             if ($newvalues{$item} ne '') {
19962:                 my @datelocale_ids = DateTime::Locale->ids();
19963:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
19964:                     push(@errors,$item);
19965:                 }
19966:             }
19967:         } elsif ($item eq 'portal_def') {
19968:             if ($newvalues{$item} ne '') {
19969:                 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])\/?$/) {
19970:                     push(@errors,$item);
19971:                 }
19972:             }
19973:         }
19974:         if (grep(/^\Q$item\E$/,@errors)) {
19975:             $newvalues{$item} = $domdefaults{$item};
19976:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
19977:             $changes{$item} = 1;
19978:         }
19979:         $domdefaults{$item} = $newvalues{$item};
19980:     }
19981:     my %staticdefaults = (
19982:                            'intauth_cost'   => 10,
19983:                            'intauth_check'  => 0,
19984:                            'intauth_switch' => 0,
19985:                          );
19986:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
19987:         if (exists($domdefaults{$item})) {
19988:             $newvalues{$item} = $domdefaults{$item};
19989:         } else {
19990:             $newvalues{$item} = $staticdefaults{$item};
19991:         }
19992:     }
19993:     my ($unamemaprules,$ruleorder);
19994:     my @possunamemaprules = &Apache::loncommon::get_env_multiple('form.unamemap_rule');
19995:     if (@possunamemaprules) {
19996:         ($unamemaprules,$ruleorder) =
19997:             &Apache::lonnet::inst_userrules($dom,'unamemap');
19998:         if ((ref($unamemaprules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
19999:             if (@{$ruleorder} > 0) {
20000:                 my %possrules;
20001:                 map { $possrules{$_} = 1; } @possunamemaprules;
20002:                 foreach my $rule (@{$ruleorder}) {
20003:                     if ($possrules{$rule}) {
20004:                         push(@{$newvalues{'unamemap_rule'}},$rule);
20005:                     }
20006:                 }
20007:             }
20008:         }
20009:     }
20010:     if (ref($domdefaults{'unamemap_rule'}) eq 'ARRAY') {
20011:         if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20012:             my @rulediffs = &Apache::loncommon::compare_arrays($domdefaults{'unamemap_rule'},
20013:                                                                $newvalues{'unamemap_rule'});
20014:             if (@rulediffs) {
20015:                 $changes{'unamemap_rule'} = 1;
20016:                 $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
20017:             }
20018:         } elsif (@{$domdefaults{'unamemap_rule'}} > 0) {
20019:             $changes{'unamemap_rule'} = 1;
20020:             delete($domdefaults{'unamemap_rule'});
20021:         }
20022:     } elsif (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20023:         if (@{$newvalues{'unamemap_rule'}} > 0) {
20024:             $changes{'unamemap_rule'} = 1;
20025:             $domdefaults{'unamemap_rule'} = $newvalues{'unamemap_rule'};
20026:         }
20027:     }
20028:     my %defaults_hash = (
20029:                          defaults => \%newvalues,
20030:                         );
20031:     my $title = &defaults_titles();
20032: 
20033:     my $currinststatus;
20034:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
20035:         $currinststatus = $domconfig{'inststatus'};
20036:     } else {
20037:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20038:         $currinststatus = {
20039:                              inststatustypes => $usertypes,
20040:                              inststatusorder => $types,
20041:                              inststatusguest => [],
20042:                           };
20043:     }
20044:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
20045:     my @allpos;
20046:     my %alltypes;
20047:     my @inststatusguest;
20048:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
20049:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
20050:             unless (grep(/^\Q$type\E$/,@todelete)) {
20051:                 push(@inststatusguest,$type);
20052:             }
20053:         }
20054:     }
20055:     my ($currtitles,$currorder);
20056:     if (ref($currinststatus) eq 'HASH') {
20057:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
20058:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
20059:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
20060:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
20061:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
20062:                     }
20063:                 }
20064:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
20065:                     my $position = $env{'form.inststatus_pos_'.$type};
20066:                     $position =~ s/\D+//g;
20067:                     $allpos[$position] = $type;
20068:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
20069:                     $alltypes{$type} =~ s/`//g;
20070:                 }
20071:             }
20072:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
20073:             $currtitles =~ s/,$//;
20074:         }
20075:     }
20076:     if ($env{'form.addinststatus'}) {
20077:         my $newtype = $env{'form.addinststatus'};
20078:         $newtype =~ s/\W//g;
20079:         unless (exists($alltypes{$newtype})) {
20080:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
20081:             $alltypes{$newtype} =~ s/`//g; 
20082:             my $position = $env{'form.addinststatus_pos'};
20083:             $position =~ s/\D+//g;
20084:             if ($position ne '') {
20085:                 $allpos[$position] = $newtype;
20086:             }
20087:         }
20088:     }
20089:     my @orderedstatus;
20090:     foreach my $type (@allpos) {
20091:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
20092:             push(@orderedstatus,$type);
20093:         }
20094:     }
20095:     foreach my $type (keys(%alltypes)) {
20096:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
20097:             delete($alltypes{$type});
20098:         }
20099:     }
20100:     $defaults_hash{'inststatus'} = {
20101:                                      inststatustypes => \%alltypes,
20102:                                      inststatusorder => \@orderedstatus,
20103:                                      inststatusguest => \@inststatusguest,
20104:                                    };
20105:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
20106:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
20107:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
20108:         }
20109:     }
20110:     if ($currorder ne join(',',@orderedstatus)) {
20111:         $changes{'inststatus'}{'inststatusorder'} = 1;
20112:     }
20113:     my $newtitles;
20114:     foreach my $item (@orderedstatus) {
20115:         $newtitles .= $alltypes{$item}.',';
20116:     }
20117:     $newtitles =~ s/,$//;
20118:     if ($currtitles ne $newtitles) {
20119:         $changes{'inststatus'}{'inststatustypes'} = 1;
20120:     }
20121:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
20122:                                              $dom);
20123:     if ($putresult eq 'ok') {
20124:         if (keys(%changes) > 0) {
20125:             $resulttext = &mt('Changes made:').'<ul>';
20126:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
20127:             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";
20128:             foreach my $item (sort(keys(%changes))) {
20129:                 if ($item eq 'inststatus') {
20130:                     if (ref($changes{'inststatus'}) eq 'HASH') {
20131:                         if (@orderedstatus) {
20132:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
20133:                             foreach my $type (@orderedstatus) { 
20134:                                 $resulttext .= $alltypes{$type}.', ';
20135:                             }
20136:                             $resulttext =~ s/, $//;
20137:                             $resulttext .= '</li>';
20138:                         } else {
20139:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
20140:                         }
20141:                     }
20142:                 } elsif ($item eq 'unamemap_rule') {
20143:                     if (ref($newvalues{'unamemap_rule'}) eq 'ARRAY') {
20144:                         my @rulenames;
20145:                         if (ref($unamemaprules) eq 'HASH') {
20146:                             foreach my $rule (@{$newvalues{'unamemap_rule'}}) {
20147:                                 if (ref($unamemaprules->{$rule}) eq 'HASH') {
20148:                                     push(@rulenames,$unamemaprules->{$rule}->{'name'});
20149:                                 }
20150:                             }
20151:                         }
20152:                         if (@rulenames) {
20153:                             $resulttext .= '<li>'.&mt('Mapping for missing usernames includes: [_1]',
20154:                                                      '<ul><li>'.join('</li><li>',@rulenames).'</li></ul>').
20155:                                            '</li>';
20156:                         } else {
20157:                             $resulttext .= '<li>'.&mt('No mapping for missing usernames via standard log-in').'</li>';
20158:                         }
20159:                     } else {
20160:                         $resulttext .= '<li>'.&mt('Mapping for missing usernames via standard log-in deleted').'</li>';
20161:                     }
20162:                 } else {
20163:                     my $value = $env{'form.'.$item};
20164:                     if ($value eq '') {
20165:                         $value = &mt('none');
20166:                     } elsif ($item eq 'auth_def') {
20167:                         my %authnames = &authtype_names();
20168:                         my %shortauth = (
20169:                                           internal   => 'int',
20170:                                           krb4       => 'krb4',
20171:                                           krb5       => 'krb5',
20172:                                           localauth  => 'loc',
20173:                                           lti        => 'lti',
20174:                         );
20175:                         $value = $authnames{$shortauth{$value}};
20176:                     }
20177:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
20178:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
20179:                 }
20180:             }
20181:             $resulttext .= '</ul>';
20182:             $mailmsgtext .= "\n";
20183:             my $cachetime = 24*60*60;
20184:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20185:             if (ref($lastactref) eq 'HASH') {
20186:                 $lastactref->{'domdefaults'} = 1;
20187:             }
20188:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
20189:                 my $notify = 1;
20190:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
20191:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
20192:                         $notify = 0;
20193:                     }
20194:                 }
20195:                 if ($notify) {
20196:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
20197:                                                "LON-CAPA Domain Settings Change - $dom",
20198:                                                $mailmsgtext);
20199:                 }
20200:             }
20201:         } else {
20202:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
20203:         }
20204:     } else {
20205:         $resulttext = '<span class="LC_error">'.
20206:             &mt('An error occurred: [_1]',$putresult).'</span>';
20207:     }
20208:     if (@errors > 0) {
20209:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
20210:         foreach my $item (@errors) {
20211:             $resulttext .= ' "'.$title->{$item}.'",';
20212:         }
20213:         $resulttext =~ s/,$//;
20214:     }
20215:     return $resulttext;
20216: }
20217: 
20218: sub modify_scantron {
20219:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20220:     my ($resulttext,%confhash,%changes,$errors);
20221:     my $custom = 'custom.tab';
20222:     my $default = 'default.tab';
20223:     my $servadm = $r->dir_config('lonAdmEMail');
20224:     my ($configuserok,$author_ok,$switchserver) =
20225:         &config_check($dom,$confname,$servadm);
20226:     if ($env{'form.scantronformat.filename'} ne '') {
20227:         my $error;
20228:         if ($configuserok eq 'ok') {
20229:             if ($switchserver) {
20230:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
20231:             } else {
20232:                 if ($author_ok eq 'ok') {
20233:                     my ($result,$scantronurl) =
20234:                         &publishlogo($r,'upload','scantronformat',$dom,
20235:                                      $confname,'scantron','','',$custom);
20236:                     if ($result eq 'ok') {
20237:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
20238:                         $changes{'scantronformat'} = 1;
20239:                     } else {
20240:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
20241:                     }
20242:                 } else {
20243:                     $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);
20244:                 }
20245:             }
20246:         } else {
20247:             $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);
20248:         }
20249:         if ($error) {
20250:             &Apache::lonnet::logthis($error);
20251:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
20252:         }
20253:     }
20254:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20255:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
20256:             if ($env{'form.scantronformat_del'}) {
20257:                 $confhash{'scantron'}{'scantronformat'} = '';
20258:                 $changes{'scantronformat'} = 1;
20259:             } else {
20260:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
20261:             }
20262:         }
20263:     }
20264:     my @options = ('hdr','pad','rem');
20265:     my @fields = &scantroncsv_fields();
20266:     my %titles = &scantronconfig_titles();
20267:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
20268:     my ($newdat,$currdat,%newcol,%currcol);
20269:     if (grep(/^dat$/,@formats)) {
20270:         $confhash{'scantron'}{config}{dat} = 1;
20271:         $newdat = 1;
20272:     } else {
20273:         $newdat = 0;
20274:     }
20275:     if (grep(/^csv$/,@formats)) {
20276:         my %bynum;
20277:         foreach my $field (@fields) {
20278:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
20279:                 my $posscol = $1;
20280:                 if (($posscol < 20) && (!$bynum{$posscol})) {
20281:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
20282:                     $bynum{$posscol} = $field;
20283:                     $newcol{$field} = $posscol;
20284:                 }
20285:             }
20286:         }
20287:         if (keys(%newcol)) {
20288:             foreach my $option (@options) {
20289:                 if ($env{'form.scantroncsv_'.$option}) {
20290:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
20291:                 }
20292:             }
20293:         }
20294:     }
20295:     $currdat = 1;
20296:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20297:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
20298:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
20299:                 $currdat = 0;
20300:             }
20301:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20302:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20303:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
20304:                 }
20305:             }
20306:         }
20307:     }
20308:     if ($currdat != $newdat) {
20309:         $changes{'config'} = 1;
20310:     } else {
20311:         foreach my $field (@fields) {
20312:             if ($currcol{$field} ne '') {
20313:                 if ($currcol{$field} ne $newcol{$field}) {
20314:                     $changes{'config'} = 1;
20315:                     last;
20316:                 }
20317:             } elsif ($newcol{$field} ne '') {
20318:                 $changes{'config'} = 1;
20319:                 last;
20320:             }
20321:         }
20322:     }
20323:     if (keys(%confhash) > 0) {
20324:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
20325:                                                  $dom);
20326:         if ($putresult eq 'ok') {
20327:             if (keys(%changes) > 0) {
20328:                 if (ref($confhash{'scantron'}) eq 'HASH') {
20329:                     $resulttext = &mt('Changes made:').'<ul>';
20330:                     if ($changes{'scantronformat'}) {
20331:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
20332:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
20333:                         } else {
20334:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
20335:                         }
20336:                     }
20337:                     if ($changes{'config'}) {
20338:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
20339:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
20340:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
20341:                             }
20342:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20343:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20344:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
20345:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
20346:                                         foreach my $field (@fields) {
20347:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
20348:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
20349:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
20350:                                             }
20351:                                         }
20352:                                         $resulttext .= '</ul></li>';
20353:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
20354:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
20355:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
20356:                                                 foreach my $option (@options) {
20357:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
20358:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
20359:                                                     }
20360:                                                 }
20361:                                                 $resulttext .= '</ul></li>';
20362:                                             }
20363:                                         }
20364:                                     }
20365:                                 }
20366:                             }
20367:                         } else {
20368:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
20369:                         }
20370:                     }
20371:                     $resulttext .= '</ul>';
20372:                 } else {
20373:                     $resulttext = &mt('Changes made to bubblesheet format file.');
20374:                 }
20375:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
20376:                 if (ref($lastactref) eq 'HASH') {
20377:                     $lastactref->{'domainconfig'} = 1;
20378:                 }
20379:             } else {
20380:                 $resulttext = &mt('No changes made to bubblesheet format settings');
20381:             }
20382:         } else {
20383:             $resulttext = '<span class="LC_error">'.
20384:                 &mt('An error occurred: [_1]',$putresult).'</span>';
20385:         }
20386:     } else {
20387:         $resulttext = &mt('No changes made to bubblesheet format file'); 
20388:     }
20389:     if ($errors) {
20390:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
20391:                        $errors.'</ul></p>';
20392:     }
20393:     return $resulttext;
20394: }
20395: 
20396: sub modify_coursecategories {
20397:     my ($dom,$lastactref,%domconfig) = @_;
20398:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
20399:         $cathash);
20400:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
20401:     my @catitems = ('unauth','auth');
20402:     my @cattypes = ('std','domonly','codesrch','none');
20403:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20404:         $cathash = $domconfig{'coursecategories'}{'cats'};
20405:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
20406:             $changes{'togglecats'} = 1;
20407:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
20408:         }
20409:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
20410:             $changes{'categorize'} = 1;
20411:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
20412:         }
20413:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
20414:             $changes{'togglecatscomm'} = 1;
20415:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
20416:         }
20417:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
20418:             $changes{'categorizecomm'} = 1;
20419:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
20420: 
20421:         }
20422:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
20423:             $changes{'togglecatsplace'} = 1;
20424:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
20425:         }
20426:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
20427:             $changes{'categorizeplace'} = 1;
20428:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
20429:         }
20430:         foreach my $item (@catitems) {
20431:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20432:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
20433:                     $changes{$item} = 1;
20434:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20435:                 }
20436:             }
20437:         }
20438:     } else {
20439:         $changes{'togglecats'} = 1;
20440:         $changes{'categorize'} = 1;
20441:         $changes{'togglecatscomm'} = 1;
20442:         $changes{'categorizecomm'} = 1;
20443:         $changes{'togglecatsplace'} = 1;
20444:         $changes{'categorizeplace'} = 1;
20445:         $domconfig{'coursecategories'} = {
20446:                                              togglecats => $env{'form.togglecats'},
20447:                                              categorize => $env{'form.categorize'},
20448:                                              togglecatscomm => $env{'form.togglecatscomm'},
20449:                                              categorizecomm => $env{'form.categorizecomm'},
20450:                                              togglecatsplace => $env{'form.togglecatsplace'},
20451:                                              categorizeplace => $env{'form.categorizeplace'},
20452:                                          };
20453:         foreach my $item (@catitems) {
20454:             if ($env{'form.coursecat_'.$item} ne 'std') {
20455:                 $changes{$item} = 1;
20456:             }
20457:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20458:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20459:             }
20460:         }
20461:     }
20462:     if (ref($cathash) eq 'HASH') {
20463:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
20464:             push (@deletecategory,'instcode::0');
20465:         }
20466:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
20467:             push(@deletecategory,'communities::0');
20468:         }
20469:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
20470:             push(@deletecategory,'placement::0');
20471:         }
20472:     }
20473:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
20474:     if (ref($cathash) eq 'HASH') {
20475:         if (@deletecategory > 0) {
20476:             #FIXME Need to remove category from all courses using a deleted category 
20477:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
20478:             foreach my $item (@deletecategory) {
20479:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
20480:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
20481:                     $deletions{$item} = 1;
20482:                     &recurse_cat_deletes($item,$cathash,\%deletions);
20483:                 }
20484:             }
20485:         }
20486:         foreach my $item (keys(%{$cathash})) {
20487:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
20488:             if ($cathash->{$item} ne $env{'form.'.$item}) {
20489:                 $reorderings{$item} = 1;
20490:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
20491:             }
20492:             if ($env{'form.addcategory_name_'.$item} ne '') {
20493:                 my $newcat = $env{'form.addcategory_name_'.$item};
20494:                 my $newdepth = $depth+1;
20495:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20496:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
20497:                 $adds{$newitem} = 1; 
20498:             }
20499:             if ($env{'form.subcat_'.$item} ne '') {
20500:                 my $newcat = $env{'form.subcat_'.$item};
20501:                 my $newdepth = $depth+1;
20502:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20503:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
20504:                 $adds{$newitem} = 1;
20505:             }
20506:         }
20507:     }
20508:     if ($env{'form.instcode'} eq '1') {
20509:         if (ref($cathash) eq 'HASH') {
20510:             my $newitem = 'instcode::0';
20511:             if ($cathash->{$newitem} eq '') {  
20512:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20513:                 $adds{$newitem} = 1;
20514:             }
20515:         } else {
20516:             my $newitem = 'instcode::0';
20517:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20518:             $adds{$newitem} = 1;
20519:         }
20520:     }
20521:     if ($env{'form.communities'} eq '1') {
20522:         if (ref($cathash) eq 'HASH') {
20523:             my $newitem = 'communities::0';
20524:             if ($cathash->{$newitem} eq '') {
20525:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20526:                 $adds{$newitem} = 1;
20527:             }
20528:         } else {
20529:             my $newitem = 'communities::0';
20530:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20531:             $adds{$newitem} = 1;
20532:         }
20533:     }
20534:     if ($env{'form.placement'} eq '1') {
20535:         if (ref($cathash) eq 'HASH') {
20536:             my $newitem = 'placement::0';
20537:             if ($cathash->{$newitem} eq '') {
20538:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20539:                 $adds{$newitem} = 1;
20540:             }
20541:         } else {
20542:             my $newitem = 'placement::0';
20543:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20544:             $adds{$newitem} = 1;
20545:         }
20546:     }
20547:     if ($env{'form.addcategory_name'} ne '') {
20548:         if (($env{'form.addcategory_name'} ne 'instcode') &&
20549:             ($env{'form.addcategory_name'} ne 'communities') &&
20550:             ($env{'form.addcategory_name'} ne 'placement')) {
20551:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
20552:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
20553:             $adds{$newitem} = 1;
20554:         }
20555:     }
20556:     my $putresult;
20557:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20558:         if (keys(%deletions) > 0) {
20559:             foreach my $key (keys(%deletions)) {
20560:                 if ($predelallitems{$key} ne '') {
20561:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
20562:                 }
20563:             }
20564:         }
20565:         my (@chkcats,@chktrails,%chkallitems);
20566:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
20567:         if (ref($chkcats[0]) eq 'ARRAY') {
20568:             my $depth = 0;
20569:             my $chg = 0;
20570:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
20571:                 my $name = $chkcats[0][$i];
20572:                 my $item;
20573:                 if ($name eq '') {
20574:                     $chg ++;
20575:                 } else {
20576:                     $item = &escape($name).'::0';
20577:                     if ($chg) {
20578:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
20579:                     }
20580:                     $depth ++; 
20581:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
20582:                     $depth --;
20583:                 }
20584:             }
20585:         }
20586:     }
20587:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20588:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
20589:         if ($putresult eq 'ok') {
20590:             my %title = (
20591:                          togglecats     => 'Show/Hide a course in catalog',
20592:                          categorize     => 'Assign a category to a course',
20593:                          togglecatscomm => 'Show/Hide a community in catalog',
20594:                          categorizecomm => 'Assign a category to a community',
20595:                         );
20596:             my %level = (
20597:                          dom  => 'set in Domain ("Modify Course/Community")',
20598:                          crs  => 'set in Course ("Course Configuration")',
20599:                          comm => 'set in Community ("Community Configuration")',
20600:                          none     => 'No catalog',
20601:                          std      => 'Standard catalog',
20602:                          domonly  => 'Domain-only catalog',
20603:                          codesrch => 'Code search form',
20604:                         );
20605:             $resulttext = &mt('Changes made:').'<ul>';
20606:             if ($changes{'togglecats'}) {
20607:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
20608:             }
20609:             if ($changes{'categorize'}) {
20610:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
20611:             }
20612:             if ($changes{'togglecatscomm'}) {
20613:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
20614:             }
20615:             if ($changes{'categorizecomm'}) {
20616:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
20617:             }
20618:             if ($changes{'unauth'}) {
20619:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
20620:             }
20621:             if ($changes{'auth'}) {
20622:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
20623:             }
20624:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20625:                 my $cathash;
20626:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20627:                     $cathash = $domconfig{'coursecategories'}{'cats'};
20628:                 } else {
20629:                     $cathash = {};
20630:                 } 
20631:                 my (@cats,@trails,%allitems);
20632:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
20633:                 if (keys(%deletions) > 0) {
20634:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
20635:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
20636:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
20637:                     }
20638:                     $resulttext .= '</ul></li>';
20639:                 }
20640:                 if (keys(%reorderings) > 0) {
20641:                     my %sort_by_trail;
20642:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
20643:                     foreach my $key (keys(%reorderings)) {
20644:                         if ($allitems{$key} ne '') {
20645:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20646:                         }
20647:                     }
20648:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20649:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20650:                     }
20651:                     $resulttext .= '</ul></li>';
20652:                 }
20653:                 if (keys(%adds) > 0) {
20654:                     my %sort_by_trail;
20655:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
20656:                     foreach my $key (keys(%adds)) {
20657:                         if ($allitems{$key} ne '') {
20658:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20659:                         }
20660:                     }
20661:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20662:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20663:                     }
20664:                     $resulttext .= '</ul></li>';
20665:                 }
20666:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
20667:                 if (ref($lastactref) eq 'HASH') {
20668:                     $lastactref->{'cats'} = 1;
20669:                 }
20670:             }
20671:             $resulttext .= '</ul>';
20672:             if ($changes{'unauth'} || $changes{'auth'}) {
20673:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20674:                 if ($changes{'auth'}) {
20675:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
20676:                 }
20677:                 if ($changes{'unauth'}) {
20678:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
20679:                 }
20680:                 my $cachetime = 24*60*60;
20681:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20682:                 if (ref($lastactref) eq 'HASH') {
20683:                     $lastactref->{'domdefaults'} = 1;
20684:                 }
20685:             }
20686:         } else {
20687:             $resulttext = '<span class="LC_error">'.
20688:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20689:         }
20690:     } else {
20691:         $resulttext = &mt('No changes made to course and community categories');
20692:     }
20693:     return $resulttext;
20694: }
20695: 
20696: sub modify_serverstatuses {
20697:     my ($dom,%domconfig) = @_;
20698:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
20699:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
20700:         %currserverstatus = %{$domconfig{'serverstatuses'}};
20701:     }
20702:     my @pages = &serverstatus_pages();
20703:     foreach my $type (@pages) {
20704:         $newserverstatus{$type}{'namedusers'} = '';
20705:         $newserverstatus{$type}{'machines'} = '';
20706:         if (defined($env{'form.'.$type.'_namedusers'})) {
20707:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
20708:             my @okusers;
20709:             foreach my $user (@users) {
20710:                 my ($uname,$udom) = split(/:/,$user);
20711:                 if (($udom =~ /^$match_domain$/) &&   
20712:                     (&Apache::lonnet::domain($udom)) &&
20713:                     ($uname =~ /^$match_username$/)) {
20714:                     if (!grep(/^\Q$user\E/,@okusers)) {
20715:                         push(@okusers,$user);
20716:                     }
20717:                 }
20718:             }
20719:             if (@okusers > 0) {
20720:                  @okusers = sort(@okusers);
20721:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
20722:             }
20723:         }
20724:         if (defined($env{'form.'.$type.'_machines'})) {
20725:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
20726:             my @okmachines;
20727:             foreach my $ip (@machines) {
20728:                 my @parts = split(/\./,$ip);
20729:                 next if (@parts < 4);
20730:                 my $badip = 0;
20731:                 for (my $i=0; $i<4; $i++) {
20732:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
20733:                         $badip = 1;
20734:                         last;
20735:                     }
20736:                 }
20737:                 if (!$badip) {
20738:                     push(@okmachines,$ip);     
20739:                 }
20740:             }
20741:             @okmachines = sort(@okmachines);
20742:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
20743:         }
20744:     }
20745:     my %serverstatushash =  (
20746:                                 serverstatuses => \%newserverstatus,
20747:                             );
20748:     foreach my $type (@pages) {
20749:         foreach my $setting ('namedusers','machines') {
20750:             my (@current,@new);
20751:             if (ref($currserverstatus{$type}) eq 'HASH') {
20752:                 if ($currserverstatus{$type}{$setting} ne '') { 
20753:                     @current = split(/,/,$currserverstatus{$type}{$setting});
20754:                 }
20755:             }
20756:             if ($newserverstatus{$type}{$setting} ne '') {
20757:                 @new = split(/,/,$newserverstatus{$type}{$setting});
20758:             }
20759:             if (@current > 0) {
20760:                 if (@new > 0) {
20761:                     foreach my $item (@current) {
20762:                         if (!grep(/^\Q$item\E$/,@new)) {
20763:                             $changes{$type}{$setting} = 1;
20764:                             last;
20765:                         }
20766:                     }
20767:                     foreach my $item (@new) {
20768:                         if (!grep(/^\Q$item\E$/,@current)) {
20769:                             $changes{$type}{$setting} = 1;
20770:                             last;
20771:                         }
20772:                     }
20773:                 } else {
20774:                     $changes{$type}{$setting} = 1;
20775:                 }
20776:             } elsif (@new > 0) {
20777:                 $changes{$type}{$setting} = 1;
20778:             }
20779:         }
20780:     }
20781:     if (keys(%changes) > 0) {
20782:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
20783:         my $putresult = &Apache::lonnet::put_dom('configuration',
20784:                                                  \%serverstatushash,$dom);
20785:         if ($putresult eq 'ok') {
20786:             $resulttext .= &mt('Changes made:').'<ul>';
20787:             foreach my $type (@pages) {
20788:                 if (ref($changes{$type}) eq 'HASH') {
20789:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
20790:                     if ($changes{$type}{'namedusers'}) {
20791:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
20792:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
20793:                         } else {
20794:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
20795:                         }
20796:                     }
20797:                     if ($changes{$type}{'machines'}) {
20798:                         if ($newserverstatus{$type}{'machines'} eq '') {
20799:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
20800:                         } else {
20801:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
20802:                         }
20803: 
20804:                     }
20805:                     $resulttext .= '</ul></li>';
20806:                 }
20807:             }
20808:             $resulttext .= '</ul>';
20809:         } else {
20810:             $resulttext = '<span class="LC_error">'.
20811:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
20812: 
20813:         }
20814:     } else {
20815:         $resulttext = &mt('No changes made to access to server status pages');
20816:     }
20817:     return $resulttext;
20818: }
20819: 
20820: sub modify_helpsettings {
20821:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20822:     my ($resulttext,$errors,%changes,%helphash);
20823:     my %defaultchecked = ('submitbugs' => 'on');
20824:     my @offon = ('off','on');
20825:     my @toggles = ('submitbugs');
20826:     my %current = ('submitbugs' => '',
20827:                    'adhoc'      => {},
20828:                   );
20829:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
20830:         %current = %{$domconfig{'helpsettings'}};
20831:     }
20832:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20833:     foreach my $item (@toggles) {
20834:         if ($defaultchecked{$item} eq 'on') { 
20835:             if ($current{$item} eq '') {
20836:                 if ($env{'form.'.$item} eq '0') {
20837:                     $changes{$item} = 1;
20838:                 }
20839:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20840:                 $changes{$item} = 1;
20841:             }
20842:         } elsif ($defaultchecked{$item} eq 'off') {
20843:             if ($current{$item} eq '') {
20844:                 if ($env{'form.'.$item} eq '1') {
20845:                     $changes{$item} = 1;
20846:                 }
20847:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20848:                 $changes{$item} = 1;
20849:             }
20850:         }
20851:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
20852:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
20853:         }
20854:     }
20855:     my $maxnum = $env{'form.helproles_maxnum'};
20856:     my $confname = $dom.'-domainconfig';
20857:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
20858:     my (@allpos,%newsettings,%changedprivs,$newrole);
20859:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20860:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
20861:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
20862:     my %lt = &Apache::lonlocal::texthash(
20863:                     s      => 'system',
20864:                     d      => 'domain',
20865:                     order  => 'Display order',
20866:                     access => 'Role usage',
20867:                     all    => 'All with domain helpdesk or helpdesk assistant role',
20868:                     dh     => 'All with domain helpdesk role',
20869:                     da     => 'All with domain helpdesk assistant role',
20870:                     none   => 'None',
20871:                     status => 'Determined based on institutional status',
20872:                     inc    => 'Include all, but exclude specific personnel',
20873:                     exc    => 'Exclude all, but include specific personnel',
20874:     );
20875:     for (my $num=0; $num<=$maxnum; $num++) {
20876:         my ($prefix,$identifier,$rolename,%curr);
20877:         if ($num == $maxnum) {
20878:             next unless ($env{'form.newcusthelp'} == $maxnum);
20879:             $identifier = 'custhelp'.$num;
20880:             $prefix = 'helproles_'.$num;
20881:             $rolename = $env{'form.custhelpname'.$num};
20882:             $rolename=~s/[^A-Za-z0-9]//gs;
20883:             next if ($rolename eq '');
20884:             next if (exists($existing{'rolesdef_'.$rolename}));
20885:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20886:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20887:                                                      $newprivs{'c'},$confname,$dom);
20888:             if ($result ne 'ok') {
20889:                 $errors .= '<li><span class="LC_error">'.
20890:                            &mt('An error occurred storing the new custom role: [_1]',
20891:                            $result).'</span></li>';
20892:                 next;
20893:             } else {
20894:                 $changedprivs{$rolename} = \%newprivs;
20895:                 $newrole = $rolename;
20896:             }
20897:         } else {
20898:             $prefix = 'helproles_'.$num;
20899:             $rolename = $env{'form.'.$prefix};
20900:             next if ($rolename eq '');
20901:             next unless (exists($existing{'rolesdef_'.$rolename}));
20902:             $identifier = 'custhelp'.$num;
20903:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20904:             my %currprivs;
20905:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
20906:                 split(/\_/,$existing{'rolesdef_'.$rolename});
20907:             foreach my $level ('c','d','s') {
20908:                 if ($newprivs{$level} ne $currprivs{$level}) {
20909:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20910:                                                              $newprivs{'c'},$confname,$dom);
20911:                     if ($result ne 'ok') {
20912:                         $errors .= '<li><span class="LC_error">'.
20913:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
20914:                                        $rolename,$result).'</span></li>';
20915:                     } else {
20916:                         $changedprivs{$rolename} = \%newprivs;
20917:                     }
20918:                     last;
20919:                 }
20920:             }
20921:             if (ref($current{'adhoc'}) eq 'HASH') {
20922:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20923:                     %curr = %{$current{'adhoc'}{$rolename}};
20924:                 }
20925:             }
20926:         }
20927:         my $newpos = $env{'form.'.$prefix.'_pos'};
20928:         $newpos =~ s/\D+//g;
20929:         $allpos[$newpos] = $rolename;
20930:         my $newdesc = $env{'form.'.$prefix.'_desc'};
20931:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
20932:         if ($curr{'desc'}) {
20933:             if ($curr{'desc'} ne $newdesc) {
20934:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
20935:                 $newsettings{$rolename}{'desc'} = $newdesc;
20936:             }
20937:         } elsif ($newdesc ne '') {
20938:             $changes{'customrole'}{$rolename}{'desc'} = 1;
20939:             $newsettings{$rolename}{'desc'} = $newdesc;
20940:         }
20941:         my $access = $env{'form.'.$prefix.'_access'};
20942:         if (grep(/^\Q$access\E$/,@accesstypes)) {
20943:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
20944:             if ($access eq 'status') {
20945:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
20946:                 if (scalar(@statuses) == 0) {
20947:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
20948:                 } else {
20949:                     my (@shownstatus,$numtypes);
20950:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20951:                     if (ref($types) eq 'ARRAY') {
20952:                         $numtypes = scalar(@{$types});
20953:                         foreach my $type (sort(@statuses)) {
20954:                             if ($type eq 'default') {
20955:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20956:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
20957:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20958:                                 push(@shownstatus,$usertypes->{$type});
20959:                             }
20960:                         }
20961:                     }
20962:                     if (grep(/^default$/,@statuses)) {
20963:                         push(@shownstatus,$othertitle);
20964:                     }
20965:                     if (scalar(@shownstatus) == 1+$numtypes) {
20966:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
20967:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
20968:                     } else {
20969:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
20970:                         if (ref($curr{'status'}) eq 'ARRAY') {
20971:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20972:                             if (@diffs) {
20973:                                 $changes{'customrole'}{$rolename}{$access} = 1;
20974:                             }
20975:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20976:                             $changes{'customrole'}{$rolename}{$access} = 1;
20977:                         }
20978:                     }
20979:                 }
20980:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
20981:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
20982:                 my @newspecstaff;
20983:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20984:                 foreach my $person (sort(@personnel)) {
20985:                     if ($domhelpdesk{$person}) {
20986:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
20987:                     }
20988:                 }
20989:                 if (ref($curr{$access}) eq 'ARRAY') {
20990:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20991:                     if (@diffs) {
20992:                         $changes{'customrole'}{$rolename}{$access} = 1;
20993:                     }
20994:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20995:                     $changes{'customrole'}{$rolename}{$access} = 1;
20996:                 }
20997:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20998:                     my ($uname,$udom) = split(/:/,$person);
20999:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
21000:                 }
21001:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
21002:             }
21003:         } else {
21004:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
21005:         }
21006:         unless ($curr{'access'} eq $access) {
21007:             $changes{'customrole'}{$rolename}{'access'} = 1;
21008:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
21009:         }
21010:     }
21011:     if (@allpos > 0) {
21012:         my $idx = 0;
21013:         foreach my $rolename (@allpos) {
21014:             if ($rolename ne '') {
21015:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
21016:                 if (ref($current{'adhoc'}) eq 'HASH') {
21017:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
21018:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
21019:                             $changes{'customrole'}{$rolename}{'order'} = 1;
21020:                             $newsettings{$rolename}{'order'} = $idx+1;
21021:                         }
21022:                     }
21023:                 }
21024:                 $idx ++;
21025:             }
21026:         }
21027:     }
21028:     my $putresult;
21029:     if (keys(%changes) > 0) {
21030:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
21031:         if ($putresult eq 'ok') {
21032:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
21033:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
21034:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
21035:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
21036:                 }
21037:             }
21038:             my $cachetime = 24*60*60;
21039:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21040:             if (ref($lastactref) eq 'HASH') {
21041:                 $lastactref->{'domdefaults'} = 1;
21042:             }
21043:         } else {
21044:             $errors .= '<li><span class="LC_error">'.
21045:                        &mt('An error occurred storing the settings: [_1]',
21046:                            $putresult).'</span></li>';
21047:         }
21048:     }
21049:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
21050:         $resulttext = &mt('Changes made:').'<ul>';
21051:         my (%shownprivs,@levelorder);
21052:         @levelorder = ('c','d','s');
21053:         if ((keys(%changes)) && ($putresult eq 'ok')) {
21054:             foreach my $item (sort(keys(%changes))) {
21055:                 if ($item eq 'submitbugs') {
21056:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
21057:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
21058:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
21059:                 } elsif ($item eq 'customrole') {
21060:                     if (ref($changes{'customrole'}) eq 'HASH') {
21061:                         my @keyorder = ('order','desc','access','status','exc','inc');
21062:                         my %keytext = &Apache::lonlocal::texthash(
21063:                                                                    order  => 'Order',
21064:                                                                    desc   => 'Role description',
21065:                                                                    access => 'Role usage',
21066:                                                                    status => 'Allowed institutional types',
21067:                                                                    exc    => 'Allowed personnel',
21068:                                                                    inc    => 'Disallowed personnel',
21069:                         );
21070:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
21071:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
21072:                                 if ($role eq $newrole) {
21073:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
21074:                                                               $role).'<ul>';
21075:                                 } else {
21076:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21077:                                                               $role).'<ul>';
21078:                                 }
21079:                                 foreach my $key (@keyorder) {
21080:                                     if ($changes{'customrole'}{$role}{$key}) {
21081:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
21082:                                                                   $keytext{$key},$newsettings{$role}{$key}).
21083:                                                        '</li>';
21084:                                     }
21085:                                 }
21086:                                 if (ref($changedprivs{$role}) eq 'HASH') {
21087:                                     $shownprivs{$role} = 1;
21088:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
21089:                                     foreach my $level (@levelorder) {
21090:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21091:                                             next if ($item eq '');
21092:                                             my ($priv) = split(/\&/,$item,2);
21093:                                             if (&Apache::lonnet::plaintext($priv)) {
21094:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21095:                                                 unless ($level eq 'c') {
21096:                                                     $resulttext .= ' ('.$lt{$level}.')';
21097:                                                 }
21098:                                                 $resulttext .= '</li>';
21099:                                             }
21100:                                         }
21101:                                     }
21102:                                     $resulttext .= '</ul>';
21103:                                 }
21104:                                 $resulttext .= '</ul></li>';
21105:                             }
21106:                         }
21107:                     }
21108:                 }
21109:             }
21110:         }
21111:         if (keys(%changedprivs)) {
21112:             foreach my $role (sort(keys(%changedprivs))) {
21113:                 unless ($shownprivs{$role}) {
21114:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
21115:                                               $role).'<ul>'.
21116:                                    '<li>'.&mt('Privileges set to :').'<ul>';
21117:                     foreach my $level (@levelorder) {
21118:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
21119:                             next if ($item eq '');
21120:                             my ($priv) = split(/\&/,$item,2);
21121:                             if (&Apache::lonnet::plaintext($priv)) {
21122:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
21123:                                 unless ($level eq 'c') {
21124:                                     $resulttext .= ' ('.$lt{$level}.')';
21125:                                 }
21126:                                 $resulttext .= '</li>';
21127:                             }
21128:                         }
21129:                     }
21130:                     $resulttext .= '</ul></li></ul></li>';
21131:                 }
21132:             }
21133:         }
21134:         $resulttext .= '</ul>';
21135:     } else {
21136:         $resulttext = &mt('No changes made to help settings');
21137:     }
21138:     if ($errors) {
21139:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
21140:                                     $errors.'</ul>';
21141:     }
21142:     return $resulttext;
21143: }
21144: 
21145: sub modify_coursedefaults {
21146:     my ($dom,$lastactref,%domconfig) = @_;
21147:     my ($resulttext,$errors,%changes,%defaultshash);
21148:     my %defaultchecked = (
21149:                            'canuse_pdfforms' => 'off',
21150:                            'uselcmath'       => 'on',
21151:                            'usejsme'         => 'on',
21152:                            'inline_chem'     => 'on',
21153:                            'ltiauth'         => 'off',
21154:                          );
21155:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem','ltiauth');
21156:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
21157:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
21158:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
21159:                    'mysqltables_textbook','mysqltables_placement');
21160:     my @types = ('official','unofficial','community','textbook','placement');
21161:     my %staticdefaults = (
21162:                            anonsurvey_threshold => 10,
21163:                            uploadquota          => 500,
21164:                            postsubmit           => 60,
21165:                            mysqltables          => 172800,
21166:                          );
21167:     my %texoptions = (
21168:                         MathJax  => 'MathJax',
21169:                         mimetex  => &mt('Convert to Images'),
21170:                         tth      => &mt('TeX to HTML'),
21171:                      );
21172:     $defaultshash{'coursedefaults'} = {};
21173: 
21174:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
21175:         if ($domconfig{'coursedefaults'} eq '') {
21176:             $domconfig{'coursedefaults'} = {};
21177:         }
21178:     }
21179: 
21180:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
21181:         foreach my $item (@toggles) {
21182:             if ($defaultchecked{$item} eq 'on') {
21183:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21184:                     ($env{'form.'.$item} eq '0')) {
21185:                     $changes{$item} = 1;
21186:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21187:                     $changes{$item} = 1;
21188:                 }
21189:             } elsif ($defaultchecked{$item} eq 'off') {
21190:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21191:                     ($env{'form.'.$item} eq '1')) {
21192:                     $changes{$item} = 1;
21193:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21194:                     $changes{$item} = 1;
21195:                 }
21196:             }
21197:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
21198:         }
21199:         foreach my $item (@numbers) {
21200:             my ($currdef,$newdef);
21201:             $newdef = $env{'form.'.$item};
21202:             if ($item eq 'anonsurvey_threshold') {
21203:                 $currdef = $domconfig{'coursedefaults'}{$item};
21204:                 $newdef =~ s/\D//g;
21205:                 if ($newdef eq '' || $newdef < 1) {
21206:                     $newdef = 1;
21207:                 }
21208:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
21209:             } else {
21210:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
21211:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
21212:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
21213:                 }
21214:                 $newdef =~ s/[^\w.\-]//g;
21215:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
21216:             }
21217:             if ($currdef ne $newdef) {
21218:                 if ($item eq 'anonsurvey_threshold') {
21219:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
21220:                         $changes{$item} = 1;
21221:                     }
21222:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
21223:                     my $setting = $1;
21224:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
21225:                         $changes{$setting} = 1;
21226:                     }
21227:                 }
21228:             }
21229:         }
21230:         my $texengine;
21231:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
21232:             $texengine = $env{'form.texengine'};
21233:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
21234:             if ($currdef eq '') {
21235:                 unless ($texengine eq $Apache::lonnet::deftex) {
21236:                     $changes{'texengine'} = 1;
21237:                 }
21238:             } elsif ($currdef ne $texengine) {
21239:                 $changes{'texengine'} = 1;
21240:             }
21241:         }
21242:         if ($texengine ne '') {
21243:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
21244:         }
21245:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
21246:         my @currclonecode;
21247:         if (ref($currclone) eq 'HASH') {
21248:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
21249:                 @currclonecode = @{$currclone->{'instcode'}};
21250:             }
21251:         }
21252:         my $newclone;
21253:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
21254:             $newclone = $env{'form.canclone'};
21255:         }
21256:         if ($newclone eq 'instcode') {
21257:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
21258:             my (%codedefaults,@code_order,@clonecode);
21259:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
21260:                                                     \@code_order);
21261:             foreach my $item (@code_order) {
21262:                 if (grep(/^\Q$item\E$/,@newcodes)) {
21263:                     push(@clonecode,$item);
21264:                 }
21265:             }
21266:             if (@clonecode) {
21267:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
21268:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
21269:                 if (@diffs) {
21270:                     $changes{'canclone'} = 1;
21271:                 }
21272:             } else {
21273:                 $newclone eq '';
21274:             }
21275:         } elsif ($newclone ne '') {
21276:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
21277:         }
21278:         if ($newclone ne $currclone) {
21279:             $changes{'canclone'} = 1;
21280:         }
21281:         my %credits;
21282:         foreach my $type (@types) {
21283:             unless ($type eq 'community') {
21284:                 $credits{$type} = $env{'form.'.$type.'_credits'};
21285:                 $credits{$type} =~ s/[^\d.]+//g;
21286:             }
21287:         }
21288:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
21289:             ($env{'form.coursecredits'} eq '1')) {
21290:             $changes{'coursecredits'} = 1;
21291:             foreach my $type (keys(%credits)) {
21292:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21293:             }
21294:         } else {
21295:             if ($env{'form.coursecredits'} eq '1') {
21296:                 foreach my $type (@types) {
21297:                     unless ($type eq 'community') {
21298:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
21299:                             $changes{'coursecredits'} = 1;
21300:                         }
21301:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21302:                     }
21303:                 }
21304:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21305:                 foreach my $type (@types) {
21306:                     unless ($type eq 'community') {
21307:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
21308:                             $changes{'coursecredits'} = 1;
21309:                             last;
21310:                         }
21311:                     }
21312:                 }
21313:             }
21314:         }
21315:         if ($env{'form.postsubmit'} eq '1') {
21316:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
21317:             my %currtimeout;
21318:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21319:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
21320:                     $changes{'postsubmit'} = 1;
21321:                 }
21322:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21323:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
21324:                 }
21325:             } else {
21326:                 $changes{'postsubmit'} = 1;
21327:             }
21328:             foreach my $type (@types) {
21329:                 my $timeout = $env{'form.'.$type.'_timeout'};
21330:                 $timeout =~ s/\D//g;
21331:                 if ($timeout == $staticdefaults{'postsubmit'}) {
21332:                     $timeout = '';
21333:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
21334:                     $timeout = '0';
21335:                 }
21336:                 unless ($timeout eq '') {
21337:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
21338:                 }
21339:                 if (exists($currtimeout{$type})) {
21340:                     if ($timeout ne $currtimeout{$type}) {
21341:                         $changes{'postsubmit'} = 1;
21342:                     }
21343:                 } elsif ($timeout ne '') {
21344:                     $changes{'postsubmit'} = 1;
21345:                 }
21346:             }
21347:         } else {
21348:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
21349:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21350:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
21351:                     $changes{'postsubmit'} = 1;
21352:                 }
21353:             } else {
21354:                 $changes{'postsubmit'} = 1;
21355:             }
21356:         }
21357:     }
21358:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21359:                                              $dom);
21360:     if ($putresult eq 'ok') {
21361:         if (keys(%changes) > 0) {
21362:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21363:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
21364:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
21365:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
21366:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'})) {
21367:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','inline_chem','texengine','ltiauth') {
21368:                     if ($changes{$item}) {
21369:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
21370:                     }
21371:                 }
21372:                 if ($changes{'coursecredits'}) {
21373:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21374:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
21375:                             $domdefaults{$type.'credits'} =
21376:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
21377:                         }
21378:                     }
21379:                 }
21380:                 if ($changes{'postsubmit'}) {
21381:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21382:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
21383:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21384:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
21385:                                 $domdefaults{$type.'postsubtimeout'} =
21386:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21387:                             }
21388:                         }
21389:                     }
21390:                 }
21391:                 if ($changes{'uploadquota'}) {
21392:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21393:                         foreach my $type (@types) {
21394:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
21395:                         }
21396:                     }
21397:                 }
21398:                 if ($changes{'canclone'}) {
21399:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21400:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21401:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
21402:                             if (@clonecodes) {
21403:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
21404:                             }
21405:                         }
21406:                     } else {
21407:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
21408:                     }
21409:                 }
21410:                 my $cachetime = 24*60*60;
21411:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21412:                 if (ref($lastactref) eq 'HASH') {
21413:                     $lastactref->{'domdefaults'} = 1;
21414:                 }
21415:             }
21416:             $resulttext = &mt('Changes made:').'<ul>';
21417:             foreach my $item (sort(keys(%changes))) {
21418:                 if ($item eq 'canuse_pdfforms') {
21419:                     if ($env{'form.'.$item} eq '1') {
21420:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
21421:                     } else {
21422:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
21423:                     }
21424:                 } elsif ($item eq 'uselcmath') {
21425:                     if ($env{'form.'.$item} eq '1') {
21426:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
21427:                     } else {
21428:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
21429:                     }
21430:                 } elsif ($item eq 'usejsme') {
21431:                     if ($env{'form.'.$item} eq '1') {
21432:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
21433:                     } else {
21434:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
21435:                     }
21436:                 } elsif ($item eq 'inline_chem') {
21437:                     if ($env{'form.'.$item} eq '1') {
21438:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
21439:                     } else {
21440:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
21441:                     }
21442:                 } elsif ($item eq 'texengine') {
21443:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
21444:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
21445:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
21446:                     }
21447:                 } elsif ($item eq 'anonsurvey_threshold') {
21448:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
21449:                 } elsif ($item eq 'uploadquota') {
21450:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21451:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
21452:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
21453:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
21454:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
21455:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
21456:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
21457:                                        '</ul>'.
21458:                                        '</li>';
21459:                     } else {
21460:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
21461:                     }
21462:                 } elsif ($item eq 'mysqltables') {
21463:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
21464:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
21465:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
21466:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
21467:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
21468:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
21469:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
21470:                                        '</ul>'.
21471:                                        '</li>';
21472:                     } else {
21473:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
21474:                     }
21475:                 } elsif ($item eq 'postsubmit') {
21476:                     if ($domdefaults{'postsubmit'} eq 'off') {
21477:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
21478:                     } else {
21479:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
21480:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21481:                             $resulttext .= &mt('durations:').'<ul>';
21482:                             foreach my $type (@types) {
21483:                                 $resulttext .= '<li>';
21484:                                 my $timeout;
21485:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21486:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21487:                                 }
21488:                                 my $display;
21489:                                 if ($timeout eq '0') {
21490:                                     $display = &mt('unlimited');
21491:                                 } elsif ($timeout eq '') {
21492:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
21493:                                 } else {
21494:                                     $display = &mt('[quant,_1,second]',$timeout);
21495:                                 }
21496:                                 if ($type eq 'community') {
21497:                                     $resulttext .= &mt('Communities');
21498:                                 } elsif ($type eq 'official') {
21499:                                     $resulttext .= &mt('Official courses');
21500:                                 } elsif ($type eq 'unofficial') {
21501:                                     $resulttext .= &mt('Unofficial courses');
21502:                                 } elsif ($type eq 'textbook') {
21503:                                     $resulttext .= &mt('Textbook courses');
21504:                                 } elsif ($type eq 'placement') {
21505:                                     $resulttext .= &mt('Placement tests');
21506:                                 }
21507:                                 $resulttext .= ' -- '.$display.'</li>';
21508:                             }
21509:                             $resulttext .= '</ul>';
21510:                         }
21511:                         $resulttext .= '</li>';
21512:                     }
21513:                 } elsif ($item eq 'coursecredits') {
21514:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21515:                         if (($domdefaults{'officialcredits'} eq '') &&
21516:                             ($domdefaults{'unofficialcredits'} eq '') &&
21517:                             ($domdefaults{'textbookcredits'} eq '')) {
21518:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21519:                         } else {
21520:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
21521:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
21522:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
21523:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
21524:                                            '</ul>'.
21525:                                            '</li>';
21526:                         }
21527:                     } else {
21528:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21529:                     }
21530:                 } elsif ($item eq 'canclone') {
21531:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21532:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21533:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
21534:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
21535:                         }
21536:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
21537:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
21538:                     } else {
21539:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
21540:                     }
21541:                 } elsif ($item eq 'ltiauth') {
21542:                     if ($env{'form.'.$item} eq '1') {
21543:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
21544:                     } else {
21545:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
21546:                     }
21547:                 }
21548:             }
21549:             $resulttext .= '</ul>';
21550:         } else {
21551:             $resulttext = &mt('No changes made to course defaults');
21552:         }
21553:     } else {
21554:         $resulttext = '<span class="LC_error">'.
21555:             &mt('An error occurred: [_1]',$putresult).'</span>';
21556:     }
21557:     return $resulttext;
21558: }
21559: 
21560: sub modify_selfenrollment {
21561:     my ($dom,$lastactref,%domconfig) = @_;
21562:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
21563:     my @types = ('official','unofficial','community','textbook','placement');
21564:     my %titles = &tool_titles();
21565:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
21566:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
21567:     $ordered{'default'} = ['types','registered','approval','limit'];
21568: 
21569:     my (%roles,%shown,%toplevel);
21570:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
21571: 
21572:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
21573:         if ($domconfig{'selfenrollment'} eq '') {
21574:             $domconfig{'selfenrollment'} = {};
21575:         }
21576:     }
21577:     %toplevel = (
21578:                   admin      => 'Configuration Rights',
21579:                   default    => 'Default settings',
21580:                   validation => 'Validation of self-enrollment requests',
21581:                 );
21582:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
21583: 
21584:     if (ref($ordered{'admin'}) eq 'ARRAY') {
21585:         foreach my $item (@{$ordered{'admin'}}) {
21586:             foreach my $type (@types) {
21587:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
21588:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
21589:                 } else {
21590:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
21591:                 }
21592:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
21593:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
21594:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
21595:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
21596:                             push(@{$changes{'admin'}{$type}},$item);
21597:                         }
21598:                     } else {
21599:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
21600:                             push(@{$changes{'admin'}{$type}},$item);
21601:                         }
21602:                     }
21603:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
21604:                     push(@{$changes{'admin'}{$type}},$item);
21605:                 }
21606:             }
21607:         }
21608:     }
21609: 
21610:     foreach my $item (@{$ordered{'default'}}) {
21611:         foreach my $type (@types) {
21612:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
21613:             if ($item eq 'types') {
21614:                 unless (($value eq 'all') || ($value eq 'dom')) {
21615:                     $value = '';
21616:                 }
21617:             } elsif ($item eq 'registered') {
21618:                 unless ($value eq '1') {
21619:                     $value = 0;
21620:                 }
21621:             } elsif ($item eq 'approval') {
21622:                 unless ($value =~ /^[012]$/) {
21623:                     $value = 0;
21624:                 }
21625:             } else {
21626:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21627:                     $value = 'none';
21628:                 }
21629:             }
21630:             $selfenrollhash{'default'}{$type}{$item} = $value;
21631:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
21632:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21633:                     if ($selfenrollhash{'default'}{$type}{$item} ne
21634:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
21635:                          push(@{$changes{'default'}{$type}},$item);
21636:                     }
21637:                 } else {
21638:                     push(@{$changes{'default'}{$type}},$item);
21639:                 }
21640:             } else {
21641:                 push(@{$changes{'default'}{$type}},$item);
21642:             }
21643:             if ($item eq 'limit') {
21644:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21645:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
21646:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
21647:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
21648:                     }
21649:                 } else {
21650:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
21651:                 }
21652:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21653:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
21654:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
21655:                          push(@{$changes{'default'}{$type}},'cap');
21656:                     }
21657:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
21658:                     push(@{$changes{'default'}{$type}},'cap');
21659:                 }
21660:             }
21661:         }
21662:     }
21663: 
21664:     foreach my $item (@{$itemsref}) {
21665:         if ($item eq 'fields') {
21666:             my @changed;
21667:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
21668:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
21669:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
21670:             }
21671:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21672:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
21673:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
21674:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
21675:                 } else {
21676:                     @changed = @{$selfenrollhash{'validation'}{$item}};
21677:                 }
21678:             } else {
21679:                 @changed = @{$selfenrollhash{'validation'}{$item}};
21680:             }
21681:             if (@changed) {
21682:                 if ($selfenrollhash{'validation'}{$item}) { 
21683:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
21684:                 } else {
21685:                     $changes{'validation'}{$item} = &mt('None');
21686:                 }
21687:             }
21688:         } else {
21689:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
21690:             if ($item eq 'markup') {
21691:                if ($env{'form.selfenroll_validation_'.$item}) {
21692:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
21693:                }
21694:             }
21695:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21696:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
21697:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
21698:                 }
21699:             }
21700:         }
21701:     }
21702: 
21703:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
21704:                                              $dom);
21705:     if ($putresult eq 'ok') {
21706:         if (keys(%changes) > 0) {
21707:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21708:             $resulttext = &mt('Changes made:').'<ul>';
21709:             foreach my $key ('admin','default','validation') {
21710:                 if (ref($changes{$key}) eq 'HASH') {
21711:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
21712:                     if ($key eq 'validation') {
21713:                         foreach my $item (@{$itemsref}) {
21714:                             if (exists($changes{$key}{$item})) {
21715:                                 if ($item eq 'markup') {
21716:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21717:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
21718:                                 } else {  
21719:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21720:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
21721:                                 }
21722:                             }
21723:                         }
21724:                     } else {
21725:                         foreach my $type (@types) {
21726:                             if ($type eq 'community') {
21727:                                 $roles{'1'} = &mt('Community personnel');
21728:                             } else {
21729:                                 $roles{'1'} = &mt('Course personnel');
21730:                             }
21731:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
21732:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
21733:                                     if ($key eq 'admin') {
21734:                                         my @mgrdc = ();
21735:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21736:                                             foreach my $item (@{$ordered{'admin'}}) {
21737:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
21738:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
21739:                                                         push(@mgrdc,$item);
21740:                                                     }
21741:                                                 }
21742:                                             }
21743:                                             if (@mgrdc) {
21744:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
21745:                                             } else {
21746:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
21747:                                             }
21748:                                         }
21749:                                     } else {
21750:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21751:                                             foreach my $item (@{$ordered{$key}}) {
21752:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21753:                                                     $domdefaults{$type.'selfenroll'.$item} =
21754:                                                         $selfenrollhash{$key}{$type}{$item};
21755:                                                 }
21756:                                             }
21757:                                         }
21758:                                     }
21759:                                 }
21760:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
21761:                                 foreach my $item (@{$ordered{$key}}) {
21762:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21763:                                         $resulttext .= '<li>';
21764:                                         if ($key eq 'admin') {
21765:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
21766:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
21767:                                         } else {
21768:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
21769:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
21770:                                         }
21771:                                         $resulttext .= '</li>';
21772:                                     }
21773:                                 }
21774:                                 $resulttext .= '</ul></li>';
21775:                             }
21776:                         }
21777:                         $resulttext .= '</ul></li>'; 
21778:                     }
21779:                 }
21780:             }
21781:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
21782:                 my $cachetime = 24*60*60;
21783:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21784:                 if (ref($lastactref) eq 'HASH') {
21785:                     $lastactref->{'domdefaults'} = 1;
21786:                 }
21787:             }
21788:             $resulttext .= '</ul>';
21789:         } else {
21790:             $resulttext = &mt('No changes made to self-enrollment settings');
21791:         }
21792:     } else {
21793:         $resulttext = '<span class="LC_error">'.
21794:             &mt('An error occurred: [_1]',$putresult).'</span>';
21795:     }
21796:     return $resulttext;
21797: }
21798: 
21799: sub modify_wafproxy {
21800:     my ($dom,$action,$lastactref,%domconfig) = @_;
21801:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21802:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
21803:         %wafproxy,%changes,%expirecache,%expiresaml);
21804:     foreach my $server (sort(keys(%servers))) {
21805:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21806:         if ($serverhome eq $server) {
21807:             my $serverdom = &Apache::lonnet::host_domain($server);
21808:             if ($serverdom eq $dom) {
21809:                 $canset{$server} = 1;
21810:             }
21811:         }
21812:     }
21813:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
21814:         %{$values{$dom}} = ();
21815:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
21816:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
21817:         }
21818:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
21819:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
21820:         }
21821:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21822:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
21823:         }
21824:     }
21825:     my $output;
21826:     if (keys(%canset)) {
21827:         %{$wafproxy{'alias'}} = ();
21828:         %{$wafproxy{'saml'}} = ();
21829:         foreach my $key (sort(keys(%canset))) {
21830:             if ($env{'form.wafproxy_'.$dom}) {
21831:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
21832:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
21833:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
21834:                     $changes{'alias'} = 1;
21835:                 }
21836:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
21837:                     $wafproxy{'saml'}{$key} = 1;
21838:                 }
21839:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
21840:                     $changes{'saml'} = 1;
21841:                 }
21842:             } else {
21843:                 $wafproxy{'alias'}{$key} = '';
21844:                 $wafproxy{'saml'}{$key} = '';
21845:                 if ($curralias{$key}) {
21846:                     $changes{'alias'} = 1;
21847:                 }
21848:                 if ($currsaml{$key}) {
21849:                     $changes{'saml'} = 1;
21850:                 }
21851:             }
21852:             if ($wafproxy{'alias'}{$key} eq '') {
21853:                 if ($curralias{$key}) {
21854:                     $expirecache{$key} = 1;
21855:                 }
21856:                 delete($wafproxy{'alias'}{$key});
21857:             }
21858:             if ($wafproxy{'saml'}{$key} eq '') {
21859:                 if ($currsaml{$key}) {
21860:                     $expiresaml{$key} = 1;
21861:                 }
21862:                 delete($wafproxy{'saml'}{$key});
21863:             }
21864:         }
21865:         unless (keys(%{$wafproxy{'alias'}})) {
21866:             delete($wafproxy{'alias'});
21867:         }
21868:         unless (keys(%{$wafproxy{'saml'}})) {
21869:             delete($wafproxy{'saml'});
21870:         }
21871:         # Localization for values in %warn occurs in &mt() calls separately.
21872:         my %warn = (
21873:                      trusted => 'trusted IP range(s)',
21874:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
21875:                      vpnext => 'IP range(s) for backend WAF connections',
21876:                    );
21877:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21878:             my $possible = $env{'form.wafproxy_'.$item};
21879:             $possible =~ s/^\s+|\s+$//g;
21880:             if ($possible ne '') {
21881:                 if ($item eq 'remoteip') {
21882:                     if ($possible =~ /^[mhn]$/) {
21883:                         $wafproxy{$item} = $possible;
21884:                     }
21885:                 } elsif ($item eq 'ipheader') {
21886:                     if ($wafproxy{'remoteip'} eq 'h') {
21887:                         $wafproxy{$item} = $possible;
21888:                     }
21889:                 } elsif ($item eq 'sslopt') {
21890:                     if ($possible =~ /^0|1$/) {
21891:                         $wafproxy{$item} = $possible;
21892:                     }
21893:                 } else {
21894:                     my (@ok,$count);
21895:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
21896:                         unless ($env{'form.wafproxy_vpnaccess'}) {
21897:                             $possible = '';
21898:                         }
21899:                     } elsif ($item eq 'trusted') {
21900:                         unless ($wafproxy{'remoteip'} eq 'h') {
21901:                             $possible = '';
21902:                         }
21903:                     }
21904:                     unless ($possible eq '') {
21905:                         $possible =~ s/[\r\n]+/\s/g;
21906:                         $possible =~ s/\s*-\s*/-/g;
21907:                         $possible =~ s/\s+/,/g;
21908:                         $possible =~ s/,+/,/g;
21909:                     }
21910:                     $count = 0;
21911:                     if ($possible ne '') {
21912:                         foreach my $poss (split(/\,/,$possible)) {
21913:                             $count ++;
21914:                             $poss = &validate_ip_pattern($poss);
21915:                             if ($poss ne '') {
21916:                                 push(@ok,$poss);
21917:                             }
21918:                         }
21919:                         my $diff = $count - scalar(@ok);
21920:                         if ($diff) {
21921:                             push(@warnings,'<li>'.
21922:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
21923:                                      $diff,$warn{$item}).
21924:                                  '</li>');
21925:                         }
21926:                         if (@ok) {
21927:                             my @cidr_list;
21928:                             foreach my $item (@ok) {
21929:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
21930:                             }
21931:                             $wafproxy{$item} = join(',',@cidr_list);
21932:                         }
21933:                     }
21934:                 }
21935:                 if ($wafproxy{$item} ne $currvalue{$item}) {
21936:                     $changes{$item} = 1;
21937:                 }
21938:             } elsif ($currvalue{$item}) {
21939:                 $changes{$item} = 1;
21940:             } 
21941:         }
21942:     } else {
21943:         if (keys(%curralias)) {
21944:             $changes{'alias'} = 1;
21945:         }
21946:         if (keys(%currsaml)) {
21947:             $changes{'saml'} = 1;
21948:         } 
21949:         if (keys(%currvalue)) {
21950:             foreach my $key (keys(%currvalue)) {
21951:                 $changes{$key} = 1;
21952:             }
21953:         }
21954:     }
21955:     if (keys(%changes)) {
21956:         my %defaultshash = (
21957:                               wafproxy => \%wafproxy,
21958:                            ); 
21959:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21960:                                                  $dom);
21961:         if ($putresult eq 'ok') {
21962:             my $cachetime = 24*60*60;
21963:             my (%domdefaults,$updatedomdefs);
21964:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
21965:                 if ($changes{$item}) {
21966:                     unless ($updatedomdefs) {
21967:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
21968:                         $updatedomdefs = 1;
21969:                     }
21970:                     if ($wafproxy{$item}) {
21971:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
21972:                     } elsif (exists($domdefaults{'waf_'.$item})) {
21973:                         delete($domdefaults{'waf_'.$item});
21974:                     } 
21975:                 }
21976:             }
21977:             if ($updatedomdefs) {
21978:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21979:                 if (ref($lastactref) eq 'HASH') {
21980:                     $lastactref->{'domdefaults'} = 1;
21981:                 }
21982:             }
21983:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
21984:                 my %updates = %expirecache;
21985:                 foreach my $key (keys(%expirecache)) {
21986:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
21987:                 }
21988:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
21989:                     my $cachetime = 24*60*60;
21990:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
21991:                         $updates{$key} = 1;
21992:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
21993:                                                       $cachetime);
21994:                     }
21995:                 }
21996:                 if (ref($lastactref) eq 'HASH') {
21997:                     $lastactref->{'proxyalias'} = \%updates;
21998:                 }
21999:             }
22000:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
22001:                 my %samlupdates = %expiresaml;
22002:                 foreach my $key (keys(%expiresaml)) {
22003:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
22004:                 }
22005:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
22006:                     my $cachetime = 24*60*60;
22007:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
22008:                         $samlupdates{$key} = 1;
22009:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
22010:                                                       $cachetime);
22011:                     }
22012:                 }
22013:                 if (ref($lastactref) eq 'HASH') {
22014:                     $lastactref->{'proxysaml'} = \%samlupdates;
22015:                 }
22016:             }
22017:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
22018:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
22019:                 if ($changes{$item}) {
22020:                     if ($item eq 'alias') {
22021:                         my $numaliased = 0;
22022:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
22023:                             my $shown;
22024:                             if (keys(%{$wafproxy{'alias'}})) {
22025:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
22026:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
22027:                                                          &Apache::lonnet::hostname($server),
22028:                                                          $wafproxy{'alias'}{$server}).'</li>';
22029:                                     $numaliased ++;
22030:                                 }
22031:                                 if ($numaliased) {
22032:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
22033:                                                           '<ul>'.$shown.'</ul>').'</li>';
22034:                                 }
22035:                             }
22036:                         }
22037:                         unless ($numaliased) {
22038:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
22039:                         }
22040:                     } elsif ($item eq 'saml') {
22041:                         my $shown; 
22042:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
22043:                             if (keys(%{$wafproxy{'saml'}})) {
22044:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
22045:                             }
22046:                         }
22047:                         if ($shown) {
22048:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
22049:                                                   $shown).'</li>';
22050:                         } else {
22051:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
22052:                         }
22053:                     } else {
22054:                         if ($item eq 'remoteip') {
22055:                             my %ip_methods = &remoteip_methods();
22056:                             if ($wafproxy{$item} =~ /^[mh]$/) {
22057:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
22058:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
22059:                             } else {
22060:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
22061:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
22062:                                                '</li>';
22063:                                 } else {
22064:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
22065:                                 }
22066:                             }
22067:                         } elsif ($item eq 'ipheader') {
22068:                             if ($wafproxy{$item}) {
22069:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
22070:                                                       $wafproxy{$item}).'</li>';
22071:                             } else {
22072:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
22073:                             }
22074:                         } elsif ($item eq 'trusted') {
22075:                             if ($wafproxy{$item}) {
22076:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
22077:                                                       $wafproxy{$item}).'</li>';
22078:                             } else {
22079:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
22080:                             }
22081:                         } elsif ($item eq 'vpnint') {
22082:                             if ($wafproxy{$item}) {
22083:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
22084:                                                        $wafproxy{$item}).'</li>';
22085:                             } else {
22086:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
22087:                             }
22088:                         } elsif ($item eq 'vpnext') {
22089:                             if ($wafproxy{$item}) {
22090:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
22091:                                                        $wafproxy{$item}).'</li>';
22092:                             } else {
22093:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
22094:                             }
22095:                         } elsif ($item eq 'sslopt') {
22096:                             if ($wafproxy{$item}) {
22097:                                 $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>';
22098:                             } else {
22099:                                 $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>';
22100:                             }
22101:                         }
22102:                     }
22103:                 }
22104:             }
22105:         } else {
22106:             $output = '<span class="LC_error">'.
22107:                       &mt('An error occurred: [_1]',$putresult).'</span>';
22108:         }
22109:     } elsif (keys(%canset)) {
22110:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
22111:     }
22112:     if (@warnings) {
22113:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
22114:                        join("\n",@warnings).'</ul>';
22115:     }
22116:     return $output;
22117: }
22118: 
22119: sub validate_ip_pattern {
22120:     my ($pattern) = @_;
22121:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
22122:         my ($start,$end) = ($1,$2);
22123:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
22124:             if (($start !~ m{/}) && ($end !~ m{/})) {
22125:                 return $start.'-'.$end;
22126:             }
22127:         }
22128:     } elsif ($pattern ne '') {
22129:         $pattern = &Net::CIDR::cidrvalidate($pattern);
22130:         if ($pattern ne '') {
22131:             return $pattern;
22132:         }
22133:     }
22134:     return;
22135: }
22136: 
22137: sub modify_usersessions {
22138:     my ($dom,$lastactref,%domconfig) = @_;
22139:     my @hostingtypes = ('version','excludedomain','includedomain');
22140:     my @offloadtypes = ('primary','default');
22141:     my %types = (
22142:                   remote => \@hostingtypes,
22143:                   hosted => \@hostingtypes,
22144:                   spares => \@offloadtypes,
22145:                 );
22146:     my @prefixes = ('remote','hosted','spares');
22147:     my @lcversions = &Apache::lonnet::all_loncaparevs();
22148:     my (%by_ip,%by_location,@intdoms,@instdoms);
22149:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22150:     my @locations = sort(keys(%by_location));
22151:     my (%defaultshash,%changes);
22152:     foreach my $prefix (@prefixes) {
22153:         $defaultshash{'usersessions'}{$prefix} = {};
22154:     }
22155:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22156:     my $resulttext;
22157:     my %iphost = &Apache::lonnet::get_iphost();
22158:     foreach my $prefix (@prefixes) {
22159:         next if ($prefix eq 'spares');
22160:         foreach my $type (@{$types{$prefix}}) {
22161:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22162:             if ($type eq 'version') {
22163:                 my $value = $env{'form.'.$prefix.'_'.$type};
22164:                 my $okvalue;
22165:                 if ($value ne '') {
22166:                     if (grep(/^\Q$value\E$/,@lcversions)) {
22167:                         $okvalue = $value;
22168:                     }
22169:                 }
22170:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22171:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22172:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
22173:                             if ($inuse == 0) {
22174:                                 $changes{$prefix}{$type} = 1;
22175:                             } else {
22176:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
22177:                                     $changes{$prefix}{$type} = 1;
22178:                                 }
22179:                                 if ($okvalue ne '') {
22180:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22181:                                 } 
22182:                             }
22183:                         } else {
22184:                             if (($inuse == 1) && ($okvalue ne '')) {
22185:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22186:                                 $changes{$prefix}{$type} = 1;
22187:                             }
22188:                         }
22189:                     } else {
22190:                         if (($inuse == 1) && ($okvalue ne '')) {
22191:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22192:                             $changes{$prefix}{$type} = 1;
22193:                         }
22194:                     }
22195:                 } else {
22196:                     if (($inuse == 1) && ($okvalue ne '')) {
22197:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22198:                         $changes{$prefix}{$type} = 1;
22199:                     }
22200:                 }
22201:             } else {
22202:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22203:                 my @okvals;
22204:                 foreach my $val (@vals) {
22205:                     if ($val =~ /:/) {
22206:                         my @items = split(/:/,$val);
22207:                         foreach my $item (@items) {
22208:                             if (ref($by_location{$item}) eq 'ARRAY') {
22209:                                 push(@okvals,$item);
22210:                             }
22211:                         }
22212:                     } else {
22213:                         if (ref($by_location{$val}) eq 'ARRAY') {
22214:                             push(@okvals,$val);
22215:                         }
22216:                     }
22217:                 }
22218:                 @okvals = sort(@okvals);
22219:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22220:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22221:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22222:                             if ($inuse == 0) {
22223:                                 $changes{$prefix}{$type} = 1; 
22224:                             } else {
22225:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22226:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
22227:                                 if (@changed > 0) {
22228:                                     $changes{$prefix}{$type} = 1;
22229:                                 }
22230:                             }
22231:                         } else {
22232:                             if ($inuse == 1) {
22233:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22234:                                 $changes{$prefix}{$type} = 1;
22235:                             }
22236:                         } 
22237:                     } else {
22238:                         if ($inuse == 1) {
22239:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22240:                             $changes{$prefix}{$type} = 1;
22241:                         }
22242:                     }
22243:                 } else {
22244:                     if ($inuse == 1) {
22245:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22246:                         $changes{$prefix}{$type} = 1;
22247:                     }
22248:                 }
22249:             }
22250:         }
22251:     }
22252: 
22253:     my @alldoms = &Apache::lonnet::all_domains();
22254:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22255:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
22256:     my $savespares;
22257: 
22258:     foreach my $lonhost (sort(keys(%servers))) {
22259:         my $serverhomeID =
22260:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
22261:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
22262:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
22263:         my %spareschg;
22264:         foreach my $type (@{$types{'spares'}}) {
22265:             my @okspares;
22266:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
22267:             foreach my $server (@checked) {
22268:                 if (&Apache::lonnet::hostname($server) ne '') {
22269:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
22270:                         unless (grep(/^\Q$server\E$/,@okspares)) {
22271:                             push(@okspares,$server);
22272:                         }
22273:                     }
22274:                 }
22275:             }
22276:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
22277:             my $newspare;
22278:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
22279:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
22280:                     $newspare = $new;
22281:                 }
22282:             }
22283:             my @spares;
22284:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
22285:                 @spares = sort(@okspares,$newspare);
22286:             } else {
22287:                 @spares = sort(@okspares);
22288:             }
22289:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
22290:             if (ref($spareid{$lonhost}) eq 'HASH') {
22291:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
22292:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
22293:                     if (@diffs > 0) {
22294:                         $spareschg{$type} = 1;
22295:                     }
22296:                 }
22297:             }
22298:         }
22299:         if (keys(%spareschg) > 0) {
22300:             $changes{'spares'}{$lonhost} = \%spareschg;
22301:         }
22302:     }
22303:     $defaultshash{'usersessions'}{'offloadnow'} = {};
22304:     $defaultshash{'usersessions'}{'offloadoth'} = {};
22305:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
22306:     my @okoffload;
22307:     if (@offloadnow) {
22308:         foreach my $server (@offloadnow) {
22309:             if (&Apache::lonnet::hostname($server) ne '') {
22310:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
22311:                     push(@okoffload,$server);
22312:                 }
22313:             }
22314:         }
22315:         if (@okoffload) {
22316:             foreach my $lonhost (@okoffload) {
22317:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
22318:             }
22319:         }
22320:     }
22321:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
22322:     my @okoffloadoth;
22323:     if (@offloadoth) {
22324:         foreach my $server (@offloadoth) {
22325:             if (&Apache::lonnet::hostname($server) ne '') {
22326:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
22327:                     push(@okoffloadoth,$server);
22328:                 }
22329:             }
22330:         }
22331:         if (@okoffloadoth) {
22332:             foreach my $lonhost (@okoffloadoth) {
22333:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
22334:             }
22335:         }
22336:     }
22337:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
22338:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
22339:             if (ref($changes{'spares'}) eq 'HASH') {
22340:                 if (keys(%{$changes{'spares'}}) > 0) {
22341:                     $savespares = 1;
22342:                 }
22343:             }
22344:         } else {
22345:             $savespares = 1;
22346:         }
22347:         foreach my $offload ('offloadnow','offloadoth') {
22348:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
22349:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
22350:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
22351:                         $changes{$offload} = 1;
22352:                         last;
22353:                     }
22354:                 }
22355:                 unless ($changes{$offload}) {
22356:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
22357:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
22358:                             $changes{$offload} = 1;
22359:                             last;
22360:                         }
22361:                     }
22362:                 }
22363:             } else {
22364:                 if (($offload eq 'offloadnow') && (@okoffload)) {
22365:                      $changes{'offloadnow'} = 1;
22366:                 }
22367:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
22368:                     $changes{'offloadoth'} = 1;
22369:                 }
22370:             } 
22371:         }
22372:     } else {
22373:         if (@okoffload) {
22374:             $changes{'offloadnow'} = 1;
22375:         }
22376:         if (@okoffloadoth) {
22377:             $changes{'offloadoth'} = 1;
22378:         }
22379:     }
22380:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
22381:     if ((keys(%changes) > 0) || ($savespares)) {
22382:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22383:                                                  $dom);
22384:         if ($putresult eq 'ok') {
22385:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22386:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
22387:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
22388:                 }
22389:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
22390:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
22391:                 }
22392:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22393:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
22394:                 }
22395:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22396:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
22397:                 }
22398:             }
22399:             my $cachetime = 24*60*60;
22400:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22401:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
22402:             if (ref($lastactref) eq 'HASH') {
22403:                 $lastactref->{'domdefaults'} = 1;
22404:                 $lastactref->{'usersessions'} = 1;
22405:             }
22406:             if (keys(%changes) > 0) {
22407:                 my %lt = &usersession_titles();
22408:                 $resulttext = &mt('Changes made:').'<ul>';
22409:                 foreach my $prefix (@prefixes) {
22410:                     if (ref($changes{$prefix}) eq 'HASH') {
22411:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22412:                         if ($prefix eq 'spares') {
22413:                             if (ref($changes{$prefix}) eq 'HASH') {
22414:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
22415:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
22416:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
22417:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
22418:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
22419:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
22420:                                         foreach my $type (@{$types{$prefix}}) {
22421:                                             if ($changes{$prefix}{$lonhost}{$type}) {
22422:                                                 my $offloadto = &mt('None');
22423:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
22424:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
22425:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
22426:                                                     }
22427:                                                 }
22428:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
22429:                                             }
22430:                                         }
22431:                                     }
22432:                                     $resulttext .= '</li>';
22433:                                 }
22434:                             }
22435:                         } else {
22436:                             foreach my $type (@{$types{$prefix}}) {
22437:                                 if (defined($changes{$prefix}{$type})) {
22438:                                     my ($newvalue,$notinuse);
22439:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22440:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
22441:                                             if ($type eq 'version') {
22442:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
22443:                                             } else {
22444:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22445:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
22446:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
22447:                                                     }
22448:                                                 } else {
22449:                                                     $notinuse = 1;
22450:                                                 }
22451:                                             }
22452:                                         }
22453:                                     }
22454:                                     if ($newvalue eq '') {
22455:                                         if ($type eq 'version') {
22456:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
22457:                                         } elsif ($notinuse) {
22458:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22459:                                         } else {
22460:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22461:                                         }
22462:                                     } else {
22463:                                         if ($type eq 'version') {
22464:                                             $newvalue .= ' '.&mt('(or later)');
22465:                                         }
22466:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22467:                                     }
22468:                                 }
22469:                             }
22470:                         }
22471:                         $resulttext .= '</ul>';
22472:                     }
22473:                 }
22474:                 if ($changes{'offloadnow'}) {
22475:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22476:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
22477:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
22478:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
22479:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22480:                             }
22481:                             $resulttext .= '</ul>';
22482:                         } else {
22483:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
22484:                         }
22485:                     } else {
22486:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
22487:                     }
22488:                 }
22489:                 if ($changes{'offloadoth'}) {
22490:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22491:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
22492:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
22493:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
22494:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22495:                             }
22496:                             $resulttext .= '</ul>';
22497:                         } else {
22498:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
22499:                         }
22500:                     } else {
22501:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
22502:                     }
22503:                 }
22504:                 $resulttext .= '</ul>';
22505:             } else {
22506:                 $resulttext = $nochgmsg;
22507:             }
22508:         } else {
22509:             $resulttext = '<span class="LC_error">'.
22510:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22511:         }
22512:     } else {
22513:         $resulttext = $nochgmsg;
22514:     }
22515:     return $resulttext;
22516: }
22517: 
22518: sub modify_ssl {
22519:     my ($dom,$lastactref,%domconfig) = @_;
22520:     my (%by_ip,%by_location,@intdoms,@instdoms);
22521:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22522:     my @locations = sort(keys(%by_location));
22523:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22524:     my (%defaultshash,%changes);
22525:     my $action = 'ssl';
22526:     my @prefixes = ('connto','connfrom','replication');
22527:     foreach my $prefix (@prefixes) {
22528:         $defaultshash{$action}{$prefix} = {};
22529:     }
22530:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22531:     my $resulttext;
22532:     my %iphost = &Apache::lonnet::get_iphost();
22533:     my @reptypes = ('certreq','nocertreq');
22534:     my @connecttypes = ('dom','intdom','other');
22535:     my %types = (
22536:                   connto      => \@connecttypes,
22537:                   connfrom    => \@connecttypes,
22538:                   replication => \@reptypes,
22539:                 );
22540:     foreach my $prefix (sort(keys(%types))) {
22541:         foreach my $type (@{$types{$prefix}}) {
22542:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22543:                 my $value = 'yes';
22544:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
22545:                     $value = $env{'form.'.$prefix.'_'.$type};
22546:                 }
22547:                 if (ref($domconfig{$action}) eq 'HASH') {
22548:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22549:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
22550:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
22551:                                 $changes{$prefix}{$type} = 1;
22552:                             }
22553:                             $defaultshash{$action}{$prefix}{$type} = $value;
22554:                         } else {
22555:                             $defaultshash{$action}{$prefix}{$type} = $value;
22556:                             $changes{$prefix}{$type} = 1;
22557:                         }
22558:                     } else {
22559:                         $defaultshash{$action}{$prefix}{$type} = $value;
22560:                         $changes{$prefix}{$type} = 1;
22561:                     }
22562:                 } else {
22563:                     $defaultshash{$action}{$prefix}{$type} = $value;
22564:                     $changes{$prefix}{$type} = 1;
22565:                 }
22566:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
22567:                     delete($changes{$prefix}{$type});
22568:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
22569:                     delete($changes{$prefix}{$type});
22570:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
22571:                     delete($changes{$prefix}{$type});
22572:                 }
22573:             } elsif ($prefix eq 'replication') {
22574:                 if (@locations > 0) {
22575:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22576:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22577:                     my @okvals;
22578:                     foreach my $val (@vals) {
22579:                         if ($val =~ /:/) {
22580:                             my @items = split(/:/,$val);
22581:                             foreach my $item (@items) {
22582:                                 if (ref($by_location{$item}) eq 'ARRAY') {
22583:                                     push(@okvals,$item);
22584:                                 }
22585:                             }
22586:                         } else {
22587:                             if (ref($by_location{$val}) eq 'ARRAY') {
22588:                                 push(@okvals,$val);
22589:                             }
22590:                         }
22591:                     }
22592:                     @okvals = sort(@okvals);
22593:                     if (ref($domconfig{$action}) eq 'HASH') {
22594:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22595:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
22596:                                 if ($inuse == 0) {
22597:                                     $changes{$prefix}{$type} = 1;
22598:                                 } else {
22599:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22600:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
22601:                                     if (@changed > 0) {
22602:                                         $changes{$prefix}{$type} = 1;
22603:                                     }
22604:                                 }
22605:                             } else {
22606:                                 if ($inuse == 1) {
22607:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22608:                                     $changes{$prefix}{$type} = 1;
22609:                                 }
22610:                             }
22611:                         } else {
22612:                             if ($inuse == 1) {
22613:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
22614:                                 $changes{$prefix}{$type} = 1;
22615:                             }
22616:                         }
22617:                     } else {
22618:                         if ($inuse == 1) {
22619:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
22620:                             $changes{$prefix}{$type} = 1;
22621:                         }
22622:                     }
22623:                 }
22624:             }
22625:         }
22626:     }
22627:     if (keys(%changes)) {
22628:         foreach my $prefix (keys(%changes)) {
22629:             if (ref($changes{$prefix}) eq 'HASH') {
22630:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
22631:                     delete($changes{$prefix});
22632:                 }
22633:             } else {
22634:                 delete($changes{$prefix});
22635:             }
22636:         }
22637:     }
22638:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
22639:     if (keys(%changes) > 0) {
22640:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22641:                                                  $dom);
22642:         if ($putresult eq 'ok') {
22643:             if (ref($defaultshash{$action}) eq 'HASH') {
22644:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
22645:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
22646:                 }
22647:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
22648:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
22649:                 }
22650:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
22651:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
22652:                 }
22653:             }
22654:             my $cachetime = 24*60*60;
22655:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22656:             if (ref($lastactref) eq 'HASH') {
22657:                 $lastactref->{'domdefaults'} = 1;
22658:             }
22659:             if (keys(%changes) > 0) {
22660:                 my %titles = &ssl_titles();
22661:                 $resulttext = &mt('Changes made:').'<ul>';
22662:                 foreach my $prefix (@prefixes) {
22663:                     if (ref($changes{$prefix}) eq 'HASH') {
22664:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
22665:                         foreach my $type (@{$types{$prefix}}) {
22666:                             if (defined($changes{$prefix}{$type})) {
22667:                                 my ($newvalue,$notinuse);
22668:                                 if (ref($defaultshash{$action}) eq 'HASH') {
22669:                                     if (ref($defaultshash{$action}{$prefix})) {
22670:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22671:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
22672:                                         } else {
22673:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
22674:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
22675:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
22676:                                                 }
22677:                                             } else {
22678:                                                 $notinuse = 1;
22679:                                             }
22680:                                         }
22681:                                     }
22682:                                     if ($notinuse) {
22683:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
22684:                                     } elsif ($newvalue eq '') {
22685:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
22686:                                     } else {
22687:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
22688:                                     }
22689:                                 }
22690:                             }
22691:                         }
22692:                         $resulttext .= '</ul>';
22693:                     }
22694:                 }
22695:             } else {
22696:                 $resulttext = $nochgmsg;
22697:             }
22698:         } else {
22699:             $resulttext = '<span class="LC_error">'.
22700:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22701:         }
22702:     } else {
22703:         $resulttext = $nochgmsg;
22704:     }
22705:     return $resulttext;
22706: }
22707: 
22708: sub modify_trust {
22709:     my ($dom,$lastactref,%domconfig) = @_;
22710:     my (%by_ip,%by_location,@intdoms,@instdoms);
22711:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22712:     my @locations = sort(keys(%by_location));
22713:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
22714:     my @types = ('exc','inc');
22715:     my (%defaultshash,%changes);
22716:     foreach my $prefix (@prefixes) {
22717:         $defaultshash{'trust'}{$prefix} = {};
22718:     }
22719:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22720:     my $resulttext;
22721:     foreach my $prefix (@prefixes) {
22722:         foreach my $type (@types) {
22723:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22724:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22725:             my @okvals;
22726:             foreach my $val (@vals) {
22727:                 if ($val =~ /:/) {
22728:                     my @items = split(/:/,$val);
22729:                     foreach my $item (@items) {
22730:                         if (ref($by_location{$item}) eq 'ARRAY') {
22731:                             push(@okvals,$item);
22732:                         }
22733:                     }
22734:                 } else {
22735:                     if (ref($by_location{$val}) eq 'ARRAY') {
22736:                         push(@okvals,$val);
22737:                     }
22738:                 }
22739:             }
22740:             @okvals = sort(@okvals);
22741:             if (ref($domconfig{'trust'}) eq 'HASH') {
22742:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
22743:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22744:                         if ($inuse == 0) {
22745:                             $changes{$prefix}{$type} = 1;
22746:                         } else {
22747:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22748:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
22749:                             if (@changed > 0) {
22750:                                 $changes{$prefix}{$type} = 1;
22751:                             }
22752:                         }
22753:                     } else {
22754:                         if ($inuse == 1) {
22755:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22756:                             $changes{$prefix}{$type} = 1;
22757:                         }
22758:                     }
22759:                 } else {
22760:                     if ($inuse == 1) {
22761:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22762:                         $changes{$prefix}{$type} = 1;
22763:                     }
22764:                 }
22765:             } else {
22766:                 if ($inuse == 1) {
22767:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22768:                     $changes{$prefix}{$type} = 1;
22769:                 }
22770:             }
22771:         }
22772:     }
22773:     my $nochgmsg = &mt('No changes made to trust settings.');
22774:     if (keys(%changes) > 0) {
22775:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22776:                                                  $dom);
22777:         if ($putresult eq 'ok') {
22778:             if (ref($defaultshash{'trust'}) eq 'HASH') {
22779:                 foreach my $prefix (@prefixes) {
22780:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
22781:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
22782:                     }
22783:                 }
22784:             }
22785:             my $cachetime = 24*60*60;
22786:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22787:             &Apache::lonnet::do_cache_new('trust',$dom,$defaultshash{'trust'},3600);
22788:             if (ref($lastactref) eq 'HASH') {
22789:                 $lastactref->{'domdefaults'} = 1;
22790:                 $lastactref->{'trust'} = 1;
22791:             }
22792:             if (keys(%changes) > 0) {
22793:                 my %lt = &trust_titles();
22794:                 $resulttext = &mt('Changes made:').'<ul>';
22795:                 foreach my $prefix (@prefixes) {
22796:                     if (ref($changes{$prefix}) eq 'HASH') {
22797:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22798:                         foreach my $type (@types) {
22799:                             if (defined($changes{$prefix}{$type})) {
22800:                                 my ($newvalue,$notinuse);
22801:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
22802:                                     if (ref($defaultshash{'trust'}{$prefix})) {
22803:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22804:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
22805:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
22806:                                             }
22807:                                         } else {
22808:                                             $notinuse = 1;
22809:                                         }
22810:                                     }
22811:                                 }
22812:                                 if ($notinuse) {
22813:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22814:                                 } elsif ($newvalue eq '') {
22815:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22816:                                 } else {
22817:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22818:                                 }
22819:                             }
22820:                         }
22821:                         $resulttext .= '</ul>';
22822:                     }
22823:                 }
22824:                 $resulttext .= '</ul>';
22825:             } else {
22826:                 $resulttext = $nochgmsg;
22827:             }
22828:         } else {
22829:             $resulttext = '<span class="LC_error">'.
22830:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22831:         }
22832:     } else {
22833:         $resulttext = $nochgmsg;
22834:     }
22835:     return $resulttext;
22836: }
22837: 
22838: sub modify_loadbalancing {
22839:     my ($dom,%domconfig) = @_;
22840:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
22841:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
22842:     my ($othertitle,$usertypes,$types) =
22843:         &Apache::loncommon::sorted_inst_types($dom);
22844:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22845:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
22846:     my @sparestypes = ('primary','default');
22847:     my %typetitles = &sparestype_titles();
22848:     my $resulttext;
22849:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
22850:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22851:         %existing = %{$domconfig{'loadbalancing'}};
22852:     }
22853:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
22854:                               \%currtargets,\%currrules,\%currcookies);
22855:     my ($saveloadbalancing,%defaultshash,%changes);
22856:     my ($alltypes,$othertypes,$titles) =
22857:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
22858:     my %ruletitles = &offloadtype_text();
22859:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
22860:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
22861:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
22862:         if ($balancer eq '') {
22863:             next;
22864:         }
22865:         if (!exists($servers{$balancer})) {
22866:             if (exists($currbalancer{$balancer})) {
22867:                 push(@{$changes{'delete'}},$balancer);
22868:             }
22869:             next;
22870:         }
22871:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
22872:             push(@{$changes{'delete'}},$balancer);
22873:             next;
22874:         }
22875:         if (!exists($currbalancer{$balancer})) {
22876:             push(@{$changes{'add'}},$balancer);
22877:         }
22878:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
22879:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
22880:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
22881:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22882:             $saveloadbalancing = 1;
22883:         }
22884:         foreach my $sparetype (@sparestypes) {
22885:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
22886:             my @offloadto;
22887:             foreach my $target (@targets) {
22888:                 if (($servers{$target}) && ($target ne $balancer)) {
22889:                     if ($sparetype eq 'default') {
22890:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
22891:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
22892:                         }
22893:                     }
22894:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
22895:                         push(@offloadto,$target);
22896:                     }
22897:                 }
22898:             }
22899:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
22900:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
22901:                     push(@offloadto,$balancer);
22902:                 }
22903:             }
22904:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
22905:         }
22906:         if ($env{'form.loadbalancing_cookie_'.$i}) {
22907:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
22908:             if (exists($currbalancer{$balancer})) { 
22909:                 unless ($currcookies{$balancer}) {
22910:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
22911:                 }
22912:             }
22913:         } elsif (exists($currbalancer{$balancer})) {
22914:             if ($currcookies{$balancer}) {
22915:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
22916:             }
22917:         }
22918:         if (ref($currtargets{$balancer}) eq 'HASH') {
22919:             foreach my $sparetype (@sparestypes) {
22920:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
22921:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
22922:                     if (@targetdiffs > 0) {
22923:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22924:                     }
22925:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22926:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22927:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22928:                     }
22929:                 }
22930:             }
22931:         } else {
22932:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
22933:                 foreach my $sparetype (@sparestypes) {
22934:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22935:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22936:                             $changes{'curr'}{$balancer}{'targets'} = 1;
22937:                         }
22938:                     }
22939:                 }
22940:             }
22941:         }
22942:         my $ishomedom;
22943:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
22944:             $ishomedom = 1;
22945:         }
22946:         if (ref($alltypes) eq 'ARRAY') {
22947:             foreach my $type (@{$alltypes}) {
22948:                 my $rule;
22949:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
22950:                          (!$ishomedom)) {
22951:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
22952:                 }
22953:                 if ($rule eq 'specific') {
22954:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
22955:                     if (exists($servers{$specifiedhost})) {
22956:                         $rule = $specifiedhost;
22957:                     }
22958:                 }
22959:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
22960:                 if (ref($currrules{$balancer}) eq 'HASH') {
22961:                     if ($rule ne $currrules{$balancer}{$type}) {
22962:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22963:                     }
22964:                 } elsif ($rule ne '') {
22965:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22966:                 }
22967:             }
22968:         }
22969:     }
22970:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
22971:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
22972:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
22973:             $defaultshash{'loadbalancing'} = {};
22974:         }
22975:         my $putresult = &Apache::lonnet::put_dom('configuration',
22976:                                                  \%defaultshash,$dom);
22977:         if ($putresult eq 'ok') {
22978:             if (keys(%changes) > 0) {
22979:                 my %toupdate;
22980:                 if (ref($changes{'delete'}) eq 'ARRAY') {
22981:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
22982:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
22983:                         $toupdate{$balancer} = 1;
22984:                     }
22985:                 }
22986:                 if (ref($changes{'add'}) eq 'ARRAY') {
22987:                     foreach my $balancer (sort(@{$changes{'add'}})) {
22988:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
22989:                         $toupdate{$balancer} = 1;
22990:                     }
22991:                 }
22992:                 if (ref($changes{'curr'}) eq 'HASH') {
22993:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
22994:                         $toupdate{$balancer} = 1;
22995:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
22996:                             if ($changes{'curr'}{$balancer}{'targets'}) {
22997:                                 my %offloadstr;
22998:                                 foreach my $sparetype (@sparestypes) {
22999:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23000:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
23001:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
23002:                                         }
23003:                                     }
23004:                                 }
23005:                                 if (keys(%offloadstr) == 0) {
23006:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
23007:                                 } else {
23008:                                     my $showoffload;
23009:                                     foreach my $sparetype (@sparestypes) {
23010:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
23011:                                         if (defined($offloadstr{$sparetype})) {
23012:                                             $showoffload .= $offloadstr{$sparetype};
23013:                                         } else {
23014:                                             $showoffload .= &mt('None');
23015:                                         }
23016:                                         $showoffload .= ('&nbsp;'x3);
23017:                                     }
23018:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
23019:                                 }
23020:                             }
23021:                         }
23022:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
23023:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
23024:                                 foreach my $type (@{$alltypes}) {
23025:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
23026:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
23027:                                         my $balancetext;
23028:                                         if ($rule eq '') {
23029:                                             $balancetext =  $ruletitles{'default'};
23030:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
23031:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
23032:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
23033:                                                 foreach my $sparetype (@sparestypes) {
23034:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
23035:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
23036:                                                     }
23037:                                                 }
23038:                                                 foreach my $item (@{$alltypes}) {
23039:                                                     next if ($item =~  /^_LC_ipchange/);
23040:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
23041:                                                     if ($hasrule eq 'homeserver') {
23042:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
23043:                                                     } else {
23044:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
23045:                                                             if ($servers{$hasrule}) {
23046:                                                                 $toupdate{$hasrule} = 1;
23047:                                                             }
23048:                                                         }
23049:                                                     }
23050:                                                 }
23051:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
23052:                                                     $balancetext =  $ruletitles{$rule};
23053:                                                 } else {
23054:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
23055:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
23056:                                                     if ($receiver) {
23057:                                                         $toupdate{$receiver};
23058:                                                     }
23059:                                                 }
23060:                                             } else {
23061:                                                 $balancetext =  $ruletitles{$rule};
23062:                                             }
23063:                                         } else {
23064:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
23065:                                         }
23066:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
23067:                                     }
23068:                                 }
23069:                             }
23070:                         }
23071:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
23072:                             if ($currcookies{$balancer}) {
23073:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
23074:                                                           $balancer).'</li>';
23075:                             } else {
23076:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
23077:                                                           $balancer).'</li>';
23078:                             }
23079:                         }
23080:                     }
23081:                 }
23082:                 if (keys(%toupdate)) {
23083:                     my %thismachine;
23084:                     my $updatedhere;
23085:                     my $cachetime = 60*60*24;
23086:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23087:                     foreach my $lonhost (keys(%toupdate)) {
23088:                         if ($thismachine{$lonhost}) {
23089:                             unless ($updatedhere) {
23090:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
23091:                                                               $defaultshash{'loadbalancing'},
23092:                                                               $cachetime);
23093:                                 $updatedhere = 1;
23094:                             }
23095:                         } else {
23096:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
23097:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
23098:                         }
23099:                     }
23100:                 }
23101:                 if ($resulttext ne '') {
23102:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
23103:                 } else {
23104:                     $resulttext = $nochgmsg;
23105:                 }
23106:             } else {
23107:                 $resulttext = $nochgmsg;
23108:             }
23109:         } else {
23110:             $resulttext = '<span class="LC_error">'.
23111:                           &mt('An error occurred: [_1]',$putresult).'</span>';
23112:         }
23113:     } else {
23114:         $resulttext = $nochgmsg;
23115:     }
23116:     return $resulttext;
23117: }
23118: 
23119: sub recurse_check {
23120:     my ($chkcats,$categories,$depth,$name) = @_;
23121:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
23122:         my $chg = 0;
23123:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
23124:             my $category = $chkcats->[$depth]{$name}[$j];
23125:             my $item;
23126:             if ($category eq '') {
23127:                 $chg ++;
23128:             } else {
23129:                 my $deeper = $depth + 1;
23130:                 $item = &escape($category).':'.&escape($name).':'.$depth;
23131:                 if ($chg) {
23132:                     $categories->{$item} -= $chg;
23133:                 }
23134:                 &recurse_check($chkcats,$categories,$deeper,$category);
23135:                 $deeper --;
23136:             }
23137:         }
23138:     }
23139:     return;
23140: }
23141: 
23142: sub recurse_cat_deletes {
23143:     my ($item,$coursecategories,$deletions) = @_;
23144:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
23145:     my $subdepth = $depth + 1;
23146:     if (ref($coursecategories) eq 'HASH') {
23147:         foreach my $subitem (keys(%{$coursecategories})) {
23148:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
23149:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
23150:                 delete($coursecategories->{$subitem});
23151:                 $deletions->{$subitem} = 1;
23152:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
23153:             }
23154:         }
23155:     }
23156:     return;
23157: }
23158: 
23159: sub active_dc_picker {
23160:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
23161:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
23162:     my @domcoord = keys(%domcoords);
23163:     if (keys(%currhash)) {
23164:         foreach my $dc (keys(%currhash)) {
23165:             unless (exists($domcoords{$dc})) {
23166:                 push(@domcoord,$dc);
23167:             }
23168:         }
23169:     }
23170:     @domcoord = sort(@domcoord);
23171:     my $numdcs = scalar(@domcoord);
23172:     my $rows = 0;
23173:     my $table;
23174:     if ($numdcs > 1) {
23175:         $table = '<table>';
23176:         for (my $i=0; $i<@domcoord; $i++) {
23177:             my $rem = $i%($numinrow);
23178:             if ($rem == 0) {
23179:                 if ($i > 0) {
23180:                     $table .= '</tr>';
23181:                 }
23182:                 $table .= '<tr>';
23183:                 $rows ++;
23184:             }
23185:             my $check = '';
23186:             if ($inputtype eq 'radio') {
23187:                 if (keys(%currhash) == 0) {
23188:                     if (!$i) {
23189:                         $check = ' checked="checked"';
23190:                     }
23191:                 } elsif (exists($currhash{$domcoord[$i]})) {
23192:                     $check = ' checked="checked"';
23193:                 }
23194:             } else {
23195:                 if (exists($currhash{$domcoord[$i]})) {
23196:                     $check = ' checked="checked"';
23197:                 }
23198:             }
23199:             if ($i == @domcoord - 1) {
23200:                 my $colsleft = $numinrow - $rem;
23201:                 if ($colsleft > 1) {
23202:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
23203:                 } else {
23204:                     $table .= '<td class="LC_left_item">';
23205:                 }
23206:             } else {
23207:                 $table .= '<td class="LC_left_item">';
23208:             }
23209:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
23210:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23211:             $table .= '<span class="LC_nobreak"><label>'.
23212:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
23213:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
23214:             if ($user ne $dcname.':'.$dcdom) {
23215:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23216:             }
23217:             $table .= '</label></span></td>';
23218:         }
23219:         $table .= '</tr></table>';
23220:     } elsif ($numdcs == 1) {
23221:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
23222:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23223:         if ($inputtype eq 'radio') {
23224:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
23225:             if ($user ne $dcname.':'.$dcdom) {
23226:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23227:             }
23228:         } else {
23229:             my $check;
23230:             if (exists($currhash{$domcoord[0]})) {
23231:                 $check = ' checked="checked"';
23232:             }
23233:             $table = '<span class="LC_nobreak"><label>'.
23234:                      '<input type="checkbox" name="'.$name.'" '.
23235:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
23236:             if ($user ne $dcname.':'.$dcdom) {
23237:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23238:             }
23239:             $table .= '</label></span>';
23240:             $rows ++;
23241:         }
23242:     }
23243:     return ($numdcs,$table,$rows);
23244: }
23245: 
23246: sub usersession_titles {
23247:     return &Apache::lonlocal::texthash(
23248:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
23249:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
23250:                spares => 'Servers offloaded to, when busy',
23251:                version => 'LON-CAPA version requirement',
23252:                excludedomain => 'Allow all, but exclude specific domains',
23253:                includedomain => 'Deny all, but include specific domains',
23254:                primary => 'Primary (checked first)',
23255:                default => 'Default',
23256:            );
23257: }
23258: 
23259: sub id_for_thisdom {
23260:     my (%servers) = @_;
23261:     my %altids;
23262:     foreach my $server (keys(%servers)) {
23263:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
23264:         if ($serverhome ne $server) {
23265:             $altids{$serverhome} = $server;
23266:         }
23267:     }
23268:     return %altids;
23269: }
23270: 
23271: sub count_servers {
23272:     my ($currbalancer,%servers) = @_;
23273:     my (@spares,$numspares);
23274:     foreach my $lonhost (sort(keys(%servers))) {
23275:         next if ($currbalancer eq $lonhost);
23276:         push(@spares,$lonhost);
23277:     }
23278:     if ($currbalancer) {
23279:         $numspares = scalar(@spares);
23280:     } else {
23281:         $numspares = scalar(@spares) - 1;
23282:     }
23283:     return ($numspares,@spares);
23284: }
23285: 
23286: sub lonbalance_targets_js {
23287:     my ($dom,$types,$servers,$settings) = @_;
23288:     my $select = &mt('Select');
23289:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
23290:     if (ref($servers) eq 'HASH') {
23291:         $alltargets = join("','",sort(keys(%{$servers})));
23292:         my @homedoms;
23293:         foreach my $server (sort(keys(%{$servers}))) {
23294:             if (&Apache::lonnet::host_domain($server) eq $dom) {
23295:                 push(@homedoms,'1');
23296:             } else {
23297:                 push(@homedoms,'0');
23298:             }
23299:         }
23300:         $allishome = join("','",@homedoms);
23301:     }
23302:     if (ref($types) eq 'ARRAY') {
23303:         if (@{$types} > 0) {
23304:             @alltypes = @{$types};
23305:         }
23306:     }
23307:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
23308:     $allinsttypes = join("','",@alltypes);
23309:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
23310:     if (ref($settings) eq 'HASH') {
23311:         %existing = %{$settings};
23312:     }
23313:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
23314:                               \%currtargets,\%currrules,\%currcookies);
23315:     my $balancers = join("','",sort(keys(%currbalancer)));
23316:     return <<"END";
23317: 
23318: <script type="text/javascript">
23319: // <![CDATA[
23320: 
23321: currBalancers = new Array('$balancers');
23322: 
23323: function toggleTargets(balnum) {
23324:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23325:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
23326:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
23327:     var prevbalancer = prevhostitem.value;
23328:     var baltotal = document.getElementById('loadbalancing_total').value;
23329:     prevhostitem.value = balancer;
23330:     if (prevbalancer != '') {
23331:         var prevIdx = currBalancers.indexOf(prevbalancer);
23332:         if (prevIdx != -1) {
23333:             currBalancers.splice(prevIdx,1);
23334:         }
23335:     }
23336:     if (balancer == '') {
23337:         hideSpares(balnum);
23338:     } else {
23339:         var currIdx = currBalancers.indexOf(balancer);
23340:         if (currIdx == -1) {
23341:             currBalancers.push(balancer);
23342:         }
23343:         var homedoms = new Array('$allishome');
23344:         var ishomedom = homedoms[lonhostitem.selectedIndex];
23345:         showSpares(balancer,ishomedom,balnum);
23346:     }
23347:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
23348:     return;
23349: }
23350: 
23351: function showSpares(balancer,ishomedom,balnum) {
23352:     var alltargets = new Array('$alltargets');
23353:     var insttypes = new Array('$allinsttypes');
23354:     var offloadtypes = new Array('primary','default');
23355: 
23356:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
23357:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
23358:  
23359:     for (var i=0; i<offloadtypes.length; i++) {
23360:         var count = 0;
23361:         for (var j=0; j<alltargets.length; j++) {
23362:             if (alltargets[j] != balancer) {
23363:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
23364:                 item.value = alltargets[j];
23365:                 item.style.textAlign='left';
23366:                 item.style.textFace='normal';
23367:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
23368:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
23369:                     item.disabled = '';
23370:                 } else {
23371:                     item.disabled = 'disabled';
23372:                     item.checked = false;
23373:                 }
23374:                 count ++;
23375:             }
23376:         }
23377:     }
23378:     for (var k=0; k<insttypes.length; k++) {
23379:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
23380:             if (ishomedom == 1) {
23381:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23382:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23383:             } else {
23384:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23385:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23386:             }
23387:         } else {
23388:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23389:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23390:         }
23391:         if ((insttypes[k] != '_LC_external') && 
23392:             ((insttypes[k] != '_LC_internetdom') ||
23393:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
23394:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
23395:             item.options.length = 0;
23396:             item.options[0] = new Option("","",true,true);
23397:             var idx = 0;
23398:             for (var m=0; m<alltargets.length; m++) {
23399:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
23400:                     idx ++;
23401:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23402:                 }
23403:             }
23404:         }
23405:     }
23406:     return;
23407: }
23408: 
23409: function hideSpares(balnum) {
23410:     var alltargets = new Array('$alltargets');
23411:     var insttypes = new Array('$allinsttypes');
23412:     var offloadtypes = new Array('primary','default');
23413: 
23414:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
23415:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
23416: 
23417:     var total = alltargets.length - 1;
23418:     for (var i=0; i<offloadtypes; i++) {
23419:         for (var j=0; j<total; j++) {
23420:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
23421:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
23422:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
23423:         }
23424:     }
23425:     for (var k=0; k<insttypes.length; k++) {
23426:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23427:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23428:         if (insttypes[k] != '_LC_external') {
23429:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
23430:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
23431:         }
23432:     }
23433:     return;
23434: }
23435: 
23436: function checkOffloads(item,balnum,type) {
23437:     var alltargets = new Array('$alltargets');
23438:     var offloadtypes = new Array('primary','default');
23439:     if (item.checked) {
23440:         var total = alltargets.length - 1;
23441:         var other;
23442:         if (type == offloadtypes[0]) {
23443:             other = offloadtypes[1];
23444:         } else {
23445:             other = offloadtypes[0];
23446:         }
23447:         for (var i=0; i<total; i++) {
23448:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
23449:             if (server == item.value) {
23450:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
23451:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
23452:                 }
23453:             }
23454:         }
23455:     }
23456:     return;
23457: }
23458: 
23459: function singleServerToggle(balnum,type) {
23460:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
23461:     if (offloadtoSelIdx == 0) {
23462:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
23463:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23464: 
23465:     } else {
23466:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
23467:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23468:     }
23469:     return;
23470: }
23471: 
23472: function balanceruleChange(formname,balnum,type) {
23473:     if (type == '_LC_external') {
23474:         return;
23475:     }
23476:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
23477:     for (var i=0; i<typesRules.length; i++) {
23478:         if (formname.elements[typesRules[i]].checked) {
23479:             if (formname.elements[typesRules[i]].value != 'specific') {
23480:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
23481:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23482:             } else {
23483:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23484:             }
23485:         }
23486:     }
23487:     return;
23488: }
23489: 
23490: function balancerDeleteChange(balnum) {
23491:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23492:     var baltotal = document.getElementById('loadbalancing_total').value;
23493:     var addtarget;
23494:     var removetarget;
23495:     var action = 'delete';
23496:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
23497:         var lonhost = hostitem.value;
23498:         var currIdx = currBalancers.indexOf(lonhost);
23499:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
23500:             if (currIdx != -1) {
23501:                 currBalancers.splice(currIdx,1);
23502:             }
23503:             addtarget = lonhost;
23504:         } else {
23505:             if (currIdx == -1) {
23506:                 currBalancers.push(lonhost);
23507:             }
23508:             removetarget = lonhost;
23509:             action = 'undelete';
23510:         }
23511:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
23512:     }
23513:     return;
23514: }
23515: 
23516: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
23517:     if (baltotal > 1) {
23518:         var offloadtypes = new Array('primary','default');
23519:         var alltargets = new Array('$alltargets');
23520:         var insttypes = new Array('$allinsttypes');
23521:         for (var i=0; i<baltotal; i++) {
23522:             if (i != balnum) {
23523:                 for (var j=0; j<offloadtypes.length; j++) {
23524:                     var total = alltargets.length - 1;
23525:                     for (var k=0; k<total; k++) {
23526:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
23527:                         var server = serveritem.value;
23528:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
23529:                             if (server == addtarget) {
23530:                                 serveritem.disabled = '';
23531:                             }
23532:                         }
23533:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23534:                             if (server == removetarget) {
23535:                                 serveritem.disabled = 'disabled';
23536:                                 serveritem.checked = false;
23537:                             }
23538:                         }
23539:                     }
23540:                 }
23541:                 for (var j=0; j<insttypes.length; j++) {
23542:                     if (insttypes[j] != '_LC_external') {
23543:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
23544:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
23545:                             var currSel = singleserver.selectedIndex;
23546:                             var currVal = singleserver.options[currSel].value;
23547:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
23548:                                 var numoptions = singleserver.options.length;
23549:                                 var needsnew = 1;
23550:                                 for (var k=0; k<numoptions; k++) {
23551:                                     if (singleserver.options[k] == addtarget) {
23552:                                         needsnew = 0;
23553:                                         break;
23554:                                     }
23555:                                 }
23556:                                 if (needsnew == 1) {
23557:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
23558:                                 }
23559:                             }
23560:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23561:                                 singleserver.options.length = 0;
23562:                                 if ((currVal) && (currVal != removetarget)) {
23563:                                     singleserver.options[0] = new Option("","",false,false);
23564:                                 } else {
23565:                                     singleserver.options[0] = new Option("","",true,true);
23566:                                 }
23567:                                 var idx = 0;
23568:                                 for (var m=0; m<alltargets.length; m++) {
23569:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
23570:                                         idx ++;
23571:                                         if (currVal == alltargets[m]) {
23572:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
23573:                                         } else {
23574:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23575:                                         }
23576:                                     }
23577:                                 }
23578:                             }
23579:                         }
23580:                     }
23581:                 }
23582:             }
23583:         }
23584:     }
23585:     return;
23586: }
23587: 
23588: // ]]>
23589: </script>
23590: 
23591: END
23592: }
23593: 
23594: 
23595: sub new_spares_js {
23596:     my @sparestypes = ('primary','default');
23597:     my $types = join("','",@sparestypes);
23598:     my $select = &mt('Select');
23599:     return <<"END";
23600: 
23601: <script type="text/javascript">
23602: // <![CDATA[
23603: 
23604: function updateNewSpares(formname,lonhost) {
23605:     var types = new Array('$types');
23606:     var include = new Array();
23607:     var exclude = new Array();
23608:     for (var i=0; i<types.length; i++) {
23609:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
23610:         for (var j=0; j<spareboxes.length; j++) {
23611:             if (formname.elements[spareboxes[j]].checked) {
23612:                 exclude.push(formname.elements[spareboxes[j]].value);
23613:             } else {
23614:                 include.push(formname.elements[spareboxes[j]].value);
23615:             }
23616:         }
23617:     }
23618:     for (var i=0; i<types.length; i++) {
23619:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
23620:         var selIdx = newSpare.selectedIndex;
23621:         var currnew = newSpare.options[selIdx].value;
23622:         var okSpares = new Array();
23623:         for (var j=0; j<newSpare.options.length; j++) {
23624:             var possible = newSpare.options[j].value;
23625:             if (possible != '') {
23626:                 if (exclude.indexOf(possible) == -1) {
23627:                     okSpares.push(possible);
23628:                 } else {
23629:                     if (currnew == possible) {
23630:                         selIdx = 0;
23631:                     }
23632:                 }
23633:             }
23634:         }
23635:         for (var k=0; k<include.length; k++) {
23636:             if (okSpares.indexOf(include[k]) == -1) {
23637:                 okSpares.push(include[k]);
23638:             }
23639:         }
23640:         okSpares.sort();
23641:         newSpare.options.length = 0;
23642:         if (selIdx == 0) {
23643:             newSpare.options[0] = new Option("$select","",true,true);
23644:         } else {
23645:             newSpare.options[0] = new Option("$select","",false,false);
23646:         }
23647:         for (var m=0; m<okSpares.length; m++) {
23648:             var idx = m+1;
23649:             var selThis = 0;
23650:             if (selIdx != 0) {
23651:                 if (okSpares[m] == currnew) {
23652:                     selThis = 1;
23653:                 }
23654:             }
23655:             if (selThis == 1) {
23656:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
23657:             } else {
23658:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
23659:             }
23660:         }
23661:     }
23662:     return;
23663: }
23664: 
23665: function checkNewSpares(lonhost,type) {
23666:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
23667:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
23668:     if (chosen != '') {
23669:         var othertype;
23670:         var othernewSpare;
23671:         if (type == 'primary') {
23672:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
23673:         }
23674:         if (type == 'default') {
23675:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
23676:         }
23677:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
23678:             othernewSpare.selectedIndex = 0;
23679:         }
23680:     }
23681:     return;
23682: }
23683: 
23684: // ]]>
23685: </script>
23686: 
23687: END
23688: 
23689: }
23690: 
23691: sub common_domprefs_js {
23692:     return <<"END";
23693: 
23694: <script type="text/javascript">
23695: // <![CDATA[
23696: 
23697: function getIndicesByName(formname,item) {
23698:     var group = new Array();
23699:     for (var i=0;i<formname.elements.length;i++) {
23700:         if (formname.elements[i].name == item) {
23701:             group.push(formname.elements[i].id);
23702:         }
23703:     }
23704:     return group;
23705: }
23706: 
23707: // ]]>
23708: </script>
23709: 
23710: END
23711: 
23712: }
23713: 
23714: sub recaptcha_js {
23715:     my %lt = &captcha_phrases();
23716:     return <<"END";
23717: 
23718: <script type="text/javascript">
23719: // <![CDATA[
23720: 
23721: function updateCaptcha(caller,context) {
23722:     var privitem;
23723:     var pubitem;
23724:     var privtext;
23725:     var pubtext;
23726:     var versionitem;
23727:     var versiontext;
23728:     if (document.getElementById(context+'_recaptchapub')) {
23729:         pubitem = document.getElementById(context+'_recaptchapub');
23730:     } else {
23731:         return;
23732:     }
23733:     if (document.getElementById(context+'_recaptchapriv')) {
23734:         privitem = document.getElementById(context+'_recaptchapriv');
23735:     } else {
23736:         return;
23737:     }
23738:     if (document.getElementById(context+'_recaptchapubtxt')) {
23739:         pubtext = document.getElementById(context+'_recaptchapubtxt');
23740:     } else {
23741:         return;
23742:     }
23743:     if (document.getElementById(context+'_recaptchaprivtxt')) {
23744:         privtext = document.getElementById(context+'_recaptchaprivtxt');
23745:     } else {
23746:         return;
23747:     }
23748:     if (document.getElementById(context+'_recaptchaversion')) {
23749:         versionitem = document.getElementById(context+'_recaptchaversion');
23750:     } else {
23751:         return;
23752:     }
23753:     if (document.getElementById(context+'_recaptchavertxt')) {
23754:         versiontext = document.getElementById(context+'_recaptchavertxt');
23755:     } else {
23756:         return;
23757:     }
23758:     if (caller.checked) {
23759:         if (caller.value == 'recaptcha') {
23760:             pubitem.type = 'text';
23761:             privitem.type = 'text';
23762:             pubitem.size = '40';
23763:             privitem.size = '40';
23764:             pubtext.innerHTML = "$lt{'pub'}";
23765:             privtext.innerHTML = "$lt{'priv'}";
23766:             versionitem.type = 'text';
23767:             versionitem.size = '3';
23768:             versiontext.innerHTML = "$lt{'ver'}";
23769:         } else {
23770:             pubitem.type = 'hidden';
23771:             privitem.type = 'hidden';
23772:             versionitem.type = 'hidden';
23773:             pubtext.innerHTML = '';
23774:             privtext.innerHTML = '';
23775:             versiontext.innerHTML = '';
23776:         }
23777:     }
23778:     return;
23779: }
23780: 
23781: // ]]>
23782: </script>
23783: 
23784: END
23785: 
23786: }
23787: 
23788: sub toggle_display_js {
23789:     return <<"END";
23790: 
23791: <script type="text/javascript">
23792: // <![CDATA[
23793: 
23794: function toggleDisplay(domForm,caller) {
23795:     if (document.getElementById(caller)) {
23796:         var divitem = document.getElementById(caller);
23797:         var optionsElement = domForm.coursecredits;
23798:         var checkval = 1;
23799:         var dispval = 'block';
23800:         var selfcreateRegExp = /^cancreate_emailverified/;
23801:         if (caller == 'emailoptions') {
23802:             optionsElement = domForm.cancreate_email;
23803:         }
23804:         if (caller == 'studentsubmission') {
23805:             optionsElement = domForm.postsubmit;
23806:         }
23807:         if (caller == 'cloneinstcode') {
23808:             optionsElement = domForm.canclone;
23809:             checkval = 'instcode';
23810:         }
23811:         if (selfcreateRegExp.test(caller)) {
23812:             optionsElement = domForm.elements[caller];
23813:             checkval = 'other';
23814:             dispval = 'inline'
23815:         }
23816:         if (optionsElement.length) {
23817:             var currval;
23818:             for (var i=0; i<optionsElement.length; i++) {
23819:                 if (optionsElement[i].checked) {
23820:                    currval = optionsElement[i].value;
23821:                 }
23822:             }
23823:             if (currval == checkval) {
23824:                 divitem.style.display = dispval;
23825:             } else {
23826:                 divitem.style.display = 'none';
23827:             }
23828:         }
23829:     }
23830:     return;
23831: }
23832: 
23833: // ]]>
23834: </script>
23835: 
23836: END
23837: 
23838: }
23839: 
23840: sub captcha_phrases {
23841:     return &Apache::lonlocal::texthash (
23842:                  priv => 'Private key',
23843:                  pub  => 'Public key',
23844:                  original  => 'original (CAPTCHA)',
23845:                  recaptcha => 'successor (ReCAPTCHA)',
23846:                  notused   => 'unused',
23847:                  ver => 'ReCAPTCHA version (1 or 2)',
23848:     );
23849: }
23850: 
23851: sub devalidate_remote_domconfs {
23852:     my ($dom,$cachekeys) = @_;
23853:     return unless (ref($cachekeys) eq 'HASH');
23854:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
23855:     my %thismachine;
23856:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23857:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
23858:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
23859:                       'ipaccess','trust');
23860:     my %cache_by_lonhost;
23861:     if (exists($cachekeys->{'samllanding'})) {
23862:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
23863:             my %landing = %{$cachekeys->{'samllanding'}};
23864:             my %domservers = &Apache::lonnet::get_servers($dom);
23865:             if (keys(%domservers)) {
23866:                 foreach my $server (keys(%domservers)) {
23867:                     my @cached;
23868:                     next if ($thismachine{$server});
23869:                     if ($landing{$server}) {
23870:                         push(@cached,&escape('samllanding').':'.&escape($server));
23871:                     }
23872:                     if (@cached) {
23873:                         $cache_by_lonhost{$server} = \@cached;
23874:                     }
23875:                 }
23876:             }
23877:         }
23878:     }
23879:     if (keys(%servers)) {
23880:         foreach my $server (keys(%servers)) {
23881:             next if ($thismachine{$server});
23882:             my @cached;
23883:             foreach my $name (@posscached) {
23884:                 if ($cachekeys->{$name}) {
23885:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
23886:                         if (ref($cachekeys->{$name}) eq 'HASH') {
23887:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
23888:                                 push(@cached,&escape($name).':'.&escape($key));
23889:                             }
23890:                         }
23891:                     } else {
23892:                         push(@cached,&escape($name).':'.&escape($dom));
23893:                     }
23894:                 }
23895:             }
23896:             if ((exists($cache_by_lonhost{$server})) &&
23897:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
23898:                 push(@cached,@{$cache_by_lonhost{$server}});
23899:             }
23900:             if (@cached) {
23901:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
23902:             }
23903:         }
23904:     }
23905:     return;
23906: }
23907: 
23908: 1;

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