File:  [LON-CAPA] / loncom / interface / domainprefs.pm
Revision 1.405: download - view: text, annotated - select for diffs
Mon Feb 14 02:48:46 2022 UTC (2 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907
  - Rename "LTI Provider" domain config item.
  - Add three additional sections: "Encryption of shared secrets",
    "Rules for shared secrets" and Link Protectors (domain).
  - Keys used in domain for a particular library server may only be set in
    a session on that server (and use Lond.pm and not lonc/lond).
  - Min and max length and character requirements can be set for secrets used
    for LTI-based link protection for deep-links.

    1: # The LearningOnline Network with CAPA
    2: # Handler to set domain-wide configuration settings
    3: #
    4: # $Id: domainprefs.pm,v 1.405 2022/02/14 02:48:46 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: ###############################################################
   30: ###############################################################
   31: 
   32: =pod
   33: 
   34: =head1 NAME
   35: 
   36: Apache::domainprefs.pm
   37: 
   38: =head1 SYNOPSIS
   39: 
   40: Handles configuration of a LON-CAPA domain.  
   41: 
   42: This is part of the LearningOnline Network with CAPA project
   43: described at http://www.lon-capa.org.
   44: 
   45: 
   46: =head1 OVERVIEW
   47: 
   48: Each institution using LON-CAPA will typically have a single domain designated 
   49: for use by individuals affiliated with the institution.  Accordingly, each domain
   50: may define a default set of logos and a color scheme which can be used to "brand"
   51: the LON-CAPA instance. In addition, an institution will typically have a language
   52: and timezone which are used for the majority of courses.
   53: 
   54: LON-CAPA provides a mechanism to display and modify these defaults, as well as a 
   55: host of other domain-wide settings which determine the types of functionality
   56: available to users and courses in the domain.
   57: 
   58: There is also a mechanism to configure cataloging of courses in the domain, and
   59: controls on the operation of automated processes which govern such things as
   60: roster updates, user directory updates and processing of course requests.
   61: 
   62: The domain coordination manual which is built dynamically on install/update of 
   63: LON-CAPA from the relevant help items provides more information about domain 
   64: configuration.
   65: 
   66: Most of the domain settings are stored in the configuration.db GDBM file which is
   67: housed on the primary library server for the domain in /home/httpd/lonUsers/$dom,
   68: where $dom is the domain.  The configuration.db stores settings in a number of 
   69: frozen hashes of hashes.  In a few cases, domain information must be uploaded to
   70: the domain as files (e.g., image files for logos etc., or plain text files for
   71: bubblesheet formats).  In this case the domainprefs.pm must be running in a user
   72: session hosted on the primary library server in the domain, as these files are 
   73: stored in author space belonging to a special $dom-domainconfig user.   
   74: 
   75: domainprefs.pm in combination with lonconfigsettings.pm will retrieve and display
   76: the current settings, and provides an interface to make modifications.
   77: 
   78: =head1 SUBROUTINES
   79: 
   80: =over
   81: 
   82: =item print_quotas()
   83: 
   84: Inputs: 4 
   85: 
   86: $dom,$settings,$rowtotal,$action.
   87: 
   88: $dom is the domain, $settings is a reference to a hash of current settings for
   89: the current context, $rowtotal is a reference to the scalar used to record the 
   90: number of rows displayed on the page, and $action is the context (quotas, 
   91: requestcourses or requestauthor).
   92: 
   93: The print_quotas routine was orginally created to display/store information
   94: about default quota sizes for portfolio spaces for the different types of 
   95: institutional affiliation in the domain (e.g., Faculty, Staff, Student etc.), 
   96: but is now also used to manage availability of user tools: 
   97: i.e., blogs, aboutme page, and portfolios, and the course request tool,
   98: used by course owners to request creation of a course, and to display/store
   99: default quota sizes for Authoring Spaces.
  100: 
  101: Outputs: 1
  102: 
  103: $datatable  - HTML containing form elements which allow settings to be changed. 
  104: 
  105: In the case of course requests, radio buttons are displayed for each institutional
  106: affiliate type (and also default, and _LC_adv) for each of the course types 
  107: (official, unofficial, community, textbook, placement, and lti).  
  108: In each case the radio buttons allow the selection of one of four values:  
  109: 
  110: 0, approval, validate, autolimit=N (where N is blank, or a positive integer).
  111: which have the following effects:
  112: 
  113: 0
  114: 
  115: =over
  116: 
  117: - course requests are not allowed for this course types/affiliation
  118: 
  119: =back
  120: 
  121: approval 
  122: 
  123: =over 
  124: 
  125: - course requests must be approved by a Doman Coordinator in the 
  126: course's domain
  127: 
  128: =back
  129: 
  130: validate 
  131: 
  132: =over
  133: 
  134: - an institutional validation (e.g., check requestor is instructor
  135: of record) needs to be passed before the course will be created.  The required
  136: validation is in localenroll.pm on the primary library server for the course 
  137: domain.
  138: 
  139: =back
  140: 
  141: autolimit 
  142: 
  143: =over
  144:  
  145: - course requests will be processed automatically up to a limit of
  146: N requests for the course type for the particular requestor.
  147: If N is undefined, there is no limit to the number of course requests
  148: which a course owner may submit and have processed automatically. 
  149: 
  150: =back
  151: 
  152: =item modify_quotas() 
  153: 
  154: =back
  155: 
  156: =cut
  157: 
  158: package Apache::domainprefs;
  159: 
  160: use strict;
  161: use Apache::Constants qw(:common :http);
  162: use Apache::lonnet;
  163: use Apache::loncommon();
  164: use Apache::lonhtmlcommon();
  165: use Apache::lonlocal;
  166: use Apache::lonmsg();
  167: use Apache::lonconfigsettings;
  168: use Apache::lonuserutils();
  169: use Apache::loncoursequeueadmin();
  170: use LONCAPA qw(:DEFAULT :match);
  171: use LONCAPA::Enrollment;
  172: use LONCAPA::lonauthcgi();
  173: use LONCAPA::SSL;
  174: use File::Copy;
  175: use Locale::Language;
  176: use DateTime::TimeZone;
  177: use DateTime::Locale;
  178: use Time::HiRes qw( sleep );
  179: use Net::CIDR;
  180: 
  181: my $registered_cleanup;
  182: my $modified_urls;
  183: 
  184: sub handler {
  185:     my $r=shift;
  186:     if ($r->header_only) {
  187:         &Apache::loncommon::content_type($r,'text/html');
  188:         $r->send_http_header;
  189:         return OK;
  190:     }
  191: 
  192:     my $context = 'domain';
  193:     my $dom = $env{'request.role.domain'};
  194:     my $domdesc = &Apache::lonnet::domain($dom,'description');
  195:     if (&Apache::lonnet::allowed('mau',$dom)) {
  196:         &Apache::loncommon::content_type($r,'text/html');
  197:         $r->send_http_header;
  198:     } else {
  199:         $env{'user.error.msg'}=
  200:         "/adm/domainprefs:mau:0:0:Cannot modify domain settings";
  201:         return HTTP_NOT_ACCEPTABLE;
  202:     }
  203: 
  204:     $registered_cleanup=0;
  205:     @{$modified_urls}=();
  206: 
  207:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  208:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  209:                                             ['phase','actions']);
  210:     my $phase = 'pickactions';
  211:     if ( exists($env{'form.phase'}) ) {
  212:         $phase = $env{'form.phase'};
  213:     }
  214:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
  215:     my %domconfig =
  216:       &Apache::lonnet::get_dom('configuration',['login','rolecolors',
  217:                 'quotas','autoenroll','autoupdate','autocreate',
  218:                 'directorysrch','usercreation','usermodification',
  219:                 'contacts','defaults','scantron','coursecategories',
  220:                 'serverstatuses','requestcourses','helpsettings',
  221:                 'coursedefaults','usersessions','loadbalancing',
  222:                 'requestauthor','selfenrollment','inststatus',
  223:                 'ltitools','ssl','trust','lti','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'}{'prot'}) eq 'HASH') {
  253:             if (ref($encconfig{'linkprot'}) eq 'HASH') {
  254:                 foreach my $id (keys(%{$domconfig{'ltisec'}{'prot'}})) {
  255:                     if ((ref($domconfig{'ltisec'}{'prot'}{$id}) eq 'HASH') &&
  256:                         (ref($encconfig{'linkprot'}{$id}) eq 'HASH')) {
  257:                         foreach my $item ('key','secret') {
  258:                             $domconfig{'ltisec'}{'prot'}{$id}{$item} = $encconfig{'linkprot'}{$id}{$item};
  259:                         }
  260:                     }
  261:                 }
  262:             }
  263:         }
  264:     }
  265:     if (ref($domconfig{'proctoring'}) eq 'HASH') {
  266:         if (ref($encconfig{'proctoring'}) eq 'HASH') {
  267:             foreach my $provider (keys(%{$domconfig{'proctoring'}})) {
  268:                 if ((ref($domconfig{'proctoring'}{$provider}) eq 'HASH') &&
  269:                     (ref($encconfig{'proctoring'}{$provider}) eq 'HASH')) {
  270:                     foreach my $item ('key','secret') {
  271:                         $domconfig{'proctoring'}{$provider}{$item} = $encconfig{'proctoring'}{$provider}{$item};
  272:                     }
  273:                 }
  274:             }
  275:         }
  276:     }
  277:     my @prefs_order = ('rolecolors','login','ipaccess','defaults','wafproxy','passwords',
  278:                        'quotas','autoenroll','autoupdate','autocreate','directorysrch',
  279:                        'contacts','privacy','usercreation','selfcreation',
  280:                        'usermodification','scantron','requestcourses','requestauthor',
  281:                        'coursecategories','serverstatuses','helpsettings','coursedefaults',
  282:                        'ltitools','proctoring','selfenrollment','usersessions','ssl',
  283:                        'trust','lti');
  284:     my %existing;
  285:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  286:         %existing = %{$domconfig{'loadbalancing'}};
  287:     }
  288:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  289:         push(@prefs_order,'loadbalancing');
  290:     }
  291:     my %prefs = (
  292:         'rolecolors' =>
  293:                    { text => 'Default color schemes',
  294:                      help => 'Domain_Configuration_Color_Schemes',
  295:                      header => [{col1 => 'Student Settings',
  296:                                  col2 => '',},
  297:                                 {col1 => 'Coordinator Settings',
  298:                                  col2 => '',},
  299:                                 {col1 => 'Author Settings',
  300:                                  col2 => '',},
  301:                                 {col1 => 'Administrator Settings',
  302:                                  col2 => '',}],
  303:                       print => \&print_rolecolors,
  304:                       modify => \&modify_rolecolors,
  305:                     },
  306:         'login' =>
  307:                     { text => 'Log-in page options',
  308:                       help => 'Domain_Configuration_Login_Page',
  309:                       header => [{col1 => 'Log-in Page Items',
  310:                                   col2 => '',},
  311:                                  {col1 => 'Log-in Help',
  312:                                   col2 => 'Value'},
  313:                                  {col1 => 'Custom HTML in document head',
  314:                                   col2 => 'Value'},
  315:                                  {col1 => 'SSO',
  316:                                   col2 => 'Dual login: SSO and non-SSO options'},
  317:                                 ],
  318:                       print => \&print_login,
  319:                       modify => \&modify_login,
  320:                     },
  321:         'defaults' => 
  322:                     { text => 'Default authentication/language/timezone/portal/types',
  323:                       help => 'Domain_Configuration_LangTZAuth',
  324:                       header => [{col1 => 'Setting',
  325:                                   col2 => 'Value'},
  326:                                  {col1 => 'Institutional user types',
  327:                                   col2 => 'Name displayed'}],
  328:                       print => \&print_defaults,
  329:                       modify => \&modify_defaults,
  330:                     },
  331:         'wafproxy' =>
  332:                     { text => 'Web Application Firewall/Reverse Proxy',
  333:                       help => 'Domain_Configuration_WAF_Proxy',
  334:                       header => [{col1 => 'Domain(s)',
  335:                                   col2 => 'Servers and WAF/Reverse Proxy alias(es)',
  336:                                  },
  337:                                  {col1 => 'Domain(s)',
  338:                                   col2 => 'WAF Configuration',}],
  339:                       print => \&print_wafproxy,
  340:                       modify => \&modify_wafproxy,
  341:                     },
  342:         'passwords' =>
  343:                     { text => 'Passwords (Internal authentication)',
  344:                       help => 'Domain_Configuration_Passwords',
  345:                       header => [{col1 => 'Resetting Forgotten Password',
  346:                                   col2 => 'Settings'},
  347:                                  {col1 => 'Encryption of Stored Passwords (Internal Auth)',
  348:                                   col2 => 'Settings'},
  349:                                  {col1 => 'Rules for LON-CAPA Passwords',
  350:                                   col2 => 'Settings'},
  351:                                  {col1 => 'Course Owner Changing Student Passwords',
  352:                                   col2 => 'Settings'}],
  353:                       print => \&print_passwords,
  354:                       modify => \&modify_passwords,
  355:                     },
  356:         'quotas' => 
  357:                     { text => 'Blogs, personal web pages, webDAV/quotas, portfolios',
  358:                       help => 'Domain_Configuration_Quotas',
  359:                       header => [{col1 => 'User affiliation',
  360:                                   col2 => 'Available tools',
  361:                                   col3 => 'Quotas, MB; (Authoring requires role)',}],
  362:                       print => \&print_quotas,
  363:                       modify => \&modify_quotas,
  364:                     },
  365:         'autoenroll' =>
  366:                    { text => 'Auto-enrollment settings',
  367:                      help => 'Domain_Configuration_Auto_Enrollment',
  368:                      header => [{col1 => 'Configuration setting',
  369:                                  col2 => 'Value(s)'}],
  370:                      print => \&print_autoenroll,
  371:                      modify => \&modify_autoenroll,
  372:                    },
  373:         'autoupdate' => 
  374:                    { text => 'Auto-update settings',
  375:                      help => 'Domain_Configuration_Auto_Updates',
  376:                      header => [{col1 => 'Setting',
  377:                                  col2 => 'Value',},
  378:                                 {col1 => 'Setting',
  379:                                  col2 => 'Affiliation'},
  380:                                 {col1 => 'User population',
  381:                                  col2 => 'Updatable user data'}],
  382:                      print => \&print_autoupdate,
  383:                      modify => \&modify_autoupdate,
  384:                   },
  385:         'autocreate' => 
  386:                   { text => 'Auto-course creation settings',
  387:                      help => 'Domain_Configuration_Auto_Creation',
  388:                      header => [{col1 => 'Configuration Setting',
  389:                                  col2 => 'Value',}],
  390:                      print => \&print_autocreate,
  391:                      modify => \&modify_autocreate,
  392:                   },
  393:         'directorysrch' => 
  394:                   { text => 'Directory searches',
  395:                     help => 'Domain_Configuration_InstDirectory_Search',
  396:                     header => [{col1 => 'Institutional Directory Setting',
  397:                                 col2 => 'Value',},
  398:                                {col1 => 'LON-CAPA Directory Setting',
  399:                                 col2 => 'Value',}],
  400:                     print => \&print_directorysrch,
  401:                     modify => \&modify_directorysrch,
  402:                   },
  403:         'contacts' =>
  404:                   { text => 'E-mail addresses and helpform',
  405:                     help => 'Domain_Configuration_Contact_Info',
  406:                     header => [{col1 => 'Default e-mail addresses',
  407:                                 col2 => 'Value',},
  408:                                {col1 => 'Recipient(s) for notifications',
  409:                                 col2 => 'Value',},
  410:                                {col1 => 'Nightly status check e-mail',
  411:                                 col2 => 'Settings',},
  412:                                {col1 => 'Ask helpdesk form settings',
  413:                                 col2 => 'Value',},],
  414:                     print => \&print_contacts,
  415:                     modify => \&modify_contacts,
  416:                   },
  417:         'usercreation' => 
  418:                   { text => 'User creation',
  419:                     help => 'Domain_Configuration_User_Creation',
  420:                     header => [{col1 => 'Format rule type',
  421:                                 col2 => 'Format rules in force'},
  422:                                {col1 => 'User account creation',
  423:                                 col2 => 'Usernames which may be created',},
  424:                                {col1 => 'Context',
  425:                                 col2 => 'Assignable authentication types'}],
  426:                     print => \&print_usercreation,
  427:                     modify => \&modify_usercreation,
  428:                   },
  429:         'selfcreation' => 
  430:                   { text => 'Users self-creating accounts',
  431:                     help => 'Domain_Configuration_Self_Creation', 
  432:                     header => [{col1 => 'Self-creation with institutional username',
  433:                                 col2 => 'Enabled?'},
  434:                                {col1 => 'Institutional user type (login/SSO self-creation)',
  435:                                 col2 => 'Information user can enter'},
  436:                                {col1 => 'Self-creation with e-mail verification',
  437:                                 col2 => 'Settings'}],
  438:                     print => \&print_selfcreation,
  439:                     modify => \&modify_selfcreation,
  440:                   },
  441:         'usermodification' =>
  442:                   { text => 'User modification',
  443:                     help => 'Domain_Configuration_User_Modification',
  444:                     header => [{col1 => 'Target user has role',
  445:                                 col2 => 'User information updatable in author context'},
  446:                                {col1 => 'Target user has role',
  447:                                 col2 => 'User information updatable in course context'}],
  448:                     print => \&print_usermodification,
  449:                     modify => \&modify_usermodification,
  450:                   },
  451:         'scantron' =>
  452:                   { text => 'Bubblesheet format',
  453:                     help => 'Domain_Configuration_Scantron_Format',
  454:                     header => [ {col1 => 'Bubblesheet format file',
  455:                                  col2 => ''},
  456:                                 {col1 => 'Bubblesheet data upload formats',
  457:                                  col2 => 'Settings'}],
  458:                     print => \&print_scantron,
  459:                     modify => \&modify_scantron,
  460:                   },
  461:         'requestcourses' => 
  462:                  {text => 'Request creation of courses',
  463:                   help => 'Domain_Configuration_Request_Courses',
  464:                   header => [{col1 => 'User affiliation',
  465:                               col2 => 'Availability/Processing of requests',},
  466:                              {col1 => 'Setting',
  467:                               col2 => 'Value'},
  468:                              {col1 => 'Available textbooks',
  469:                               col2 => ''},
  470:                              {col1 => 'Available templates',
  471:                               col2 => ''},
  472:                              {col1 => 'Validation (not official courses)',
  473:                               col2 => 'Value'},],
  474:                   print => \&print_quotas,
  475:                   modify => \&modify_quotas,
  476:                  },
  477:         'requestauthor' =>
  478:                  {text => 'Request Authoring Space',
  479:                   help => 'Domain_Configuration_Request_Author',
  480:                   header => [{col1 => 'User affiliation',
  481:                               col2 => 'Availability/Processing of requests',},
  482:                              {col1 => 'Setting',
  483:                               col2 => 'Value'}],
  484:                   print => \&print_quotas,
  485:                   modify => \&modify_quotas,
  486:                  },
  487:         'coursecategories' =>
  488:                   { text => 'Cataloging of courses/communities',
  489:                     help => 'Domain_Configuration_Cataloging_Courses',
  490:                     header => [{col1 => 'Catalog type/availability',
  491:                                 col2 => '',},
  492:                                {col1 => 'Category settings for standard catalog',
  493:                                 col2 => '',},
  494:                                {col1 => 'Categories',
  495:                                 col2 => '',
  496:                                }],
  497:                     print => \&print_coursecategories,
  498:                     modify => \&modify_coursecategories,
  499:                   },
  500:         'serverstatuses' =>
  501:                  {text   => 'Access to server status pages',
  502:                   help   => 'Domain_Configuration_Server_Status',
  503:                   header => [{col1 => 'Status Page',
  504:                               col2 => 'Other named users',
  505:                               col3 => 'Specific IPs',
  506:                             }],
  507:                   print => \&print_serverstatuses,
  508:                   modify => \&modify_serverstatuses,
  509:                  },
  510:         'helpsettings' =>
  511:                  {text   => 'Support settings',
  512:                   help   => 'Domain_Configuration_Help_Settings',
  513:                   header => [{col1 => 'Help Page Settings (logged-in users)',
  514:                               col2 => 'Value'},
  515:                              {col1 => 'Helpdesk Roles',
  516:                               col2 => 'Settings'},],
  517:                   print  => \&print_helpsettings,
  518:                   modify => \&modify_helpsettings,
  519:                  },
  520:         'coursedefaults' => 
  521:                  {text => 'Course/Community defaults',
  522:                   help => 'Domain_Configuration_Course_Defaults',
  523:                   header => [{col1 => 'Defaults which can be overridden in each course by a CC',
  524:                               col2 => 'Value',},
  525:                              {col1 => 'Defaults which can be overridden for each course by a DC',
  526:                               col2 => 'Value',},],
  527:                   print => \&print_coursedefaults,
  528:                   modify => \&modify_coursedefaults,
  529:                  },
  530:         'selfenrollment' => 
  531:                  {text   => 'Self-enrollment in Course/Community',
  532:                   help   => 'Domain_Configuration_Selfenrollment',
  533:                   header => [{col1 => 'Configuration Rights',
  534:                               col2 => 'Configured by Course Personnel or Domain Coordinator?'},
  535:                              {col1 => 'Defaults',
  536:                               col2 => 'Value'},
  537:                              {col1 => 'Self-enrollment validation (optional)',
  538:                               col2 => 'Value'},],
  539:                   print => \&print_selfenrollment,
  540:                   modify => \&modify_selfenrollment,
  541:                  },
  542:         'privacy' => 
  543:                  {text   => 'Availability of User Information',
  544:                   help   => 'Domain_Configuration_User_Privacy',
  545:                   header => [{col1 => 'Role assigned in different domain',
  546:                               col2 => 'Approval options'},
  547:                              {col1 => 'Role assigned in different domain to user of type',
  548:                               col2 => 'User information available in that domain'},
  549:                              {col1 => "Role assigned in user's domain",
  550:                               col2 => 'Information viewable by privileged user'},
  551:                              {col1 => "Role assigned in user's domain",
  552:                               col2 => 'Information viewable by unprivileged user'}],
  553:                   print => \&print_privacy,
  554:                   modify => \&modify_privacy,
  555:                  },
  556:         'usersessions' =>
  557:                  {text  => 'User session hosting/offloading',
  558:                   help  => 'Domain_Configuration_User_Sessions',
  559:                   header => [{col1 => 'Domain server',
  560:                               col2 => 'Servers to offload sessions to when busy'},
  561:                              {col1 => 'Hosting of users from other domains',
  562:                               col2 => 'Rules'},
  563:                              {col1 => "Hosting domain's own users elsewhere",
  564:                               col2 => 'Rules'}],
  565:                   print => \&print_usersessions,
  566:                   modify => \&modify_usersessions,
  567:                  },
  568:         'loadbalancing' =>
  569:                  {text  => 'Dedicated Load Balancer(s)',
  570:                   help  => 'Domain_Configuration_Load_Balancing',
  571:                   header => [{col1 => 'Balancers',
  572:                               col2 => 'Default destinations',
  573:                               col3 => 'User affiliation',
  574:                               col4 => 'Overrides'},
  575:                             ],
  576:                   print => \&print_loadbalancing,
  577:                   modify => \&modify_loadbalancing,
  578:                  },
  579:         'ltitools' => 
  580:                  {text => 'External Tools (LTI)',
  581:                   help => 'Domain_Configuration_LTI_Tools',
  582:                   header => [{col1 => 'Setting',
  583:                               col2 => 'Value',}],
  584:                   print => \&print_ltitools,
  585:                   modify => \&modify_ltitools,
  586:                  },
  587:         'proctoring' =>
  588:                  {text => 'Remote Proctoring Integration',
  589:                   help => 'Domain_Configuration_Proctoring',
  590:                   header => [{col1 => 'Name',
  591:                               col2 => 'Configuration'}],
  592:                   print => \&print_proctoring,
  593:                   modify => \&modify_proctoring,
  594:                  },
  595:         'ssl' =>
  596:                  {text  => 'LON-CAPA Network (SSL)',
  597:                   help  => 'Domain_Configuration_Network_SSL',
  598:                   header => [{col1 => 'Server',
  599:                               col2 => 'Certificate Status'},
  600:                              {col1 => 'Connections to other servers',
  601:                               col2 => 'Rules'},
  602:                              {col1 => 'Connections from other servers',
  603:                               col2 => 'Rules'},
  604:                              {col1 => "Replicating domain's published content",
  605:                               col2 => 'Rules'}],
  606:                   print => \&print_ssl,
  607:                   modify => \&modify_ssl,
  608:                  },
  609:         'trust' =>
  610:                  {text   => 'Trust Settings',
  611:                   help   => 'Domain_Configuration_Trust',
  612:                   header => [{col1 => "Access to this domain's content by others",
  613:                               col2 => 'Rules'},
  614:                              {col1 => "Access to other domain's content by this domain",
  615:                               col2 => 'Rules'},
  616:                              {col1 => "Enrollment in this domain's courses by others",
  617:                               col2 => 'Rules',},
  618:                              {col1 => "Co-author roles in this domain for others",
  619:                               col2 => 'Rules',},
  620:                              {col1 => "Co-author roles for this domain's users elsewhere",
  621:                               col2 => 'Rules',},
  622:                              {col1 => "Domain roles in this domain assignable to others",
  623:                               col2 => 'Rules'},
  624:                              {col1 => "Course catalog for this domain displayed elsewhere",
  625:                               col2 => 'Rules'},
  626:                              {col1 => "Requests for creation of courses in this domain by others",
  627:                               col2 => 'Rules'},
  628:                              {col1 => "Users in other domains can send messages to this domain",
  629:                               col2 => 'Rules'},],
  630:                   print => \&print_trust,
  631:                   modify => \&modify_trust,
  632:                  },
  633:           'lti' =>
  634:                  {text => 'LTI Link Protection and LTI Consumers',
  635:                   help => 'Domain_Configuration_LTI_Provider',
  636:                   header => [{col1 => 'Encryption of shared secrets',
  637:                               col2 => 'Settings'},
  638:                              {col1 => 'Rules for shared secrets', 
  639:                               col2 => 'Settings'},
  640:                              {col1 => 'Link Protectors (domain)',
  641:                               col2 => 'Settings'},
  642:                              {col1 => 'Consumers',
  643:                               col2 => 'Settings'},],
  644:                   print => \&print_lti,
  645:                   modify => \&modify_lti,
  646:                  },
  647:            'ipaccess' =>
  648:                        {text => 'IP-based access control',
  649:                         help => 'Domain_Configuration_IP_Access',
  650:                         header => [{col1 => 'Setting',
  651:                                     col2 => 'Value'},],
  652:                         print  => \&print_ipaccess,
  653:                         modify => \&modify_ipaccess,
  654:                        },
  655:     );
  656:     if (keys(%servers) > 1) {
  657:         $prefs{'login'}  = { text   => 'Log-in page options',
  658:                              help   => 'Domain_Configuration_Login_Page',
  659:                             header => [{col1 => 'Log-in Service',
  660:                                         col2 => 'Server Setting',},
  661:                                        {col1 => 'Log-in Page Items',
  662:                                         col2 => 'Settings'},
  663:                                        {col1 => 'Log-in Help',
  664:                                         col2 => 'Value'},
  665:                                        {col1 => 'Custom HTML in document head',
  666:                                         col2 => 'Value'},
  667:                                        {col1 => 'SSO',
  668:                                         col2 => 'Dual login: SSO and non-SSO options'},
  669:                                       ],
  670:                             print => \&print_login,
  671:                             modify => \&modify_login,
  672:                            };
  673:     }
  674: 
  675:     my @roles = ('student','coordinator','author','admin');
  676:     my @actions = &Apache::loncommon::get_env_multiple('form.actions');
  677:     &Apache::lonhtmlcommon::add_breadcrumb
  678:     ({href=>"javascript:changePage(document.$phase,'pickactions')",
  679:       text=>"Settings to display/modify"});
  680:     my $confname = $dom.'-domainconfig';
  681: 
  682:     if ($phase eq 'process') {
  683:         my $result = &Apache::lonconfigsettings::make_changes($r,$dom,$phase,$context,\@prefs_order,
  684:                                                               \%prefs,\%domconfig,$confname,\@roles);
  685:         if ((ref($result) eq 'HASH') && (keys(%{$result}))) {
  686:             $r->rflush();
  687:             &devalidate_remote_domconfs($dom,$result);
  688:         }
  689:     } elsif ($phase eq 'display') {
  690:         my $js = &recaptcha_js().
  691:                  &toggle_display_js();
  692:         if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
  693:             my ($othertitle,$usertypes,$types) =
  694:                 &Apache::loncommon::sorted_inst_types($dom);
  695:             $js .= &lonbalance_targets_js($dom,$types,\%servers,
  696:                                           $domconfig{'loadbalancing'}).
  697:                    &new_spares_js().
  698:                    &common_domprefs_js().
  699:                    &Apache::loncommon::javascript_array_indexof();
  700:         }
  701:         if (grep(/^requestcourses$/,@actions)) {
  702:             my $javascript_validations;
  703:             my $coursebrowserjs=&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}); 
  704:             $js .= <<END;
  705: <script type="text/javascript">
  706: $javascript_validations
  707: </script>
  708: $coursebrowserjs
  709: END
  710:         } elsif (grep(/^ipaccess$/,@actions)) {
  711:             $js .= &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'});
  712:         }
  713:         if (grep(/^selfcreation$/,@actions)) {
  714:             $js .= &selfcreate_javascript();
  715:         }
  716:         if (grep(/^contacts$/,@actions)) {
  717:             $js .= &contacts_javascript();
  718:         }
  719:         if (grep(/^scantron$/,@actions)) {
  720:             $js .= &scantron_javascript();
  721:         }
  722:         &Apache::lonconfigsettings::display_settings($r,$dom,$phase,$context,\@prefs_order,\%prefs,\%domconfig,$confname,$js);
  723:     } else {
  724: # check if domconfig user exists for the domain.
  725:         my $servadm = $r->dir_config('lonAdmEMail');
  726:         my ($configuserok,$author_ok,$switchserver) =
  727:             &config_check($dom,$confname,$servadm);
  728:         unless ($configuserok eq 'ok') {
  729:             &Apache::lonconfigsettings::print_header($r,$phase,$context);
  730:             $r->print(&mt('The domain configuration user "[_1]" has yet to be created.',
  731:                           $confname).
  732:                       '<br />'
  733:             );
  734:             if ($switchserver) {
  735:                 $r->print(&mt('Ordinarily, that domain configuration user is created when the ./UPDATE script is run to install LON-CAPA for the first time.').
  736:                           '<br />'.
  737:                           &mt('However, that does not apply when new domains are added to a multi-domain server, and ./UPDATE has not been run recently.').
  738:                           '<br />'.
  739:                           &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).
  740:                           '<br />'.
  741:                           &mt('To do that now, use the following link: [_1]',$switchserver)
  742:                 );
  743:             } else {
  744:                 $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.').
  745:                           '<br />'.
  746:                           &mt('Once that is done, you will be able to use the web-based "Set domain configuration" to configure the domain')
  747:                 );
  748:             }
  749:             $r->print(&Apache::loncommon::end_page());
  750:             return OK;
  751:         }
  752:         if (keys(%domconfig) == 0) {
  753:             my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
  754:             my @ids=&Apache::lonnet::current_machine_ids();
  755:             if (!grep(/^\Q$primarylibserv\E$/,@ids)) {
  756:                 my %designhash = &Apache::loncommon::get_domainconf($dom);
  757:                 my @loginimages = ('img','logo','domlogo','login');
  758:                 my $custom_img_count = 0;
  759:                 foreach my $img (@loginimages) {
  760:                     if ($designhash{$dom.'.login.'.$img} ne '') {
  761:                         $custom_img_count ++;
  762:                     }
  763:                 }
  764:                 foreach my $role (@roles) {
  765:                     if ($designhash{$dom.'.'.$role.'.img'} ne '') {
  766:                         $custom_img_count ++;
  767:                     }
  768:                 }
  769:                 if ($custom_img_count > 0) {
  770:                     &Apache::lonconfigsettings::print_header($r,$phase,$context);
  771:                     my $switch_server = &check_switchserver($dom,$confname);
  772:                     $r->print(
  773:     &mt('Domain configuration settings have yet to be saved for this domain via the web-based domain preferences interface.').'<br />'.
  774:     &mt("While this remains so, you must switch to the domain's primary library server in order to update settings.").'<br /><br />'.
  775:     &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 />'.
  776:     &mt("However, you will still need to switch to the domain's primary library server to upload new images or logos.").'<br /><br />');
  777:                     if ($switch_server) {
  778:                         $r->print($switch_server.' '.&mt('to primary library server for domain: [_1]',$dom));
  779:                     }
  780:                     $r->print(&Apache::loncommon::end_page());
  781:                     return OK;
  782:                 }
  783:             }
  784:         }
  785:         &Apache::lonconfigsettings::display_choices($r,$phase,$context,\@prefs_order,\%prefs);
  786:     }
  787:     return OK;
  788: }
  789: 
  790: sub process_changes {
  791:     my ($r,$dom,$confname,$action,$roles,$values,$lastactref) = @_;
  792:     my %domconfig;
  793:     if (ref($values) eq 'HASH') {
  794:         %domconfig = %{$values};
  795:     }
  796:     my $output;
  797:     if ($action eq 'login') {
  798:         $output = &modify_login($r,$dom,$confname,$lastactref,%domconfig);
  799:     } elsif ($action eq 'rolecolors') {
  800:         $output = &modify_rolecolors($r,$dom,$confname,$roles,
  801:                                      $lastactref,%domconfig);
  802:     } elsif ($action eq 'quotas') {
  803:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  804:     } elsif ($action eq 'autoenroll') {
  805:         $output = &modify_autoenroll($dom,$lastactref,%domconfig);
  806:     } elsif ($action eq 'autoupdate') {
  807:         $output = &modify_autoupdate($dom,%domconfig);
  808:     } elsif ($action eq 'autocreate') {
  809:         $output = &modify_autocreate($dom,%domconfig);
  810:     } elsif ($action eq 'directorysrch') {
  811:         $output = &modify_directorysrch($dom,$lastactref,%domconfig);
  812:     } elsif ($action eq 'usercreation') {
  813:         $output = &modify_usercreation($dom,%domconfig);
  814:     } elsif ($action eq 'selfcreation') {
  815:         $output = &modify_selfcreation($dom,$lastactref,%domconfig);
  816:     } elsif ($action eq 'usermodification') {
  817:         $output = &modify_usermodification($dom,%domconfig);
  818:     } elsif ($action eq 'contacts') {
  819:         $output = &modify_contacts($dom,$lastactref,%domconfig);
  820:     } elsif ($action eq 'defaults') {
  821:         $output = &modify_defaults($dom,$lastactref,%domconfig);
  822:     } elsif ($action eq 'scantron') {
  823:         $output = &modify_scantron($r,$dom,$confname,$lastactref,%domconfig);
  824:     } elsif ($action eq 'coursecategories') {
  825:         $output = &modify_coursecategories($dom,$lastactref,%domconfig);
  826:     } elsif ($action eq 'serverstatuses') {
  827:         $output = &modify_serverstatuses($dom,%domconfig);
  828:     } elsif ($action eq 'requestcourses') {
  829:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  830:     } elsif ($action eq 'requestauthor') {
  831:         $output = &modify_quotas($r,$dom,$action,$lastactref,%domconfig);
  832:     } elsif ($action eq 'helpsettings') {
  833:         $output = &modify_helpsettings($r,$dom,$confname,$lastactref,%domconfig);
  834:     } elsif ($action eq 'coursedefaults') {
  835:         $output = &modify_coursedefaults($dom,$lastactref,%domconfig);
  836:     } elsif ($action eq 'selfenrollment') {
  837:         $output = &modify_selfenrollment($dom,$lastactref,%domconfig)
  838:     } elsif ($action eq 'usersessions') {
  839:         $output = &modify_usersessions($dom,$lastactref,%domconfig);
  840:     } elsif ($action eq 'loadbalancing') {
  841:         $output = &modify_loadbalancing($dom,%domconfig);
  842:     } elsif ($action eq 'ltitools') {
  843:         $output = &modify_ltitools($r,$dom,$action,$lastactref,%domconfig);
  844:     } elsif ($action eq 'proctoring') {
  845:         $output = &modify_proctoring($r,$dom,$action,$lastactref,%domconfig);
  846:     } elsif ($action eq 'ssl') {
  847:         $output = &modify_ssl($dom,$lastactref,%domconfig);
  848:     } elsif ($action eq 'trust') {
  849:         $output = &modify_trust($dom,$lastactref,%domconfig);
  850:     } elsif ($action eq 'lti') {
  851:         $output = &modify_lti($r,$dom,$action,$lastactref,%domconfig);
  852:     } elsif ($action eq 'privacy') {
  853:         $output = &modify_privacy($dom,%domconfig);
  854:     } elsif ($action eq 'passwords') {
  855:         $output = &modify_passwords($r,$dom,$confname,$lastactref,%domconfig);
  856:     } elsif ($action eq 'wafproxy') {
  857:         $output = &modify_wafproxy($dom,$action,$lastactref,%domconfig);
  858:     } elsif ($action eq 'ipaccess') {
  859:         $output = &modify_ipaccess($dom,$lastactref,%domconfig);
  860:     }
  861:     return $output;
  862: }
  863: 
  864: sub print_config_box {
  865:     my ($r,$dom,$confname,$phase,$action,$item,$settings) = @_;
  866:     my $rowtotal = 0;
  867:     my $output;
  868:     if ($action eq 'coursecategories') {
  869:         $output = &coursecategories_javascript($settings);
  870:     } elsif ($action eq 'defaults') {
  871:         $output = &defaults_javascript($settings); 
  872:     } elsif ($action eq 'passwords') {
  873:         $output = &passwords_javascript($action);
  874:     } elsif ($action eq 'helpsettings') {
  875:         my (%privs,%levelscurrent);
  876:         my %full=();
  877:         my %levels=(
  878:                      course => {},
  879:                      domain => {},
  880:                      system => {},
  881:                    );
  882:         my $context = 'domain';
  883:         my $crstype = 'Course';
  884:         my $formname = 'display';
  885:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
  886:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
  887:         $output =
  888:             &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,\%full, 
  889:                                                       \@templateroles);
  890:     } elsif ($action eq 'ltitools') {
  891:         $output .= &ltitools_javascript($settings);
  892:     } elsif ($action eq 'lti') {
  893:         $output .= &passwords_javascript('secrets')."\n".
  894:                    &lti_javascript($dom,$settings);
  895:     } elsif ($action eq 'proctoring') {
  896:         $output .= &proctoring_javascript($settings);
  897:     } elsif ($action eq 'wafproxy') {
  898:         $output .= &wafproxy_javascript($dom);
  899:     } elsif ($action eq 'autoupdate') {
  900:         $output .= &autoupdate_javascript();
  901:     } elsif ($action eq 'autoenroll') {
  902:         $output .= &autoenroll_javascript();
  903:     } elsif ($action eq 'login') {
  904:         $output .= &saml_javascript();
  905:     } elsif ($action eq 'ipaccess') {
  906:         $output .= &ipaccess_javascript($settings);
  907:     }
  908:     $output .=
  909:          '<table class="LC_nested_outer">
  910:           <tr>
  911:            <th class="LC_left_item LC_middle"><span class="LC_nobreak">'.
  912:            &mt($item->{text}).'&nbsp;'.
  913:            &Apache::loncommon::help_open_topic($item->{'help'}).'</span></th>'."\n".
  914:           '</tr>';
  915:     $rowtotal ++;
  916:     my $numheaders = 1;
  917:     if (ref($item->{'header'}) eq 'ARRAY') {
  918:         $numheaders = scalar(@{$item->{'header'}});
  919:     }
  920:     if ($numheaders > 1) {
  921:         my $colspan = '';
  922:         my $rightcolspan = '';
  923:         my $leftnobr = '';
  924:         if (($action eq 'rolecolors') || ($action eq 'defaults') ||
  925:             ($action eq 'directorysrch') ||
  926:             (($action eq 'login') && ($numheaders < 5))) {
  927:             $colspan = ' colspan="2"';
  928:         }
  929:         if ($action eq 'usersessions') {
  930:             $rightcolspan = ' colspan="3"'; 
  931:         }
  932:         if ($action eq 'passwords') {
  933:             $leftnobr = ' LC_nobreak';
  934:         }
  935:         $output .= '
  936:           <tr>
  937:            <td>
  938:             <table class="LC_nested">
  939:              <tr class="LC_info_row">
  940:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[0]->{'col1'}).'</td>
  941:               <td class="LC_right_item"'.$rightcolspan.'>'.&mt($item->{'header'}->[0]->{'col2'}).'</td>
  942:              </tr>';
  943:         $rowtotal ++;
  944:         if (($action eq 'autoupdate') || ($action eq 'usercreation') || ($action eq 'selfcreation') ||
  945:             ($action eq 'usermodification') || ($action eq 'defaults') || ($action eq 'coursedefaults') ||
  946:             ($action eq 'selfenrollment') || ($action eq 'usersessions') || ($action eq 'ssl') ||
  947:             ($action eq 'directorysrch') || ($action eq 'trust') || ($action eq 'helpsettings') ||
  948:             ($action eq 'contacts') || ($action eq 'privacy') || ($action eq 'wafproxy') || ($action eq 'lti')) {
  949:             $output .= $item->{'print'}->('top',$dom,$settings,\$rowtotal);
  950:         } elsif ($action eq 'passwords') {
  951:             $output .= $item->{'print'}->('top',$dom,$confname,$settings,\$rowtotal);
  952:         } elsif ($action eq 'coursecategories') {
  953:             $output .= $item->{'print'}->('top',$dom,$item,$settings,\$rowtotal);
  954:         } elsif ($action eq 'scantron') {
  955:             $output .= $item->{'print'}->($r,'top',$dom,$confname,$settings,\$rowtotal);
  956:         } elsif ($action eq 'login') {
  957:             if ($numheaders == 5) {
  958:                 $colspan = ' colspan="2"';
  959:                 $output .= &print_login('service',$dom,$confname,$phase,$settings,\$rowtotal);
  960:             } else {
  961:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal);
  962:             }
  963:         } elsif (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
  964:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
  965:         } elsif ($action eq 'rolecolors') {
  966:             $output .= &print_rolecolors($phase,'student',$dom,$confname,$settings,\$rowtotal);
  967:         }
  968:         $output .= '
  969:            </table>
  970:           </td>
  971:          </tr>
  972:          <tr>
  973:            <td>
  974:             <table class="LC_nested">
  975:              <tr class="LC_info_row">
  976:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col1'}).'</td>
  977:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[1]->{'col2'}).'</td>
  978:              </tr>';
  979:             $rowtotal ++;
  980:         if (($action eq 'autoupdate') || ($action eq 'usercreation') ||
  981:             ($action eq 'selfcreation') || ($action eq 'selfenrollment') ||
  982:             ($action eq 'usersessions') || ($action eq 'coursecategories') || 
  983:             ($action eq 'trust') || ($action eq 'contacts') ||
  984:             ($action eq 'privacy') || ($action eq 'passwords') || ($action eq 'lti')) {
  985:             if ($action eq 'coursecategories') {
  986:                 $output .= &print_coursecategories('middle',$dom,$item,$settings,\$rowtotal);
  987:                 $colspan = ' colspan="2"';
  988:             } elsif ($action eq 'trust') {
  989:                 $output .= $item->{'print'}->('shared',$dom,$settings,\$rowtotal);
  990:             } elsif ($action eq 'passwords') {
  991:                 $output .= $item->{'print'}->('middle',$dom,$confname,$settings,\$rowtotal);
  992:             } else {
  993:                 $output .= $item->{'print'}->('middle',$dom,$settings,\$rowtotal);
  994:             }
  995:             if ($action eq 'trust') {
  996:                 $output .= '
  997:             </table>
  998:           </td>
  999:          </tr>';
 1000:                 my @trusthdrs = qw(2 3 4 5 6 7);
 1001:                 my @prefixes = qw(enroll othcoau coaurem domroles catalog reqcrs);
 1002:                 for (my $i=0; $i<@trusthdrs; $i++) {
 1003:                     $output .= '
 1004:          <tr>
 1005:            <td>
 1006:             <table class="LC_nested">
 1007:              <tr class="LC_info_row">
 1008:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col1'}).'</td>
 1009:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[$trusthdrs[$i]]->{'col2'}).'</td></tr>'.
 1010:                            $item->{'print'}->($prefixes[$i],$dom,$settings,\$rowtotal).'
 1011:             </table>
 1012:           </td>
 1013:          </tr>';
 1014:                 }
 1015:                 $output .= '
 1016:          <tr>
 1017:            <td>
 1018:             <table class="LC_nested">
 1019:              <tr class="LC_info_row">
 1020:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col1'}).'</td>
 1021:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[8]->{'col2'}).'</td></tr>'.
 1022:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1023:             } else {
 1024:                 $output .= '
 1025:            </table>
 1026:           </td>
 1027:          </tr>
 1028:          <tr>
 1029:            <td>
 1030:             <table class="LC_nested">
 1031:              <tr class="LC_info_row">
 1032:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1033:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1034:              </tr>'."\n";
 1035:                 if ($action eq 'coursecategories') {
 1036:                     $output .= &print_coursecategories('bottom',$dom,$item,$settings,\$rowtotal);
 1037:                 } elsif (($action eq 'contacts') || ($action eq 'privacy') || 
 1038:                          ($action eq 'passwords') || ($action eq 'lti')) {
 1039:                     if ($action eq 'passwords') {
 1040:                         $output .= $item->{'print'}->('lower',$dom,$confname,$settings,\$rowtotal);
 1041:                     } else {
 1042:                         $output .= $item->{'print'}->('lower',$dom,$settings,\$rowtotal);
 1043:                     }
 1044:                     $output .= '
 1045:              </tr>
 1046:             </table>
 1047:            </td>
 1048:           </tr>
 1049:           <tr>
 1050:            <td>
 1051:             <table class="LC_nested">
 1052:              <tr class="LC_info_row">
 1053:               <td class="LC_left_item'.$leftnobr.'"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1054:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'."\n";
 1055:                     if ($action eq 'passwords') {
 1056:                         $output .= $item->{'print'}->('bottom',$dom,$confname,$settings,\$rowtotal);
 1057:                     } else {
 1058:                         $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1059:                     }
 1060:                     $output .= '
 1061:             </table>
 1062:           </td>
 1063:          </tr>
 1064:          <tr>';
 1065:                 } else {
 1066:                     $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1067:                 }
 1068:             }
 1069:             $rowtotal ++;
 1070:         } elsif (($action eq 'usermodification') || ($action eq 'coursedefaults') ||
 1071:                  ($action eq 'defaults') || ($action eq 'directorysrch') ||
 1072:                  ($action eq 'helpsettings') || ($action eq 'wafproxy')) {
 1073:             $output .= $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1074:         } elsif ($action eq 'scantron') {
 1075:             $output .= $item->{'print'}->($r,'bottom',$dom,$confname,$settings,\$rowtotal);
 1076:         } elsif ($action eq 'ssl') {
 1077:             $output .= $item->{'print'}->('connto',$dom,$settings,\$rowtotal).'
 1078:             </table>
 1079:           </td>
 1080:          </tr>
 1081:          <tr>
 1082:            <td>
 1083:             <table class="LC_nested">
 1084:              <tr class="LC_info_row">
 1085:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1086:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1087:                            $item->{'print'}->('connfrom',$dom,$settings,\$rowtotal).'
 1088:             </table>
 1089:           </td>
 1090:          </tr>
 1091:          <tr>
 1092:            <td>
 1093:             <table class="LC_nested">
 1094:              <tr class="LC_info_row">
 1095:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1096:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td></tr>'.
 1097:                            $item->{'print'}->('bottom',$dom,$settings,\$rowtotal);
 1098:         } elsif ($action eq 'login') {
 1099:             if ($numheaders == 5) {
 1100:                 $output .= &print_login('page',$dom,$confname,$phase,$settings,\$rowtotal).'
 1101:            </table>
 1102:           </td>
 1103:          </tr>
 1104:          <tr>
 1105:            <td>
 1106:             <table class="LC_nested">
 1107:              <tr class="LC_info_row">
 1108:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1109:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td></tr>'.
 1110:                        &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1111:                 $rowtotal ++;
 1112:             } else {
 1113:                 $output .= &print_login('help',$dom,$confname,$phase,$settings,\$rowtotal);
 1114:             }
 1115:             $output .= '
 1116:            </table>
 1117:           </td>
 1118:          </tr>
 1119:          <tr>
 1120:            <td>
 1121:             <table class="LC_nested">
 1122:              <tr class="LC_info_row">';
 1123:             if ($numheaders == 5) {
 1124:                 $output .= '
 1125:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1126:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1127:              </tr>';
 1128:             } else {
 1129:                 $output .= '
 1130:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1131:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col2'}).'</td>
 1132:              </tr>';
 1133:             }
 1134:             $rowtotal ++;
 1135:             $output .= &print_login('headtag',$dom,$confname,$phase,$settings,\$rowtotal).'
 1136:            </table>
 1137:           </td>
 1138:          </tr>
 1139:          <tr>
 1140:            <td>
 1141:             <table class="LC_nested">
 1142:              <tr class="LC_info_row">';
 1143:             if ($numheaders == 5) {
 1144:                 $output .= '
 1145:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1146:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1147:              </tr>';
 1148:             } else {
 1149:                 $output .= '
 1150:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1151:               <td class="LC_right_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1152:              </tr>';
 1153:             }
 1154:             $rowtotal ++;
 1155:             $output .= &print_login('saml',$dom,$confname,$phase,$settings,\$rowtotal);
 1156:         } elsif ($action eq 'requestcourses') {
 1157:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1158:             $rowtotal ++;
 1159:             $output .= &print_studentcode($settings,\$rowtotal).'
 1160:            </table>
 1161:           </td>
 1162:          </tr>
 1163:          <tr>
 1164:            <td>
 1165:             <table class="LC_nested">
 1166:              <tr class="LC_info_row">
 1167:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[2]->{'col1'}).'</td>
 1168:               <td class="LC_right_item">'.&mt($item->{'header'}->[2]->{'col2'}).'</td> </tr>'.
 1169:                        &textbookcourses_javascript($settings).
 1170:                        &print_textbookcourses($dom,'textbooks',$settings,\$rowtotal).'
 1171:             </table>
 1172:            </td>
 1173:           </tr>
 1174:          <tr>
 1175:            <td>
 1176:             <table class="LC_nested">
 1177:              <tr class="LC_info_row">
 1178:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1179:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td> </tr>'.
 1180:                        &print_textbookcourses($dom,'templates',$settings,\$rowtotal).'
 1181:             </table>
 1182:            </td>
 1183:           </tr>
 1184:           <tr>
 1185:            <td>
 1186:             <table class="LC_nested">
 1187:              <tr class="LC_info_row">
 1188:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col1'}).'</td>
 1189:               <td class="LC_right_item" style="vertical-align: top">'.&mt($item->{'header'}->[4]->{'col2'}).'</td>
 1190:              </tr>'.
 1191:             &print_validation_rows('requestcourses',$dom,$settings,\$rowtotal);
 1192:         } elsif ($action eq 'requestauthor') {
 1193:             $output .= &print_requestmail($dom,$action,$settings,\$rowtotal);
 1194:             $rowtotal ++;
 1195:         } elsif ($action eq 'rolecolors') {
 1196:             $output .= &print_rolecolors($phase,'coordinator',$dom,$confname,$settings,\$rowtotal).'
 1197:            </table>
 1198:           </td>
 1199:          </tr>
 1200:          <tr>
 1201:            <td>
 1202:             <table class="LC_nested">
 1203:              <tr class="LC_info_row">
 1204:               <td class="LC_left_item"'.$colspan.' style="vertical-align: top">'.
 1205:                &mt($item->{'header'}->[2]->{'col1'}).'</td>
 1206:               <td class="LC_right_item" style="vertical-align: top">'.
 1207:                &mt($item->{'header'}->[2]->{'col2'}).'</td>
 1208:              </tr>'.
 1209:             &print_rolecolors($phase,'author',$dom,$confname,$settings,\$rowtotal).'
 1210:            </table>
 1211:           </td>
 1212:          </tr>
 1213:          <tr>
 1214:            <td>
 1215:             <table class="LC_nested">
 1216:              <tr class="LC_info_row">
 1217:               <td class="LC_left_item"'.$colspan.'>'.&mt($item->{'header'}->[3]->{'col1'}).'</td>
 1218:               <td class="LC_right_item">'.&mt($item->{'header'}->[3]->{'col2'}).'</td>
 1219:              </tr>'.
 1220:             &print_rolecolors($phase,'admin',$dom,$confname,$settings,\$rowtotal);
 1221:             $rowtotal += 2;
 1222:         }
 1223:     } else {
 1224:         $output .= '
 1225:           <tr>
 1226:            <td>
 1227:             <table class="LC_nested">
 1228:              <tr class="LC_info_row">';
 1229:         if ($action eq 'login') {
 1230:             $output .= '  
 1231:               <td class="LC_left_item" colspan="2">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1232:         } elsif ($action eq 'serverstatuses') {
 1233:             $output .= '
 1234:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).
 1235:               '<br />('.&mt('Automatic access for Dom. Coords.').')</td>';
 1236: 
 1237:         } else {
 1238:             $output .= '
 1239:               <td class="LC_left_item" style="vertical-align: top">'.&mt($item->{'header'}->[0]->{'col1'}).'</td>';
 1240:         }
 1241:         if (defined($item->{'header'}->[0]->{'col3'})) {
 1242:             $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1243:                        &mt($item->{'header'}->[0]->{'col2'});
 1244:             if ($action eq 'serverstatuses') {
 1245:                 $output .= '<br />(<tt>'.&mt('user1:domain1,user2:domain2 etc.').'</tt>)';
 1246:             } 
 1247:         } else {
 1248:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1249:                        &mt($item->{'header'}->[0]->{'col2'});
 1250:         }
 1251:         $output .= '</td>';
 1252:         if ($item->{'header'}->[0]->{'col3'}) {
 1253:             if (defined($item->{'header'}->[0]->{'col4'})) {
 1254:                 $output .= '<td class="LC_left_item" style="vertical-align: top">'.
 1255:                             &mt($item->{'header'}->[0]->{'col3'});
 1256:             } else {
 1257:                 $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1258:                            &mt($item->{'header'}->[0]->{'col3'});
 1259:             }
 1260:             if ($action eq 'serverstatuses') {
 1261:                 $output .= '<br />(<tt>'.&mt('IP1,IP2 etc.').'</tt>)';
 1262:             }
 1263:             $output .= '</td>';
 1264:         }
 1265:         if ($item->{'header'}->[0]->{'col4'}) {
 1266:             $output .= '<td class="LC_right_item" style="vertical-align: top">'.
 1267:                        &mt($item->{'header'}->[0]->{'col4'});
 1268:         }
 1269:         $output .= '</tr>';
 1270:         $rowtotal ++;
 1271:         if ($action eq 'quotas') {
 1272:             $output .= &print_quotas($dom,$settings,\$rowtotal,$action);
 1273:         } elsif (($action eq 'autoenroll') || ($action eq 'autocreate') || 
 1274:                  ($action eq 'serverstatuses') || ($action eq 'loadbalancing') || 
 1275:                  ($action eq 'ltitools') || ($action eq 'proctoring') ||
 1276:                  ($action eq 'ipaccess')) {
 1277:             $output .= $item->{'print'}->($dom,$settings,\$rowtotal);
 1278:         }
 1279:     }
 1280:     $output .= '
 1281:    </table>
 1282:   </td>
 1283:  </tr>
 1284: </table><br />';
 1285:     return ($output,$rowtotal);
 1286: }
 1287: 
 1288: sub print_login {
 1289:     my ($caller,$dom,$confname,$phase,$settings,$rowtotal) = @_;
 1290:     my ($css_class,$datatable,$switchserver,%lt);
 1291:     my %choices = &login_choices();
 1292:     if (($caller eq 'help') || ($caller eq 'headtag') || ($caller eq 'saml')) {
 1293:         %lt = &login_file_options();
 1294:         $switchserver = &check_switchserver($dom,$confname);
 1295:     }
 1296:     if ($caller eq 'service') {
 1297:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 1298:         my $choice = $choices{'disallowlogin'};
 1299:         $css_class = ' class="LC_odd_row"';
 1300:         $datatable .= '<tr'.$css_class.'><td>'.$choice.'</td>'.
 1301:                       '<td style="text-align: right"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1302:                       '<th>'.$choices{'server'}.'</th>'.
 1303:                       '<th>'.$choices{'serverpath'}.'</th>'.
 1304:                       '<th>'.$choices{'custompath'}.'</th>'.
 1305:                       '<th><span class="LC_nobreak">'.$choices{'exempt'}.'</span></th></tr>'."\n";
 1306:         my %disallowed;
 1307:         if (ref($settings) eq 'HASH') {
 1308:             if (ref($settings->{'loginvia'}) eq 'HASH') {
 1309:                %disallowed = %{$settings->{'loginvia'}};
 1310:             }
 1311:         }
 1312:         foreach my $lonhost (sort(keys(%servers))) {
 1313:             my $direct = 'selected="selected"';
 1314:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1315:                 if ($disallowed{$lonhost}{'server'} ne '') {
 1316:                     $direct = '';
 1317:                 }
 1318:             }
 1319:             $datatable .= '<tr><td>'.$servers{$lonhost}.'</td>'.
 1320:                           '<td><select name="'.$lonhost.'_server">'.
 1321:                           '<option value=""'.$direct.'>'.$choices{'directlogin'}.
 1322:                           '</option>';
 1323:             foreach my $hostid (sort(keys(%servers))) {
 1324:                 next if ($servers{$hostid} eq $servers{$lonhost});
 1325:                 my $selected = '';
 1326:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1327:                     if ($hostid eq $disallowed{$lonhost}{'server'}) {
 1328:                         $selected = 'selected="selected"';
 1329:                     }
 1330:                 }
 1331:                 $datatable .= '<option value="'.$hostid.'"'.$selected.'>'.
 1332:                               $servers{$hostid}.'</option>';
 1333:             }
 1334:             $datatable .= '</select></td>'.
 1335:                           '<td><select name="'.$lonhost.'_serverpath">';
 1336:             foreach my $path ('','/','/adm/login','/adm/roles','custom') {
 1337:                 my $pathname = $path;
 1338:                 if ($path eq 'custom') {
 1339:                     $pathname = &mt('Custom Path').' ->';
 1340:                 }
 1341:                 my $selected = '';
 1342:                 if (ref($disallowed{$lonhost}) eq 'HASH') {
 1343:                     if ($path eq $disallowed{$lonhost}{'serverpath'}) {
 1344:                         $selected = 'selected="selected"';
 1345:                     }
 1346:                 } elsif ($path eq '') {
 1347:                     $selected = 'selected="selected"';
 1348:                 }
 1349:                 $datatable .= '<option value="'.$path.'"'.$selected.'>'.$pathname.'</option>';
 1350:             }
 1351:             $datatable .= '</select></td>';
 1352:             my ($custom,$exempt);
 1353:             if (ref($disallowed{$lonhost}) eq 'HASH') {
 1354:                 $custom = $disallowed{$lonhost}{'custompath'};
 1355:                 $exempt = $disallowed{$lonhost}{'exempt'};
 1356:             }
 1357:             $datatable .= '<td><input type="text" name="'.$lonhost.'_custompath" size="6" value="'.$custom.'" /></td>'.
 1358:                           '<td><input type="text" name="'.$lonhost.'_exempt" size="8" value="'.$exempt.'" /></td>'.
 1359:                           '</tr>';
 1360:         }
 1361:         $datatable .= '</table></td></tr>';
 1362:         return $datatable;
 1363:     } elsif ($caller eq 'page') {
 1364:         my %defaultchecked = ( 
 1365:                                'coursecatalog' => 'on',
 1366:                                'helpdesk'      => 'on',
 1367:                                'adminmail'     => 'off',
 1368:                                'newuser'       => 'off',
 1369:                              );
 1370:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
 1371:         my (%checkedon,%checkedoff);
 1372:         foreach my $item (@toggles) {
 1373:             if ($defaultchecked{$item} eq 'on') { 
 1374:                 $checkedon{$item} = ' checked="checked" ';
 1375:                 $checkedoff{$item} = ' ';
 1376:             } elsif ($defaultchecked{$item} eq 'off') {
 1377:                 $checkedoff{$item} = ' checked="checked" ';
 1378:                 $checkedon{$item} = ' ';
 1379:             }
 1380:         }
 1381:         my @images = ('img','logo','domlogo','login');
 1382:         my @alttext = ('img','logo','domlogo');
 1383:         my @logintext = ('textcol','bgcol');
 1384:         my @bgs = ('pgbg','mainbg','sidebg');
 1385:         my @links = ('link','alink','vlink');
 1386:         my %designhash = &Apache::loncommon::get_domainconf($dom);
 1387:         my %defaultdesign = %Apache::loncommon::defaultdesign;
 1388:         my (%is_custom,%designs);
 1389:         my %defaults = (
 1390:                        font => $defaultdesign{'login.font'},
 1391:                        );
 1392:         foreach my $item (@images) {
 1393:             $defaults{$item} = $defaultdesign{'login.'.$item};
 1394:             $defaults{'showlogo'}{$item} = 1;
 1395:         }
 1396:         foreach my $item (@bgs) {
 1397:             $defaults{'bgs'}{$item} = $defaultdesign{'login.'.$item};
 1398:         }
 1399:         foreach my $item (@logintext) {
 1400:             $defaults{'logintext'}{$item} = $defaultdesign{'login.'.$item};
 1401:         }
 1402:         foreach my $item (@links) {
 1403:             $defaults{'links'}{$item} = $defaultdesign{'login.'.$item};
 1404:         }
 1405:         if (ref($settings) eq 'HASH') {
 1406:             foreach my $item (@toggles) {
 1407:                 if ($settings->{$item} eq '1') {
 1408:                     $checkedon{$item} =  ' checked="checked" ';
 1409:                     $checkedoff{$item} = ' ';
 1410:                 } elsif ($settings->{$item} eq '0') {
 1411:                     $checkedoff{$item} =  ' checked="checked" ';
 1412:                     $checkedon{$item} = ' ';
 1413:                 }
 1414:             }
 1415:             foreach my $item (@images) {
 1416:                 if (defined($settings->{$item})) {
 1417:                     $designs{$item} = $settings->{$item};
 1418:                     $is_custom{$item} = 1;
 1419:                 }
 1420:                 if (defined($settings->{'showlogo'}{$item})) {
 1421:                     $designs{'showlogo'}{$item} = $settings->{'showlogo'}{$item};
 1422:                 }
 1423:             }
 1424:             foreach my $item (@alttext) {
 1425:                 if (ref($settings->{'alttext'}) eq 'HASH') {
 1426:                     if ($settings->{'alttext'}->{$item} ne '') {
 1427:                         $designs{'alttext'}{$item} = $settings->{'alttext'}{$item};
 1428:                     }
 1429:                 }
 1430:             }
 1431:             foreach my $item (@logintext) {
 1432:                 if ($settings->{$item} ne '') {
 1433:                     $designs{'logintext'}{$item} = $settings->{$item};
 1434:                     $is_custom{$item} = 1;
 1435:                 }
 1436:             }
 1437:             if ($settings->{'font'} ne '') {
 1438:                 $designs{'font'} = $settings->{'font'};
 1439:                 $is_custom{'font'} = 1;
 1440:             }
 1441:             foreach my $item (@bgs) {
 1442:                 if ($settings->{$item} ne '') {
 1443:                     $designs{'bgs'}{$item} = $settings->{$item};
 1444:                     $is_custom{$item} = 1;
 1445:                 }
 1446:             }
 1447:             foreach my $item (@links) {
 1448:                 if ($settings->{$item} ne '') {
 1449:                     $designs{'links'}{$item} = $settings->{$item};
 1450:                     $is_custom{$item} = 1;
 1451:                 }
 1452:             }
 1453:         } else {
 1454:             if ($designhash{$dom.'.login.font'} ne '') {
 1455:                 $designs{'font'} = $designhash{$dom.'.login.font'};
 1456:                 $is_custom{'font'} = 1;
 1457:             }
 1458:             foreach my $item (@images) {
 1459:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1460:                     $designs{$item} = $designhash{$dom.'.login.'.$item};
 1461:                     $is_custom{$item} = 1;
 1462:                 }
 1463:             }
 1464:             foreach my $item (@bgs) {
 1465:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1466:                     $designs{'bgs'}{$item} = $designhash{$dom.'.login.'.$item};
 1467:                     $is_custom{$item} = 1;
 1468:                 }
 1469:             }
 1470:             foreach my $item (@links) {
 1471:                 if ($designhash{$dom.'.login.'.$item} ne '') {
 1472:                     $designs{'links'}{$item} = $designhash{$dom.'.login.'.$item};
 1473:                     $is_custom{$item} = 1;
 1474:                 }
 1475:             }
 1476:         }
 1477:         my %alt_text = &Apache::lonlocal::texthash  ( img => 'Log-in banner',
 1478:                                                       logo => 'Institution Logo',
 1479:                                                       domlogo => 'Domain Logo',
 1480:                                                       login => 'Login box');
 1481:         my $itemcount = 1;
 1482:         foreach my $item (@toggles) {
 1483:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1484:             $datatable .=  
 1485:                 '<tr'.$css_class.'><td colspan="2">'.$choices{$item}.
 1486:                 '</td><td>'.
 1487:                 '<span class="LC_nobreak"><label><input type="radio" name="'.
 1488:                 $item.'"'.$checkedon{$item}.' value="1" />'.&mt('Yes').
 1489:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'"'.
 1490:                 $checkedoff{$item}.' value="0" />'.&mt('No').'</label></span></td>'.
 1491:                 '</tr>';
 1492:             $itemcount ++;
 1493:         }
 1494:         $datatable .= &display_color_options($dom,$confname,$phase,'login',$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal,\@logintext);
 1495:         $datatable .= '</tr></table></td></tr>';
 1496:     } elsif ($caller eq 'help') {
 1497:         my ($defaulturl,$defaulttype,%url,%type,%langchoices);
 1498:         my $itemcount = 1;
 1499:         $defaulturl = '/adm/loginproblems.html';
 1500:         $defaulttype = 'default';
 1501:         %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
 1502:         my @currlangs;
 1503:         if (ref($settings) eq 'HASH') {
 1504:             if (ref($settings->{'helpurl'}) eq 'HASH') {
 1505:                 foreach my $key (sort(keys(%{$settings->{'helpurl'}}))) {
 1506:                     next if ($settings->{'helpurl'}{$key} eq '');
 1507:                     $url{$key} = $settings->{'helpurl'}{$key}.'?inhibitmenu=yes';
 1508:                     $type{$key} = 'custom';
 1509:                     unless ($key eq 'nolang') {
 1510:                         push(@currlangs,$key);
 1511:                     }
 1512:                 }
 1513:             } elsif ($settings->{'helpurl'} ne '') {
 1514:                 $type{'nolang'} = 'custom';
 1515:                 $url{'nolang'} = $settings->{'helpurl'}.'?inhibitmenu=yes';
 1516:             }
 1517:         }
 1518:         foreach my $lang ('nolang',sort(@currlangs)) {
 1519:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1520:             $datatable .= '<tr'.$css_class.'>';
 1521:             if ($url{$lang} eq '') {
 1522:                 $url{$lang} = $defaulturl;
 1523:             }
 1524:             if ($type{$lang} eq '') {
 1525:                 $type{$lang} = $defaulttype;
 1526:             }
 1527:             $datatable .= '<td colspan="2"><span class="LC_nobreak">';
 1528:             if ($lang eq 'nolang') {
 1529:                 $datatable .= &mt('Log-in help page if no specific language file: [_1]',
 1530:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1531:             } else {
 1532:                 $datatable .= &mt('Log-in help page for language: [_1] is [_2]',
 1533:                                   $langchoices{$lang},
 1534:                                   &Apache::loncommon::modal_link($url{$lang},$lt{$type{$lang}},600,500));
 1535:             }
 1536:             $datatable .= '</span></td>'."\n".
 1537:                           '<td class="LC_left_item">';
 1538:             if ($type{$lang} eq 'custom') {
 1539:                 $datatable .= '<span class="LC_nobreak"><label>'.
 1540:                               '<input type="checkbox" name="loginhelpurl_del" value="'.$lang.'" />'.
 1541:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1542:             } else {
 1543:                 $datatable .= $lt{'upl'};
 1544:             }
 1545:             $datatable .='<br />';
 1546:             if ($switchserver) {
 1547:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1548:             } else {
 1549:                 $datatable .= '<input type="file" name="loginhelpurl_'.$lang.'" />';
 1550:             }
 1551:             $datatable .= '</td></tr>';
 1552:             $itemcount ++;
 1553:         }
 1554:         my @addlangs;
 1555:         foreach my $lang (sort(keys(%langchoices))) {
 1556:             next if ((grep(/^\Q$lang\E$/,@currlangs)) || ($lang eq 'x_chef'));
 1557:             push(@addlangs,$lang);
 1558:         }
 1559:         if (@addlangs > 0) {
 1560:             my %toadd;
 1561:             map { $toadd{$_} = $langchoices{$_} ; } @addlangs;
 1562:             $toadd{''} = &mt('Select');
 1563:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 1564:             $datatable .= '<tr'.$css_class.'><td class="LC_left_item" colspan="2">'.
 1565:                           &mt('Add log-in help page for a specific language:').'&nbsp;'.
 1566:                           &Apache::loncommon::select_form('','loginhelpurl_add_lang',\%toadd).
 1567:                           '</td><td class="LC_left_item">'.$lt{'upl'}.'<br />';
 1568:             if ($switchserver) {
 1569:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1570:             } else {
 1571:                 $datatable .= '<input type="file" name="loginhelpurl_add_file" />';
 1572:             }
 1573:             $datatable .= '</td></tr>';
 1574:             $itemcount ++;
 1575:         }
 1576:         $datatable .= &captcha_choice('login',$settings,$itemcount);
 1577:     } elsif ($caller eq 'headtag') {
 1578:         my %domservers = &Apache::lonnet::get_servers($dom);
 1579:         my $choice = $choices{'headtag'};
 1580:         $css_class = ' class="LC_odd_row"';
 1581:         $datatable .= '<tr'.$css_class.'><td colspan="2">'.$choice.'</td>'.
 1582:                       '<td style="text-align: left"><table><tr><th>'.$choices{'hostid'}.'</th>'.
 1583:                       '<th>'.$choices{'current'}.'</th>'.
 1584:                       '<th>'.$choices{'action'}.'</th>'.
 1585:                       '<th>'.$choices{'exempt'}.'</th></tr>'."\n";
 1586:         my (%currurls,%currexempt);
 1587:         if (ref($settings) eq 'HASH') {
 1588:             if (ref($settings->{'headtag'}) eq 'HASH') {
 1589:                 foreach my $lonhost (keys(%{$settings->{'headtag'}})) {
 1590:                     if (ref($settings->{'headtag'}{$lonhost}) eq 'HASH') {
 1591:                         $currurls{$lonhost} = $settings->{'headtag'}{$lonhost}{'url'};
 1592:                         $currexempt{$lonhost} = $settings->{'headtag'}{$lonhost}{'exempt'};
 1593:                     }
 1594:                 }
 1595:             }
 1596:         }
 1597:         foreach my $lonhost (sort(keys(%domservers))) {
 1598:             my $exempt = &check_exempt_addresses($currexempt{$lonhost});
 1599:             $datatable .= '<tr><td>'.$domservers{$lonhost}.'</td>';
 1600:             if ($currurls{$lonhost}) {
 1601:                 $datatable .= '<td class="LC_right_item"><a href="'.
 1602:                               "javascript:void(open('$currurls{$lonhost}?inhibitmenu=yes','Custom_HeadTag',
 1603:                               'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
 1604:                               '">'.$lt{'curr'}.'</a></td>'.
 1605:                               '<td><span class="LC_nobreak"><label>'.
 1606:                               '<input type="checkbox" name="loginheadtag_del" value="'.$lonhost.'" />'.
 1607:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1608:             } else {
 1609:                 $datatable .= '<td class="LC_right_item">'.$lt{'none'}.'</td><td>'.$lt{'upl'};
 1610:             }
 1611:             $datatable .='<br />';
 1612:             if ($switchserver) {
 1613:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1614:             } else {
 1615:                 $datatable .= '<input type="file" name="loginheadtag_'.$lonhost.'" />';
 1616:             }
 1617:             $datatable .= '</td><td><input type="text" name="loginheadtagexempt_'.$lonhost.'" value="'.$exempt.'" /></td></tr>';
 1618:         }
 1619:         $datatable .= '</table></td></tr>';
 1620:     } elsif ($caller eq 'saml') {
 1621:         my %domservers = &Apache::lonnet::get_servers($dom);
 1622:         $datatable .= '<tr><td colspan="3" style="text-align: left">'.
 1623:                       '<table><tr><th>'.$choices{'hostid'}.'</th>'.
 1624:                       '<th>'.$choices{'samllanding'}.'</th>'.
 1625:                       '<th>'.$choices{'samloptions'}.'</th></tr>'."\n";
 1626:         my (%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso,%styleon,%styleoff);
 1627:         foreach my $lonhost (keys(%domservers)) {
 1628:             $samlurl{$lonhost} = '/adm/sso';
 1629:             $styleon{$lonhost} = 'display:none';
 1630:             $styleoff{$lonhost} = '';
 1631:         }
 1632:         if (ref($settings->{'saml'}) eq 'HASH') {
 1633:             foreach my $lonhost (keys(%{$settings->{'saml'}})) {
 1634:                 if (ref($settings->{'saml'}{$lonhost}) eq 'HASH') {
 1635:                     $saml{$lonhost} = 1;
 1636:                     $samltext{$lonhost} = $settings->{'saml'}{$lonhost}{'text'};
 1637:                     $samlimg{$lonhost} = $settings->{'saml'}{$lonhost}{'img'};
 1638:                     $samlalt{$lonhost} = $settings->{'saml'}{$lonhost}{'alt'};
 1639:                     $samlurl{$lonhost} = $settings->{'saml'}{$lonhost}{'url'};
 1640:                     $samltitle{$lonhost} = $settings->{'saml'}{$lonhost}{'title'};
 1641:                     $samlnotsso{$lonhost} = $settings->{'saml'}{$lonhost}{'notsso'};
 1642:                     $styleon{$lonhost} = '';
 1643:                     $styleoff{$lonhost} = 'display:none';
 1644:                 } else {
 1645:                     $styleon{$lonhost} = 'display:none';
 1646:                     $styleoff{$lonhost} = '';
 1647:                 }
 1648:             }
 1649:         }
 1650:         my $itemcount = 1;
 1651:         foreach my $lonhost (sort(keys(%domservers))) {
 1652:             my $samlon = ' ';
 1653:             my $samloff = ' checked="checked" ';
 1654:             if ($saml{$lonhost}) {
 1655:                 $samlon = $samloff;
 1656:                 $samloff = ' ';
 1657:             }
 1658:             my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1659:             $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.$domservers{$lonhost}.'</span></td>'.
 1660:                           '<td><span class="LC_nobreak"><label><input type="radio" name="saml_'.$lonhost.'"'.$samloff.
 1661:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="0" />'.
 1662:                           &mt('No').'</label>'.('&nbsp;'x2).
 1663:                           '<label><input type="radio" name="saml_'.$lonhost.'"'.$samlon.
 1664:                           'onclick="toggleSamlOptions(this.form,'."'$lonhost'".');" value="1" />'.
 1665:                           &mt('Yes').'</label></span></td>'.
 1666:                           '<td id="samloptionson_'.$lonhost.'" style="'.$styleon{$lonhost}.'" width="100%">'.
 1667:                           '<table><tr><th colspan="5" align="center">'.&mt('SSO').'</th><th align="center">'.
 1668:                           '<span class="LC_nobreak">'.&mt('Non-SSO').'</span></th></tr>'.
 1669:                           '<tr><th>'.&mt('Text').'</th><th>'.&mt('Image').'</th>'.
 1670:                           '<th>'.&mt('Alt Text').'</th><th>'.&mt('URL').'</th>'.
 1671:                           '<th>'.&mt('Tool Tip').'</th><th>'.&mt('Text').'</th></tr>'.
 1672:                           '<tr'.$css_class.'><td><input type="text" name="saml_text_'.$lonhost.'" size="8" value="'.
 1673:                           $samltext{$lonhost}.'" /></td><td>';
 1674:             if ($samlimg{$lonhost}) {
 1675:                 $datatable .= '<img src="'.$samlimg{$lonhost}.'" /><br />'.
 1676:                               '<span class="LC_nobreak"><label>'.
 1677:                               '<input type="checkbox" name="saml_img_del" value="'.$lonhost.'" />'.
 1678:                               $lt{'del'}.'</label>&nbsp;'.$lt{'rep'}.'</span>';
 1679:             } else {
 1680:                 $datatable .= $lt{'upl'};
 1681:             }
 1682:             $datatable .='<br />';
 1683:             if ($switchserver) {
 1684:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 1685:             } else {
 1686:                 $datatable .= '<input type="file" name="saml_img_'.$lonhost.'" />';
 1687:             }
 1688:             $datatable .= '</td>'.
 1689:                           '<td><input type="text" name="saml_alt_'.$lonhost.'" size="20" '.
 1690:                           'value="'.$samlalt{$lonhost}.'" /></td>'.
 1691:                           '<td><input type="text" name="saml_url_'.$lonhost.'" size="8" '.
 1692:                           'value="'.$samlurl{$lonhost}.'" /></td>'.
 1693:                           '<td><textarea name="saml_title_'.$lonhost.'" rows="3" cols="15">'.
 1694:                           $samltitle{$lonhost}.'</textarea></td>'.
 1695:                           '<td><input type="text" name="saml_notsso_'.$lonhost.'" size="8" '.
 1696:                           'value="'.$samlnotsso{$lonhost}.'" /></td></tr>'.
 1697:                           '</table></td>'.
 1698:                           '<td id="samloptionsoff_'.$lonhost.'" style="'.$styleoff{$lonhost}.'" width="100%">&nbsp;</td></tr>';
 1699:            $itemcount ++;
 1700:         }
 1701:         $datatable .= '</table></td></tr>';
 1702:     }
 1703:     return $datatable;
 1704: }
 1705: 
 1706: sub login_choices {
 1707:     my %choices =
 1708:         &Apache::lonlocal::texthash (
 1709:             coursecatalog => 'Display Course/Community Catalog link?',
 1710:             adminmail     => "Display Administrator's E-mail Address?",
 1711:             helpdesk      => 'Display "Contact Helpdesk" link',
 1712:             disallowlogin => "Login page requests redirected",
 1713:             hostid        => "Server",
 1714:             server        => "Redirect to:",
 1715:             serverpath    => "Path",
 1716:             custompath    => "Custom", 
 1717:             exempt        => "Exempt IP(s)",
 1718:             directlogin   => "No redirect",
 1719:             newuser       => "Link to create a user account",
 1720:             img           => "Header",
 1721:             logo          => "Main Logo",
 1722:             domlogo       => "Domain Logo",
 1723:             login         => "Log-in Header", 
 1724:             textcol       => "Text color",
 1725:             bgcol         => "Box color",
 1726:             bgs           => "Background colors",
 1727:             links         => "Link colors",
 1728:             font          => "Font color",
 1729:             pgbg          => "Header",
 1730:             mainbg        => "Page",
 1731:             sidebg        => "Login box",
 1732:             link          => "Link",
 1733:             alink         => "Active link",
 1734:             vlink         => "Visited link",
 1735:             headtag       => "Custom markup",
 1736:             action        => "Action",
 1737:             current       => "Current",
 1738:             samllanding   => "Dual login?",
 1739:             samloptions   => "Options",
 1740:             alttext       => "Alt text",
 1741:         );
 1742:     return %choices;
 1743: }
 1744: 
 1745: sub login_file_options {
 1746:       return &Apache::lonlocal::texthash(
 1747:                                            del     => 'Delete?',
 1748:                                            rep     => 'Replace:',
 1749:                                            upl     => 'Upload:',
 1750:                                            curr    => 'View contents',
 1751:                                            default => 'Default',
 1752:                                            custom  => 'Custom',
 1753:                                            none    => 'None',
 1754:       );
 1755: }
 1756: 
 1757: sub print_ipaccess {
 1758:     my ($dom,$settings,$rowtotal) = @_;
 1759:     my $css_class;
 1760:     my $itemcount = 0;
 1761:     my $datatable;
 1762:     my %ordered;
 1763:     if (ref($settings) eq 'HASH') {
 1764:         foreach my $item (keys(%{$settings})) {
 1765:             if (ref($settings->{$item}) eq 'HASH') {
 1766:                 my $num = $settings->{$item}{'order'};
 1767:                 if ($num eq '') {
 1768:                     $num = scalar(keys(%{$settings}));
 1769:                 }
 1770:                 $ordered{$num} = $item;
 1771:             }
 1772:         }
 1773:     }
 1774:     my $maxnum = scalar(keys(%ordered));
 1775:     if (keys(%ordered)) {
 1776:         my @items = sort { $a <=> $b } keys(%ordered);
 1777:         for (my $i=0; $i<@items; $i++) {
 1778:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1779:             my $item = $ordered{$items[$i]};
 1780:             my ($name,$ipranges,%commblocks,%courses);
 1781:             if (ref($settings->{$item}) eq 'HASH') {
 1782:                 $name = $settings->{$item}->{'name'};
 1783:                 $ipranges = $settings->{$item}->{'ip'};
 1784:                 if (ref($settings->{$item}->{'commblocks'}) eq 'HASH') {
 1785:                     %commblocks = %{$settings->{$item}->{'commblocks'}};
 1786:                 }
 1787:                 if (ref($settings->{$item}->{'courses'}) eq 'HASH') {
 1788:                     %courses = %{$settings->{$item}->{'courses'}};
 1789:                 }
 1790:             }
 1791:             my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_".$item."'".');"';
 1792:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 1793:                          .'<select name="ipaccess_pos_'.$item.'"'.$chgstr.'>';
 1794:             for (my $k=0; $k<=$maxnum; $k++) {
 1795:                 my $vpos = $k+1;
 1796:                 my $selstr;
 1797:                 if ($k == $i) {
 1798:                     $selstr = ' selected="selected" ';
 1799:                 }
 1800:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1801:             }
 1802:             $datatable .= '</select>'.('&nbsp;'x2).
 1803:                 '<label><input type="checkbox" name="ipaccess_del" value="'.$item.'" />'.
 1804:                 &mt('Delete?').'</label></span></td>'.
 1805:                 '<td colspan="2"><input type="hidden" name="ipaccess_id_'.$i.'" value="'.$item.'" />'.
 1806:                 &ipaccess_options($i,$itemcount,$dom,$name,$ipranges,\%commblocks,\%courses).
 1807:                 '</td></tr>';
 1808:             $itemcount ++;
 1809:         }
 1810:     }
 1811:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 1812:     my $chgstr = ' onchange="javascript:reorderIPaccess(this.form,'."'ipaccess_pos_add'".');"';
 1813:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 1814:                   '<input type="hidden" name="ipaccess_maxnum" value="'.$maxnum.'" />'."\n".
 1815:                   '<select name="ipaccess_pos_add"'.$chgstr.'>';
 1816:     for (my $k=0; $k<$maxnum+1; $k++) {
 1817:         my $vpos = $k+1;
 1818:         my $selstr;
 1819:         if ($k == $maxnum) {
 1820:             $selstr = ' selected="selected" ';
 1821:         }
 1822:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 1823:     }
 1824:     $datatable .= '</select>&nbsp;'."\n".
 1825:                   '<input type="checkbox" name="ipaccess_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 1826:                   '<td colspan="2">'.
 1827:                   &ipaccess_options('add',$itemcount,$dom).
 1828:                   '</td>'."\n".
 1829:                   '</tr>'."\n";
 1830:     $$rowtotal ++;
 1831:     return $datatable;
 1832: }
 1833: 
 1834: sub ipaccess_options {
 1835:     my ($num,$itemcount,$dom,$name,$ipranges,$blocksref,$coursesref) = @_;
 1836:     my (%currblocks,%currcourses,$output);
 1837:     if (ref($blocksref) eq 'HASH') {
 1838:         %currblocks = %{$blocksref};
 1839:     }
 1840:     if (ref($coursesref) eq 'HASH') {
 1841:         %currcourses = %{$coursesref};
 1842:     }
 1843:     $output = '<fieldset><legend>'.&mt('Location(s)').'</legend>'.
 1844:               '<span class="LC_nobreak">'.&mt('Name').':&nbsp;'.
 1845:               '<input type="text" name="ipaccess_name_'.$num.'" value="'.$name.'" />'.
 1846:               '</span></fieldset>'.
 1847:               '<fieldset><legend>'.&mt('IP Range(s)').'</legend>'.
 1848:               &mt('Format for each IP range').': '.&mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 1849:               &mt('Range(s) will be stored as IP netblock(s) in CIDR notation (comma separated)').'<br />'.
 1850:               '<textarea name="ipaccess_range_'.$num.'" rows="3" cols="80">'.
 1851:               $ipranges.'</textarea></fieldset>'.
 1852:               '<fieldset><legend>'.&mt('Functionality Blocked?').'</legend>'.
 1853:               &blocker_checkboxes($num,$blocksref).'</fieldset>'.
 1854:               '<fieldset><legend>'.&mt('Courses/Communities allowed').'</legend>'.
 1855:               '<table>';
 1856:     foreach my $cid (sort(keys(%currcourses))) {
 1857:         my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
 1858:         $output .= '<tr><td><span class="LC_nobreak">'.
 1859:                    '<label><input type="checkbox" name="ipaccess_course_delete_'.$num.'" value="'.$cid.'" />'.
 1860:                    &mt('Delete?').'&nbsp;<span class="LC_cusr_emph">'.$courseinfo{'description'}.'</span></label></span>'.
 1861:                    ' <span class="LC_fontsize_medium">('.$cid.')</span></td></tr>';
 1862:     }
 1863:     $output .= '<tr><td><span class="LC_nobreak">'.&mt('Add').':&nbsp;'.
 1864:                '<input type="text" name="ipaccess_cdesc_'.$num.'" value="" onfocus="this.blur();opencrsbrowser('."'display','ipaccess_cnum_$num','ipaccess_cdom_$num','ipaccess_cdesc_$num'".');" />'.
 1865:                 &Apache::loncommon::selectcourse_link('display','ipaccess_cnum_'.$num,'ipaccess_cdom_'.$num,'ipaccess_cdesc_'.$num,$dom,undef,'Course/Community').
 1866:                '<input type="hidden" name="ipaccess_cnum_'.$num.'" value="" />'.
 1867:                '<input type="hidden" name="ipaccess_cdom_'.$num.'" value="" />'.
 1868:                '</span></td></tr></table>'."\n".
 1869:                '</fieldset>';
 1870:     return $output;
 1871: }
 1872: 
 1873: sub blocker_checkboxes {
 1874:     my ($num,$blocks) = @_;
 1875:     my ($typeorder,$types) = &commblocktype_text();
 1876:     my $numinrow = 6;
 1877:     my $output = '<table>';
 1878:     for (my $i=0; $i<@{$typeorder}; $i++) {
 1879:         my $block = $typeorder->[$i];
 1880:         my $blockstatus;
 1881:         if (ref($blocks) eq 'HASH') {
 1882:             if ($blocks->{$block} eq 'on') {
 1883:                 $blockstatus = 'checked="checked"';
 1884:             }
 1885:         }
 1886:         my $rem = $i%($numinrow);
 1887:         if ($rem == 0) {
 1888:             if ($i > 0) {
 1889:                 $output .= '</tr>';
 1890:             }
 1891:             $output .= '<tr>';
 1892:         }
 1893:         if ($i == scalar(@{$typeorder})-1) {
 1894:             my $colsleft = $numinrow-$rem;
 1895:             if ($colsleft > 1) {
 1896:                 $output .= '<td colspan="'.$colsleft.'">';
 1897:             } else {
 1898:                 $output .= '<td>';
 1899:             }
 1900:         } else {
 1901:             $output .= '<td>';
 1902:         }
 1903:         my $item = 'ipaccess_block_'.$num;
 1904:         if ($blockstatus) {
 1905:             $blockstatus = ' '.$blockstatus;
 1906:         }
 1907:         $output .= '<span class="LC_nobreak"><label>'."\n".
 1908:                    '<input type="checkbox" name="'.$item.'"'.
 1909:                    $blockstatus.' value="'.$block.'"'.' />'.
 1910:                    $types->{$block}.'</label></span>'."\n".
 1911:                    '<br /></td>';
 1912:     }
 1913:     $output .= '</tr></table>';
 1914:     return $output;
 1915: }
 1916: 
 1917: sub commblocktype_text {
 1918:     my %types = &Apache::lonlocal::texthash(
 1919:         'com' => 'Messaging',
 1920:         'chat' => 'Chat Room',
 1921:         'boards' => 'Discussion',
 1922:         'port' => 'Portfolio',
 1923:         'groups' => 'Groups',
 1924:         'blogs' => 'Blogs',
 1925:         'about' => 'User Information',
 1926:         'printout' => 'Printouts',
 1927:         'passwd' => 'Change Password',
 1928:         'grades' => 'Gradebook',
 1929:         'search' => 'Course search',
 1930:         'wishlist' => 'Stored links',
 1931:         'annotate' => 'Annotations',
 1932:     );
 1933:     my $typeorder = ['com','chat','boards','port','groups','blogs','about','wishlist','printout','grades','search','annotate','passwd'];
 1934:     return ($typeorder,\%types);
 1935: }
 1936: 
 1937: sub print_rolecolors {
 1938:     my ($phase,$role,$dom,$confname,$settings,$rowtotal) = @_;
 1939:     my %choices = &color_font_choices();
 1940:     my @bgs = ('pgbg','tabbg','sidebg');
 1941:     my @links = ('link','alink','vlink');
 1942:     my @images = ('img');
 1943:     my %alt_text = &Apache::lonlocal::texthash(img => "Banner for $role role");
 1944:     my %designhash = &Apache::loncommon::get_domainconf($dom);
 1945:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 1946:     my (%is_custom,%designs);
 1947:     my %defaults = &role_defaults($role,\@bgs,\@links,\@images);
 1948:     if (ref($settings) eq 'HASH') {
 1949:         if (ref($settings->{$role}) eq 'HASH') {
 1950:             if ($settings->{$role}->{'img'} ne '') {
 1951:                 $designs{'img'} = $settings->{$role}->{'img'};
 1952:                 $is_custom{'img'} = 1;
 1953:             }
 1954:             if ($settings->{$role}->{'font'} ne '') {
 1955:                 $designs{'font'} = $settings->{$role}->{'font'};
 1956:                 $is_custom{'font'} = 1;
 1957:             }
 1958:             if ($settings->{$role}->{'fontmenu'} ne '') {
 1959:                 $designs{'fontmenu'} = $settings->{$role}->{'fontmenu'};
 1960:                 $is_custom{'fontmenu'} = 1;
 1961:             }
 1962:             foreach my $item (@bgs) {
 1963:                 if ($settings->{$role}->{$item} ne '') {
 1964:                     $designs{'bgs'}{$item} = $settings->{$role}->{$item};
 1965:                     $is_custom{$item} = 1;
 1966:                 }
 1967:             }
 1968:             foreach my $item (@links) {
 1969:                 if ($settings->{$role}->{$item} ne '') {
 1970:                     $designs{'links'}{$item} = $settings->{$role}->{$item};
 1971:                     $is_custom{$item} = 1;
 1972:                 }
 1973:             }
 1974:         }
 1975:     } else {
 1976:         if ($designhash{$dom.'.'.$role.'.img'} ne '') {
 1977:             $designs{img} = $designhash{$dom.'.'.$role.'.img'};
 1978:             $is_custom{'img'} = 1;
 1979:         }
 1980:         if ($designhash{$dom.'.'.$role.'.fontmenu'} ne '') {
 1981:             $designs{fontmenu} = $designhash{$dom.'.'.$role.'.fontmenu'};
 1982:             $is_custom{'fontmenu'} = 1; 
 1983:         }
 1984:         if ($designhash{$dom.'.'.$role.'.font'} ne '') {
 1985:             $designs{font} = $designhash{$dom.'.'.$role.'.font'};
 1986:             $is_custom{'font'} = 1;
 1987:         }
 1988:         foreach my $item (@bgs) {
 1989:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1990:                 $designs{'bgs'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1991:                 $is_custom{$item} = 1;
 1992:             
 1993:             }
 1994:         }
 1995:         foreach my $item (@links) {
 1996:             if ($designhash{$dom.'.'.$role.'.'.$item} ne '') {
 1997:                 $designs{'links'}{$item} = $designhash{$dom.'.'.$role.'.'.$item};
 1998:                 $is_custom{$item} = 1;
 1999:             }
 2000:         }
 2001:     }
 2002:     my $itemcount = 1;
 2003:     my $datatable = &display_color_options($dom,$confname,$phase,$role,$itemcount,\%choices,\%is_custom,\%defaults,\%designs,\@images,\@bgs,\@links,\%alt_text,$rowtotal);
 2004:     $datatable .= '</tr></table></td></tr>';
 2005:     return $datatable;
 2006: }
 2007: 
 2008: sub role_defaults {
 2009:     my ($role,$bgs,$links,$images,$logintext) = @_;
 2010:     my %defaults;
 2011:     unless ((ref($bgs) eq 'ARRAY') && (ref($links) eq 'ARRAY') && (ref($images) eq 'ARRAY')) {
 2012:         return %defaults;
 2013:     }
 2014:     my %defaultdesign = %Apache::loncommon::defaultdesign;
 2015:     if ($role eq 'login') {
 2016:         %defaults = (
 2017:                        font => $defaultdesign{$role.'.font'},
 2018:                     );
 2019:         if (ref($logintext) eq 'ARRAY') {
 2020:             foreach my $item (@{$logintext}) {
 2021:                 $defaults{'logintext'}{$item} = $defaultdesign{$role.'.'.$item};
 2022:             }
 2023:         }
 2024:         foreach my $item (@{$images}) {
 2025:             $defaults{'showlogo'}{$item} = 1;
 2026:         }
 2027:     } else {
 2028:         %defaults = (
 2029:                        img => $defaultdesign{$role.'.img'},
 2030:                        font => $defaultdesign{$role.'.font'},
 2031:                        fontmenu => $defaultdesign{$role.'.fontmenu'},
 2032:                     );
 2033:     }
 2034:     foreach my $item (@{$bgs}) {
 2035:         $defaults{'bgs'}{$item} = $defaultdesign{$role.'.'.$item};
 2036:     }
 2037:     foreach my $item (@{$links}) {
 2038:         $defaults{'links'}{$item} = $defaultdesign{$role.'.'.$item};
 2039:     }
 2040:     foreach my $item (@{$images}) {
 2041:         $defaults{$item} = $defaultdesign{$role.'.'.$item};
 2042:     }
 2043:     return %defaults;
 2044: }
 2045: 
 2046: sub display_color_options {
 2047:     my ($dom,$confname,$phase,$role,$itemcount,$choices,$is_custom,$defaults,$designs,
 2048:         $images,$bgs,$links,$alt_text,$rowtotal,$logintext) = @_;
 2049:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
 2050:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2051:     my $datatable = '<tr'.$css_class.'>'.
 2052:         '<td>'.$choices->{'font'}.'</td>';
 2053:     if (!$is_custom->{'font'}) {
 2054:         $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'font'}.';">'.$defaults->{'font'}.'</span></td>';
 2055:     } else {
 2056:         $datatable .= '<td>&nbsp;</td>';
 2057:     }
 2058:     my $current_color = $designs->{'font'} ? $designs->{'font'} : $defaults->{'font'};
 2059: 
 2060:     $datatable .= '<td><span class="LC_nobreak">'.
 2061:                   '<input type="text" class="colorchooser" size="10" name="'.$role.'_font"'.
 2062:                   ' value="'.$current_color.'" />&nbsp;'.
 2063:                   '&nbsp;</span></td></tr>';
 2064:     unless ($role eq 'login') { 
 2065:         $datatable .= '<tr'.$css_class.'>'.
 2066:                       '<td>'.$choices->{'fontmenu'}.'</td>';
 2067:         if (!$is_custom->{'fontmenu'}) {
 2068:             $datatable .=  '<td>'.&mt('Default in use:').'&nbsp;<span class="css_default_'.$role.'_font" style="color: '.$defaults->{'fontmenu'}.';">'.$defaults->{'fontmenu'}.'</span></td>';
 2069:         } else {
 2070:             $datatable .= '<td>&nbsp;</td>';
 2071:         }
 2072: 	$current_color = $designs->{'fontmenu'} ?
 2073: 	    $designs->{'fontmenu'} : $defaults->{'fontmenu'};
 2074:         $datatable .= '<td><span class="LC_nobreak">'.
 2075:                       '<input class="colorchooser" type="text" size="10" name="'
 2076: 		      .$role.'_fontmenu"'.
 2077:                       ' value="'.$current_color.'" />&nbsp;'.
 2078:                       '&nbsp;</span></td></tr>';
 2079:     }
 2080:     my $switchserver = &check_switchserver($dom,$confname);
 2081:     foreach my $img (@{$images}) {
 2082: 	$itemcount ++;
 2083:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2084:         $datatable .= '<tr'.$css_class.'>'.
 2085:                       '<td>'.$choices->{$img};
 2086:         my ($imgfile,$img_import,$login_hdr_pick,$logincolors,$alttext);
 2087:         if ($role eq 'login') {
 2088:             if ($img eq 'login') {
 2089:                 $login_hdr_pick =
 2090:                     &login_header_options($img,$role,$defaults,$is_custom,$choices);
 2091:                 $logincolors =
 2092:                     &login_text_colors($img,$role,$logintext,$phase,$choices,
 2093:                                        $designs,$defaults);
 2094:             } else {
 2095:                 if ($img ne 'domlogo') {
 2096:                     $datatable.= &logo_display_options($img,$defaults,$designs);
 2097:                 }
 2098:                 if (ref($designs->{'alttext'}) eq 'HASH') {
 2099:                     $alttext = $designs->{'alttext'}{$img};
 2100:                 }
 2101:             }
 2102:         }
 2103:         $datatable .= '</td>';
 2104:         if ($designs->{$img} ne '') {
 2105:             $imgfile = $designs->{$img};
 2106: 	    $img_import = ($imgfile =~ m{^/adm/});
 2107:         } else {
 2108:             $imgfile = $defaults->{$img};
 2109:         }
 2110:         if ($imgfile) {
 2111:             my ($showfile,$fullsize);
 2112:             if ($imgfile =~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
 2113:                 my $urldir = $1;
 2114:                 my $filename = $2;
 2115:                 my @info = &Apache::lonnet::stat_file($designs->{$img});
 2116:                 if (@info) {
 2117:                     my $thumbfile = 'tn-'.$filename;
 2118:                     my @thumb=&Apache::lonnet::stat_file($urldir.'/'.$thumbfile);
 2119:                     if (@thumb) {
 2120:                         $showfile = $urldir.'/'.$thumbfile;
 2121:                     } else {
 2122:                         $showfile = $imgfile;
 2123:                     }
 2124:                 } else {
 2125:                     $showfile = '';
 2126:                 }
 2127:             } elsif ($imgfile =~ m-^/(adm/[^/]+)/([^/]+)$-) {
 2128:                 $showfile = $imgfile;
 2129:                 my $imgdir = $1;
 2130:                 my $filename = $2;
 2131:                 if (-e "$londocroot/$imgdir/tn-".$filename) {
 2132:                     $showfile = "/$imgdir/tn-".$filename;
 2133:                 } else {
 2134:                     my $input = $londocroot.$imgfile;
 2135:                     my $output = "$londocroot/$imgdir/tn-".$filename;
 2136:                     if (!-e $output) {
 2137:                         my ($width,$height) = &thumb_dimensions();
 2138:                         my ($fullwidth,$fullheight) = &check_dimensions($input);
 2139:                         if ($fullwidth ne '' && $fullheight ne '') {
 2140:                             if ($fullwidth > $width && $fullheight > $height) { 
 2141:                                 my $size = $width.'x'.$height;
 2142:                                 my @args = ('convert','-sample',$size,$input,$output);
 2143:                                 system({$args[0]} @args);
 2144:                                 $showfile = "/$imgdir/tn-".$filename;
 2145:                             }
 2146:                         }
 2147:                     }
 2148:                 }
 2149:             }
 2150:             if ($showfile) {
 2151:                 if ($showfile =~ m{^/(adm|res)/}) {
 2152:                     if ($showfile =~ m{^/res/}) {
 2153:                         my $local_showfile =
 2154:                             &Apache::lonnet::filelocation('',$showfile);
 2155:                         &Apache::lonnet::repcopy($local_showfile);
 2156:                     }
 2157:                     $showfile = &Apache::loncommon::lonhttpdurl($showfile);
 2158:                 }
 2159:                 if ($imgfile) {
 2160:                     if ($imgfile  =~ m{^/(adm|res)/}) {
 2161:                         if ($imgfile =~ m{^/res/}) {
 2162:                             my $local_imgfile =
 2163:                                 &Apache::lonnet::filelocation('',$imgfile);
 2164:                             &Apache::lonnet::repcopy($local_imgfile);
 2165:                         }
 2166:                         $fullsize = &Apache::loncommon::lonhttpdurl($imgfile);
 2167:                     } else {
 2168:                         $fullsize = $imgfile;
 2169:                     }
 2170:                 }
 2171:                 $datatable .= '<td>';
 2172:                 if ($img eq 'login') {
 2173:                     $datatable .= $login_hdr_pick;
 2174:                 } 
 2175:                 $datatable .= &image_changes($is_custom->{$img},$alt_text->{$img},$img_import,
 2176:                                              $showfile,$fullsize,$role,$img,$imgfile,$logincolors);
 2177:             } else {
 2178:                 $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2179:                               &mt('Upload:').'<br />';
 2180:             }
 2181:         } else {
 2182:             $datatable .= '<td>&nbsp;</td><td class="LC_left_item">'.
 2183:                           &mt('Upload:').'<br />';
 2184:         }
 2185:         if ($switchserver) {
 2186:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2187:         } else {
 2188:             if ($img ne 'login') { # suppress file selection for Log-in header
 2189:                 $datatable .='&nbsp;<input type="file" name="'.$role.'_'.$img.'" />';
 2190:             }
 2191:         }
 2192:         if (($role eq 'login') && ($img ne 'login')) {
 2193:             $datatable .= ('&nbsp;' x2).' <span class="LC_nobreak"><label>'.$choices->{'alttext'}.':'.
 2194:                           '<input type="text" name="'.$role.'_alt_'.$img.'" size="10" value="'.$alttext.'" />'.
 2195:                           '</label></span>';
 2196:         }
 2197:         $datatable .= '</td></tr>';
 2198:     }
 2199:     $itemcount ++;
 2200:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2201:     $datatable .= '<tr'.$css_class.'>'.
 2202:                   '<td>'.$choices->{'bgs'}.'</td>';
 2203:     my $bgs_def;
 2204:     foreach my $item (@{$bgs}) {
 2205:         if (!$is_custom->{$item}) {
 2206:             $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>';
 2207:         }
 2208:     }
 2209:     if ($bgs_def) {
 2210:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$bgs_def.'</tr></table></td>';
 2211:     } else {
 2212:         $datatable .= '<td>&nbsp;</td>';
 2213:     }
 2214:     $datatable .= '<td class="LC_right_item">'.
 2215:                   '<table border="0"><tr>';
 2216: 
 2217:     foreach my $item (@{$bgs}) {
 2218:         $datatable .= '<td style="text-align: center">'.$choices->{$item};
 2219: 	my $color = $designs->{'bgs'}{$item} ? $designs->{'bgs'}{$item} : $defaults->{'bgs'}{$item};
 2220:         if ($designs->{'bgs'}{$item}) {
 2221:             $datatable .= '&nbsp;';
 2222:         }
 2223:         $datatable .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2224:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2225:     }
 2226:     $datatable .= '</tr></table></td></tr>';
 2227:     $itemcount ++;
 2228:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2229:     $datatable .= '<tr'.$css_class.'>'.
 2230:                   '<td>'.$choices->{'links'}.'</td>';
 2231:     my $links_def;
 2232:     foreach my $item (@{$links}) {
 2233:         if (!$is_custom->{$item}) {
 2234:             $links_def .= '<td>'.$choices->{$item}.'<br /><span class="css_default_'.$role.'_'.$item.'" style="color: '.$defaults->{'links'}{$item}.';">'.$defaults->{'links'}{$item}.'</span></td>';
 2235:         }
 2236:     }
 2237:     if ($links_def) {
 2238:         $datatable .= '<td>'.&mt('Default(s) in use:').'<br /><table border="0"><tr>'.$links_def.'</tr></table></td>';
 2239:     } else {
 2240:         $datatable .= '<td>&nbsp;</td>';
 2241:     }
 2242:     $datatable .= '<td class="LC_right_item">'.
 2243:                   '<table border="0"><tr>';
 2244:     foreach my $item (@{$links}) {
 2245: 	my $color = $designs->{'links'}{$item} ? $designs->{'links'}{$item} : $defaults->{'links'}{$item};
 2246:         $datatable .= '<td style="text-align: center">'.$choices->{$item}."\n";
 2247:         if ($designs->{'links'}{$item}) {
 2248:             $datatable.='&nbsp;';
 2249:         }
 2250:         $datatable .= '<br /><input type="text" size="8" class="colorchooser" name="'.$role.'_'.$item.'" value="'.$color.
 2251:                       '" /></td>';
 2252:     }
 2253:     $$rowtotal += $itemcount;
 2254:     return $datatable;
 2255: }
 2256: 
 2257: sub logo_display_options {
 2258:     my ($img,$defaults,$designs) = @_;
 2259:     my $checkedon;
 2260:     if (ref($defaults) eq 'HASH') {
 2261:         if (ref($defaults->{'showlogo'}) eq 'HASH') {
 2262:             if ($defaults->{'showlogo'}{$img}) {
 2263:                 $checkedon = 'checked="checked" ';     
 2264:             }
 2265:         } 
 2266:     }
 2267:     if (ref($designs) eq 'HASH') {
 2268:         if (ref($designs->{'showlogo'}) eq 'HASH') {
 2269:             if (defined($designs->{'showlogo'}{$img})) {
 2270:                 if ($designs->{'showlogo'}{$img} == 0) {
 2271:                     $checkedon = '';
 2272:                 } elsif ($designs->{'showlogo'}{$img} == 1) {
 2273:                     $checkedon = 'checked="checked" ';
 2274:                 }
 2275:             }
 2276:         }
 2277:     }
 2278:     return '<br /><label>&nbsp;&nbsp;<input type="checkbox" name="'.
 2279:            'login_showlogo_'.$img.'" value="1" '.$checkedon.'/>'.
 2280:            &mt('show').'</label>'."\n";
 2281: }
 2282: 
 2283: sub login_header_options  {
 2284:     my ($img,$role,$defaults,$is_custom,$choices) = @_;
 2285:     my $output = '';
 2286:     if ((!$is_custom->{'textcol'}) || (!$is_custom->{'bgcol'})) {
 2287:         $output .= &mt('Text default(s):').'<br />';
 2288:         if (!$is_custom->{'textcol'}) {
 2289:             $output .= $choices->{'textcol'}.':&nbsp;'.$defaults->{'logintext'}{'textcol'}.
 2290:                        '&nbsp;&nbsp;&nbsp;';
 2291:         }
 2292:         if (!$is_custom->{'bgcol'}) {
 2293:             $output .= $choices->{'bgcol'}.':&nbsp;'.
 2294:                        '<span id="css_'.$role.'_font" style="background-color: '.
 2295:                        $defaults->{'logintext'}{'bgcol'}.';">&nbsp;&nbsp;&nbsp;</span>';
 2296:         }
 2297:         $output .= '<br />';
 2298:     }
 2299:     $output .='<br />';
 2300:     return $output;
 2301: }
 2302: 
 2303: sub login_text_colors {
 2304:     my ($img,$role,$logintext,$phase,$choices,$designs,$defaults) = @_;
 2305:     my $color_menu = '<table border="0"><tr>';
 2306:     foreach my $item (@{$logintext}) {
 2307:         $color_menu .= '<td style="text-align: center">'.$choices->{$item};
 2308:         my $color = $designs->{'logintext'}{$item} ? $designs->{'logintext'}{$item} : $defaults->{'logintext'}{$item};
 2309:         $color_menu .= '<br /><input type="text" class="colorchooser" size="8" name="'.$role.'_'.$item.'" value="'.$color.
 2310:                       '" onblur = "javascript:colchg_span('."'css_".$role.'_'.$item."'".',this);" /></td>';
 2311:     }
 2312:     $color_menu .= '</tr></table><br />';
 2313:     return $color_menu;
 2314: }
 2315: 
 2316: sub image_changes {
 2317:     my ($is_custom,$alt_text,$img_import,$showfile,$fullsize,$role,$img,$imgfile,$logincolors) = @_;
 2318:     my $output;
 2319:     if ($img eq 'login') {
 2320:         $output = '</td><td>'.$logincolors; # suppress image for Log-in header
 2321:     } elsif (!$is_custom) {
 2322:         if ($img ne 'domlogo') {
 2323:             $output = &mt('Default image:').'<br />';
 2324:         } else {
 2325:             $output = &mt('Default in use:').'<br />';
 2326:         }
 2327:     }
 2328:     if ($img ne 'login') {
 2329:         if ($img_import) {
 2330:             $output .= '<input type="hidden" name="'.$role.'_import_'.$img.'" value="'.$imgfile.'" />';
 2331:         }
 2332:         $output .= '<a href="'.$fullsize.'" target="_blank"><img src="'.
 2333:                    $showfile.'" alt="'.$alt_text.'" border="0" /></a></td>';
 2334:         if ($is_custom) {
 2335:             $output .= '<td>'.$logincolors.'<span class="LC_nobreak"><label>'.
 2336:                        '<input type="checkbox" name="'.
 2337:                        $role.'_del_'.$img.'" value="1" />'.&mt('Delete?').
 2338:                        '</label>&nbsp;'.&mt('Replace:').'</span><br />';
 2339:         } else {
 2340:             $output .= '<td class="LC_middle">'.$logincolors.&mt('Upload:').'<br />';
 2341:         }
 2342:     }
 2343:     return $output;
 2344: }
 2345: 
 2346: sub print_quotas {
 2347:     my ($dom,$settings,$rowtotal,$action) = @_;
 2348:     my $context;
 2349:     if ($action eq 'quotas') {
 2350:         $context = 'tools';
 2351:     } else {
 2352:         $context = $action;
 2353:     }
 2354:     my ($datatable,$defaultquota,$authorquota,@usertools,@options,%validations);
 2355:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 2356:     my $typecount = 0;
 2357:     my ($css_class,%titles);
 2358:     if ($context eq 'requestcourses') {
 2359:         @usertools = ('official','unofficial','community','textbook','placement','lti');
 2360:         @options =('norequest','approval','validate','autolimit');
 2361:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
 2362:         %titles = &courserequest_titles();
 2363:     } elsif ($context eq 'requestauthor') {
 2364:         @usertools = ('author');
 2365:         @options = ('norequest','approval','automatic');
 2366:         %titles = &authorrequest_titles();
 2367:     } else {
 2368:         @usertools = ('aboutme','blog','webdav','portfolio');
 2369:         %titles = &tool_titles();
 2370:     }
 2371:     if (ref($types) eq 'ARRAY') {
 2372:         foreach my $type (@{$types}) {
 2373:             my ($currdefquota,$currauthorquota);
 2374:             unless (($context eq 'requestcourses') ||
 2375:                     ($context eq 'requestauthor')) {
 2376:                 if (ref($settings) eq 'HASH') {
 2377:                     if (ref($settings->{defaultquota}) eq 'HASH') {
 2378:                         $currdefquota = $settings->{defaultquota}->{$type};
 2379:                     } else {
 2380:                         $currdefquota = $settings->{$type};
 2381:                     }
 2382:                     if (ref($settings->{authorquota}) eq 'HASH') {
 2383:                         $currauthorquota = $settings->{authorquota}->{$type};
 2384:                     }
 2385:                 }
 2386:             }
 2387:             if (defined($usertypes->{$type})) {
 2388:                 $typecount ++;
 2389:                 $css_class = $typecount%2?' class="LC_odd_row"':'';
 2390:                 $datatable .= '<tr'.$css_class.'>'.
 2391:                               '<td>'.$usertypes->{$type}.'</td>'.
 2392:                               '<td class="LC_left_item">';
 2393:                 if ($context eq 'requestcourses') {
 2394:                     $datatable .= '<table><tr>';
 2395:                 }
 2396:                 my %cell;  
 2397:                 foreach my $item (@usertools) {
 2398:                     if ($context eq 'requestcourses') {
 2399:                         my ($curroption,$currlimit);
 2400:                         if (ref($settings) eq 'HASH') {
 2401:                             if (ref($settings->{$item}) eq 'HASH') {
 2402:                                 $curroption = $settings->{$item}->{$type};
 2403:                                 if ($curroption =~ /^autolimit=(\d*)$/) {
 2404:                                     $currlimit = $1; 
 2405:                                 }
 2406:                             }
 2407:                         }
 2408:                         if (!$curroption) {
 2409:                             $curroption = 'norequest';
 2410:                         }
 2411:                         $datatable .= '<th>'.$titles{$item}.'</th>';
 2412:                         foreach my $option (@options) {
 2413:                             my $val = $option;
 2414:                             if ($option eq 'norequest') {
 2415:                                 $val = 0;  
 2416:                             }
 2417:                             if ($option eq 'validate') {
 2418:                                 my $canvalidate = 0;
 2419:                                 if (ref($validations{$item}) eq 'HASH') { 
 2420:                                     if ($validations{$item}{$type}) {
 2421:                                         $canvalidate = 1;
 2422:                                     }
 2423:                                 }
 2424:                                 next if (!$canvalidate);
 2425:                             }
 2426:                             my $checked = '';
 2427:                             if ($option eq $curroption) {
 2428:                                 $checked = ' checked="checked"';
 2429:                             } elsif ($option eq 'autolimit') {
 2430:                                 if ($curroption =~ /^autolimit/) {
 2431:                                     $checked = ' checked="checked"';
 2432:                                 }                       
 2433:                             } 
 2434:                             $cell{$item} .= '<span class="LC_nobreak"><label>'.
 2435:                                   '<input type="radio" name="crsreq_'.$item.
 2436:                                   '_'.$type.'" value="'.$val.'"'.$checked.' />'.
 2437:                                   $titles{$option}.'</label>';
 2438:                             if ($option eq 'autolimit') {
 2439:                                 $cell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2440:                                                 $item.'_limit_'.$type.'" size="1" '.
 2441:                                                 'value="'.$currlimit.'" />';
 2442:                             }
 2443:                             $cell{$item} .= '</span> ';
 2444:                             if ($option eq 'autolimit') {
 2445:                                 $cell{$item} .= $titles{'unlimited'};
 2446:                             }
 2447:                         }
 2448:                     } elsif ($context eq 'requestauthor') {
 2449:                         my $curroption;
 2450:                         if (ref($settings) eq 'HASH') {
 2451:                             $curroption = $settings->{$type};
 2452:                         }
 2453:                         if (!$curroption) {
 2454:                             $curroption = 'norequest';
 2455:                         }
 2456:                         foreach my $option (@options) {
 2457:                             my $val = $option;
 2458:                             if ($option eq 'norequest') {
 2459:                                 $val = 0;
 2460:                             }
 2461:                             my $checked = '';
 2462:                             if ($option eq $curroption) {
 2463:                                 $checked = ' checked="checked"';
 2464:                             }
 2465:                             $datatable .= '<span class="LC_nobreak"><label>'.
 2466:                                   '<input type="radio" name="authorreq_'.$type.
 2467:                                   '" value="'.$val.'"'.$checked.' />'.
 2468:                                   $titles{$option}.'</label></span>&nbsp; ';
 2469:                         }
 2470:                     } else {
 2471:                         my $checked = 'checked="checked" ';
 2472:                         if (ref($settings) eq 'HASH') {
 2473:                             if (ref($settings->{$item}) eq 'HASH') {
 2474:                                 if ($settings->{$item}->{$type} == 0) {
 2475:                                     $checked = '';
 2476:                                 } elsif ($settings->{$item}->{$type} == 1) {
 2477:                                     $checked =  'checked="checked" ';
 2478:                                 }
 2479:                             }
 2480:                         }
 2481:                         $datatable .= '<span class="LC_nobreak"><label>'.
 2482:                                       '<input type="checkbox" name="'.$context.'_'.$item.
 2483:                                       '" value="'.$type.'" '.$checked.'/>'.$titles{$item}.
 2484:                                       '</label></span>&nbsp; ';
 2485:                     }
 2486:                 }
 2487:                 if ($context eq 'requestcourses') {
 2488:                     $datatable .= '</tr><tr>';
 2489:                     foreach my $item (@usertools) {
 2490:                         $datatable .= '<td style="vertical-align: top">'.$cell{$item}.'</td>';  
 2491:                     }
 2492:                     $datatable .= '</tr></table>';
 2493:                 }
 2494:                 $datatable .= '</td>';
 2495:                 unless (($context eq 'requestcourses') ||
 2496:                         ($context eq 'requestauthor')) {
 2497:                     $datatable .= 
 2498:                               '<td class="LC_right_item">'.
 2499:                               '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2500:                               '<input type="text" name="quota_'.$type.
 2501:                               '" value="'.$currdefquota.
 2502:                               '" size="5" /></span>'.('&nbsp;' x 2).
 2503:                               '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2504:                               '<input type="text" name="authorquota_'.$type.
 2505:                               '" value="'.$currauthorquota.
 2506:                               '" size="5" /></span></td>';
 2507:                 }
 2508:                 $datatable .= '</tr>';
 2509:             }
 2510:         }
 2511:     }
 2512:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2513:         $defaultquota = '20';
 2514:         $authorquota = '500';
 2515:         if (ref($settings) eq 'HASH') {
 2516:             if (ref($settings->{'defaultquota'}) eq 'HASH') {
 2517:                 $defaultquota = $settings->{'defaultquota'}->{'default'};
 2518:             } elsif (defined($settings->{'default'})) {
 2519:                 $defaultquota = $settings->{'default'};
 2520:             }
 2521:             if (ref($settings->{'authorquota'}) eq 'HASH') {
 2522:                 $authorquota = $settings->{'authorquota'}->{'default'};
 2523:             }
 2524:         }
 2525:     }
 2526:     $typecount ++;
 2527:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2528:     $datatable .= '<tr'.$css_class.'>'.
 2529:                   '<td>'.$othertitle.'</td>'.
 2530:                   '<td class="LC_left_item">';
 2531:     if ($context eq 'requestcourses') {
 2532:         $datatable .= '<table><tr>';
 2533:     }
 2534:     my %defcell;
 2535:     foreach my $item (@usertools) {
 2536:         if ($context eq 'requestcourses') {
 2537:             my ($curroption,$currlimit);
 2538:             if (ref($settings) eq 'HASH') {
 2539:                 if (ref($settings->{$item}) eq 'HASH') {
 2540:                     $curroption = $settings->{$item}->{'default'};
 2541:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2542:                         $currlimit = $1;
 2543:                     }
 2544:                 }
 2545:             }
 2546:             if (!$curroption) {
 2547:                 $curroption = 'norequest';
 2548:             }
 2549:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2550:             foreach my $option (@options) {
 2551:                 my $val = $option;
 2552:                 if ($option eq 'norequest') {
 2553:                     $val = 0;
 2554:                 }
 2555:                 if ($option eq 'validate') {
 2556:                     my $canvalidate = 0;
 2557:                     if (ref($validations{$item}) eq 'HASH') {
 2558:                         if ($validations{$item}{'default'}) {
 2559:                             $canvalidate = 1;
 2560:                         }
 2561:                     }
 2562:                     next if (!$canvalidate);
 2563:                 }
 2564:                 my $checked = '';
 2565:                 if ($option eq $curroption) {
 2566:                     $checked = ' checked="checked"';
 2567:                 } elsif ($option eq 'autolimit') {
 2568:                     if ($curroption =~ /^autolimit/) {
 2569:                         $checked = ' checked="checked"';
 2570:                     }
 2571:                 }
 2572:                 $defcell{$item} .= '<span class="LC_nobreak"><label>'.
 2573:                                   '<input type="radio" name="crsreq_'.$item.
 2574:                                   '_default" value="'.$val.'"'.$checked.' />'.
 2575:                                   $titles{$option}.'</label>';
 2576:                 if ($option eq 'autolimit') {
 2577:                     $defcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2578:                                        $item.'_limit_default" size="1" '.
 2579:                                        'value="'.$currlimit.'" />';
 2580:                 }
 2581:                 $defcell{$item} .= '</span> ';
 2582:                 if ($option eq 'autolimit') {
 2583:                     $defcell{$item} .= $titles{'unlimited'};
 2584:                 }
 2585:             }
 2586:         } elsif ($context eq 'requestauthor') {
 2587:             my $curroption;
 2588:             if (ref($settings) eq 'HASH') {
 2589:                 $curroption = $settings->{'default'};
 2590:             }
 2591:             if (!$curroption) {
 2592:                 $curroption = 'norequest';
 2593:             }
 2594:             foreach my $option (@options) {
 2595:                 my $val = $option;
 2596:                 if ($option eq 'norequest') {
 2597:                     $val = 0;
 2598:                 }
 2599:                 my $checked = '';
 2600:                 if ($option eq $curroption) {
 2601:                     $checked = ' checked="checked"';
 2602:                 }
 2603:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2604:                               '<input type="radio" name="authorreq_default"'.
 2605:                               ' value="'.$val.'"'.$checked.' />'.
 2606:                               $titles{$option}.'</label></span>&nbsp; ';
 2607:             }
 2608:         } else {
 2609:             my $checked = 'checked="checked" ';
 2610:             if (ref($settings) eq 'HASH') {
 2611:                 if (ref($settings->{$item}) eq 'HASH') {
 2612:                     if ($settings->{$item}->{'default'} == 0) {
 2613:                         $checked = '';
 2614:                     } elsif ($settings->{$item}->{'default'} == 1) {
 2615:                         $checked = 'checked="checked" ';
 2616:                     }
 2617:                 }
 2618:             }
 2619:             $datatable .= '<span class="LC_nobreak"><label>'.
 2620:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2621:                           '" value="default" '.$checked.'/>'.$titles{$item}.
 2622:                           '</label></span>&nbsp; ';
 2623:         }
 2624:     }
 2625:     if ($context eq 'requestcourses') {
 2626:         $datatable .= '</tr><tr>';
 2627:         foreach my $item (@usertools) {
 2628:             $datatable .= '<td style="vertical-align: top">'.$defcell{$item}.'</td>';
 2629:         }
 2630:         $datatable .= '</tr></table>';
 2631:     }
 2632:     $datatable .= '</td>';
 2633:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
 2634:         $datatable .= '<td class="LC_right_item">'.
 2635:                       '<span class="LC_nobreak">'.&mt('Portfolio').':&nbsp;'.
 2636:                       '<input type="text" name="defaultquota" value="'.
 2637:                       $defaultquota.'" size="5" /></span>'.('&nbsp;' x2).
 2638:                       '<span class="LC_nobreak">'.&mt('Authoring').':&nbsp;'.
 2639:                       '<input type="text" name="authorquota" value="'.
 2640:                       $authorquota.'" size="5" /></span></td>';
 2641:     }
 2642:     $datatable .= '</tr>';
 2643:     $typecount ++;
 2644:     $css_class = $typecount%2?' class="LC_odd_row"':'';
 2645:     $datatable .= '<tr'.$css_class.'>'.
 2646:                   '<td>'.&mt('LON-CAPA Advanced Users').'<br />';
 2647:     if ($context eq 'requestcourses') {
 2648:         $datatable .= &mt('(overrides affiliation, if set)').
 2649:                       '</td>'.
 2650:                       '<td class="LC_left_item">'.
 2651:                       '<table><tr>';
 2652:     } else {
 2653:         $datatable .= &mt('(overrides affiliation, if checked)').
 2654:                       '</td>'.
 2655:                       '<td class="LC_left_item" colspan="2">'.
 2656:                       '<br />';
 2657:     }
 2658:     my %advcell;
 2659:     foreach my $item (@usertools) {
 2660:         if ($context eq 'requestcourses') {
 2661:             my ($curroption,$currlimit);
 2662:             if (ref($settings) eq 'HASH') {
 2663:                 if (ref($settings->{$item}) eq 'HASH') {
 2664:                     $curroption = $settings->{$item}->{'_LC_adv'};
 2665:                     if ($curroption =~ /^autolimit=(\d*)$/) {
 2666:                         $currlimit = $1;
 2667:                     }
 2668:                 }
 2669:             }
 2670:             $datatable .= '<th>'.$titles{$item}.'</th>';
 2671:             my $checked = '';
 2672:             if ($curroption eq '') {
 2673:                 $checked = ' checked="checked"';
 2674:             }
 2675:             $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2676:                                '<input type="radio" name="crsreq_'.$item.
 2677:                                '__LC_adv" value=""'.$checked.' />'.
 2678:                                &mt('No override set').'</label></span>&nbsp; ';
 2679:             foreach my $option (@options) {
 2680:                 my $val = $option;
 2681:                 if ($option eq 'norequest') {
 2682:                     $val = 0;
 2683:                 }
 2684:                 if ($option eq 'validate') {
 2685:                     my $canvalidate = 0;
 2686:                     if (ref($validations{$item}) eq 'HASH') {
 2687:                         if ($validations{$item}{'_LC_adv'}) {
 2688:                             $canvalidate = 1;
 2689:                         }
 2690:                     }
 2691:                     next if (!$canvalidate);
 2692:                 }
 2693:                 my $checked = '';
 2694:                 if ($val eq $curroption) {
 2695:                     $checked = ' checked="checked"';
 2696:                 } elsif ($option eq 'autolimit') {
 2697:                     if ($curroption =~ /^autolimit/) {
 2698:                         $checked = ' checked="checked"';
 2699:                     }
 2700:                 }
 2701:                 $advcell{$item} .= '<span class="LC_nobreak"><label>'.
 2702:                                   '<input type="radio" name="crsreq_'.$item.
 2703:                                   '__LC_adv" value="'.$val.'"'.$checked.' />'.
 2704:                                   $titles{$option}.'</label>';
 2705:                 if ($option eq 'autolimit') {
 2706:                     $advcell{$item} .= '&nbsp;<input type="text" name="crsreq_'.
 2707:                                        $item.'_limit__LC_adv" size="1" '.
 2708:                                        'value="'.$currlimit.'" />';
 2709:                 }
 2710:                 $advcell{$item} .= '</span> ';
 2711:                 if ($option eq 'autolimit') {
 2712:                     $advcell{$item} .= $titles{'unlimited'};
 2713:                 }
 2714:             }
 2715:         } elsif ($context eq 'requestauthor') {
 2716:             my $curroption;
 2717:             if (ref($settings) eq 'HASH') {
 2718:                 $curroption = $settings->{'_LC_adv'};
 2719:             }
 2720:             my $checked = '';
 2721:             if ($curroption eq '') {
 2722:                 $checked = ' checked="checked"';
 2723:             }
 2724:             $datatable .= '<span class="LC_nobreak"><label>'.
 2725:                           '<input type="radio" name="authorreq__LC_adv"'.
 2726:                           ' value=""'.$checked.' />'.
 2727:                           &mt('No override set').'</label></span>&nbsp; ';
 2728:             foreach my $option (@options) {
 2729:                 my $val = $option;
 2730:                 if ($option eq 'norequest') {
 2731:                     $val = 0;
 2732:                 }
 2733:                 my $checked = '';
 2734:                 if ($val eq $curroption) {
 2735:                     $checked = ' checked="checked"';
 2736:                 }
 2737:                 $datatable .= '<span class="LC_nobreak"><label>'.
 2738:                               '<input type="radio" name="authorreq__LC_adv"'.
 2739:                               ' value="'.$val.'"'.$checked.' />'.
 2740:                               $titles{$option}.'</label></span>&nbsp; ';
 2741:             }
 2742:         } else {
 2743:             my $checked = 'checked="checked" ';
 2744:             if (ref($settings) eq 'HASH') {
 2745:                 if (ref($settings->{$item}) eq 'HASH') {
 2746:                     if ($settings->{$item}->{'_LC_adv'} == 0) {
 2747:                         $checked = '';
 2748:                     } elsif ($settings->{$item}->{'_LC_adv'} == 1) {
 2749:                         $checked = 'checked="checked" ';
 2750:                     }
 2751:                 }
 2752:             }
 2753:             $datatable .= '<span class="LC_nobreak"><label>'.
 2754:                           '<input type="checkbox" name="'.$context.'_'.$item.
 2755:                           '" value="_LC_adv" '.$checked.'/>'.$titles{$item}.
 2756:                           '</label></span>&nbsp; ';
 2757:         }
 2758:     }
 2759:     if ($context eq 'requestcourses') {
 2760:         $datatable .= '</tr><tr>';
 2761:         foreach my $item (@usertools) {
 2762:             $datatable .= '<td style="vertical-align: top">'.$advcell{$item}.'</td>';
 2763:         }
 2764:         $datatable .= '</tr></table>';
 2765:     }
 2766:     $datatable .= '</td></tr>';
 2767:     $$rowtotal += $typecount;
 2768:     return $datatable;
 2769: }
 2770: 
 2771: sub print_requestmail {
 2772:     my ($dom,$action,$settings,$rowtotal,$customcss,$rowstyle) = @_;
 2773:     my ($now,$datatable,%currapp);
 2774:     $now = time;
 2775:     if (ref($settings) eq 'HASH') {
 2776:         if (ref($settings->{'notify'}) eq 'HASH') {
 2777:             if ($settings->{'notify'}{'approval'} ne '') {
 2778:                 map {$currapp{$_}=1;} split(/,/,$settings->{'notify'}{'approval'});
 2779:             }
 2780:         }
 2781:     }
 2782:     my $numinrow = 2;
 2783:     my $css_class;
 2784:     if ($$rowtotal%2) {
 2785:         $css_class = 'LC_odd_row';
 2786:     }
 2787:     if ($customcss) {
 2788:         $css_class .= " $customcss";
 2789:     }
 2790:     $css_class =~ s/^\s+//;
 2791:     if ($css_class) {
 2792:         $css_class = ' class="'.$css_class.'"';
 2793:     }
 2794:     if ($rowstyle) {
 2795:         $css_class .= ' style="'.$rowstyle.'"';
 2796:     }
 2797:     my $text;
 2798:     if ($action eq 'requestcourses') {
 2799:         $text = &mt('Receive notification of course requests requiring approval');
 2800:     } elsif ($action eq 'requestauthor') {
 2801:         $text = &mt('Receive notification of Authoring Space requests requiring approval');
 2802:     } else {
 2803:        $text = &mt('Receive notification of queued requests for self-created user accounts requiring approval');
 2804:     }
 2805:     $datatable = '<tr'.$css_class.'>'.
 2806:                  ' <td>'.$text.'</td>'.
 2807:                  ' <td class="LC_left_item">';
 2808:     my ($numdc,$table,$rows) = &active_dc_picker($dom,$numinrow,'checkbox',
 2809:                                                  $action.'notifyapproval',%currapp);
 2810:     if ($numdc > 0) {
 2811:         $datatable .= $table;
 2812:     } else {
 2813:         $datatable .= &mt('There are no active Domain Coordinators');
 2814:     }
 2815:     $datatable .='</td></tr>';
 2816:     return $datatable;
 2817: }
 2818: 
 2819: sub print_studentcode {
 2820:     my ($settings,$rowtotal) = @_;
 2821:     my $rownum = 0; 
 2822:     my ($output,%current);
 2823:     my @crstypes = ('official','unofficial','community','textbook','placement','lti');
 2824:     if (ref($settings) eq 'HASH') {
 2825:         if (ref($settings->{'uniquecode'}) eq 'HASH') {
 2826:             foreach my $type (@crstypes) {
 2827:                 $current{$type} = $settings->{'uniquecode'}{$type};
 2828:             }
 2829:         }
 2830:     }
 2831:     $output .= '<tr>'.
 2832:                '<td class="LC_left_item">'.&mt('Generate unique six character code as course identifier?').'</td>'.
 2833:                '<td class="LC_left_item">';
 2834:     foreach my $type (@crstypes) {
 2835:         my $check = ' ';
 2836:         if ($current{$type}) {
 2837:             $check = ' checked="checked" ';
 2838:         }
 2839:         $output .= '<span class="LC_nobreak"><label>'.
 2840:                    '<input type="checkbox" name="uniquecode" value="'.$type.'"'.$check.'/>'.
 2841:                    &mt($type).'</label></span>'.('&nbsp;'x2).' ';
 2842:     }
 2843:     $output .= '</td></tr>';
 2844:     $$rowtotal ++;
 2845:     return $output;
 2846: }
 2847: 
 2848: sub print_textbookcourses {
 2849:     my ($dom,$type,$settings,$rowtotal) = @_;
 2850:     my $rownum = 0;
 2851:     my $css_class;
 2852:     my $itemcount = 1;
 2853:     my $maxnum = 0;
 2854:     my $bookshash;
 2855:     if (ref($settings) eq 'HASH') {
 2856:         $bookshash = $settings->{$type};
 2857:     }
 2858:     my %ordered;
 2859:     if (ref($bookshash) eq 'HASH') {
 2860:         foreach my $item (keys(%{$bookshash})) {
 2861:             if (ref($bookshash->{$item}) eq 'HASH') {
 2862:                 my $num = $bookshash->{$item}{'order'};
 2863:                 $ordered{$num} = $item;
 2864:             }
 2865:         }
 2866:     }
 2867:     my $confname = $dom.'-domainconfig';
 2868:     my $switchserver = &check_switchserver($dom,$confname);
 2869:     my $maxnum = scalar(keys(%ordered));
 2870:     my $datatable;
 2871:     if (keys(%ordered)) {
 2872:         my @items = sort { $a <=> $b } keys(%ordered);
 2873:         for (my $i=0; $i<@items; $i++) {
 2874:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2875:             my $key = $ordered{$items[$i]};
 2876:             my %coursehash=&Apache::lonnet::coursedescription($key);
 2877:             my $coursetitle = $coursehash{'description'};
 2878:             my ($subject,$title,$author,$publisher,$image,$imgsrc,$cdom,$cnum);
 2879:             if (ref($bookshash->{$key}) eq 'HASH') {
 2880:                 $subject = $bookshash->{$key}->{'subject'};
 2881:                 $title = $bookshash->{$key}->{'title'};
 2882:                 if ($type eq 'textbooks') {
 2883:                     $publisher = $bookshash->{$key}->{'publisher'};
 2884:                     $author = $bookshash->{$key}->{'author'};
 2885:                     $image = $bookshash->{$key}->{'image'};
 2886:                     if ($image ne '') {
 2887:                         my ($path,$imagefile) = ($image =~ m{^(.+)/([^/]+)$});
 2888:                         my $imagethumb = "$path/tn-".$imagefile;
 2889:                         $imgsrc = '<img src="'.$imagethumb.'" alt="'.&mt('Textbook image').'" />';
 2890:                     }
 2891:                 }
 2892:             }
 2893:             my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type".'_'."$key','$type'".');"';
 2894:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 2895:                          .'<select name="'.$type.'_'.$key.'"'.$chgstr.'>';
 2896:             for (my $k=0; $k<=$maxnum; $k++) {
 2897:                 my $vpos = $k+1;
 2898:                 my $selstr;
 2899:                 if ($k == $i) {
 2900:                     $selstr = ' selected="selected" ';
 2901:                 }
 2902:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2903:             }
 2904:             $datatable .= '</select>'.('&nbsp;'x2).
 2905:                 '<label><input type="checkbox" name="'.$type.'_del" value="'.$key.'" />'.
 2906:                 &mt('Delete?').'</label></span></td>'.
 2907:                 '<td colspan="2">'.
 2908:                 '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_subject_'.$i.'" value="'.$subject.'" /></span> '.
 2909:                 ('&nbsp;'x2).
 2910:                 '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_title_'.$i.'" value="'.$title.'" /></span> ';
 2911:             if ($type eq 'textbooks') {
 2912:                 $datatable .= ('&nbsp;'x2).
 2913:                               '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_publisher_'.$i.'" value="'.$publisher.'" /></span> '.
 2914:                               ('&nbsp;'x2).
 2915:                               '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_author_'.$i.'" value="'.$author.'" /></span> '.
 2916:                               ('&nbsp;'x2).
 2917:                               '<span class="LC_nobreak">'.&mt('Thumbnail:');
 2918:                 if ($image) {
 2919:                     $datatable .= $imgsrc.
 2920:                                   '<label><input type="checkbox" name="'.$type.'_image_del"'.
 2921:                                   ' value="'.$key.'" />'.&mt('Delete?').'</label></span> '.
 2922:                                   '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 2923:                 }
 2924:                 if ($switchserver) {
 2925:                     $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2926:                 } else {
 2927:                     $datatable .= '<input type="file" name="'.$type.'_image_'.$i.'" value="" />';
 2928:                 }
 2929:             }
 2930:             $datatable .= '<input type="hidden" name="'.$type.'_id_'.$i.'" value="'.$type.'_'.$key.'" /></span> '.
 2931:                           '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2932:                           $coursetitle.'</span></td></tr>'."\n";
 2933:             $itemcount ++;
 2934:         }
 2935:     }
 2936:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 2937:     my $chgstr = ' onchange="javascript:reorderBooks(this.form,'."'$type"."_addbook_pos','$type'".');"';
 2938:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 2939:                   '<input type="hidden" name="'.$type.'_maxnum" value="'.$maxnum.'" />'."\n".
 2940:                   '<select name="'.$type.'_addbook_pos"'.$chgstr.'>';
 2941:     for (my $k=0; $k<$maxnum+1; $k++) {
 2942:         my $vpos = $k+1;
 2943:         my $selstr;
 2944:         if ($k == $maxnum) {
 2945:             $selstr = ' selected="selected" ';
 2946:         }
 2947:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 2948:     }
 2949:     $datatable .= '</select>&nbsp;'."\n".
 2950:                   '<input type="checkbox" name="'.$type.'_addbook" value="1" />'.&mt('Add').'</span></td>'."\n".
 2951:                   '<td colspan="2">'.
 2952:                   '<span class="LC_nobreak">'.&mt('Subject:').'<input type="text" size="15" name="'.$type.'_addbook_subject" value="" /></span> '."\n".
 2953:                   ('&nbsp;'x2).
 2954:                   '<span class="LC_nobreak">'.&mt('Title:').'<input type="text" size="30" name="'.$type.'_addbook_title" value="" /></span> '."\n".
 2955:                   ('&nbsp;'x2);
 2956:     if ($type eq 'textbooks') {
 2957:         $datatable .= '<span class="LC_nobreak">'.&mt('Publisher:').'<input type="text" size="10" name="'.$type.'_addbook_publisher" value="" /></span> '."\n".
 2958:                       ('&nbsp;'x2).
 2959:                       '<span class="LC_nobreak">'.&mt('Author(s):').'<input type="text" size="25" name="'.$type.'_addbook_author" value="" /></span> '."\n".
 2960:                       ('&nbsp;'x2).
 2961:                       '<span class="LC_nobreak">'.&mt('Image:').'&nbsp;';
 2962:         if ($switchserver) {
 2963:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 2964:         } else {
 2965:             $datatable .= '<input type="file" name="'.$type.'_addbook_image" value="" />';
 2966:         }
 2967:         $datatable .= '</span>'."\n";
 2968:     }
 2969:     $datatable .= '<span class="LC_nobreak">'.&mt('LON-CAPA course:').'&nbsp;'.
 2970:                   &Apache::loncommon::select_dom_form($env{'request.role.domain'},$type.'_addbook_cdom').
 2971:                   '<input type="text" size="25" name="'.$type.'_addbook_cnum" value="" />'.
 2972:                   &Apache::loncommon::selectcourse_link
 2973:                       ('display',$type.'_addbook_cnum',$type.'_addbook_cdom',undef,undef,undef,'Course').
 2974:                   '</span></td>'."\n".
 2975:                   '</tr>'."\n";
 2976:     $itemcount ++;
 2977:     return $datatable;
 2978: }
 2979: 
 2980: sub textbookcourses_javascript {
 2981:     my ($settings) = @_;
 2982:     return unless(ref($settings) eq 'HASH');
 2983:     my (%ordered,%total,%jstext);
 2984:     foreach my $type ('textbooks','templates') {
 2985:         $total{$type} = 0;
 2986:         if (ref($settings->{$type}) eq 'HASH') {
 2987:             foreach my $item (keys(%{$settings->{$type}})) {
 2988:                 if (ref($settings->{$type}->{$item}) eq 'HASH') {
 2989:                     my $num = $settings->{$type}->{$item}{'order'};
 2990:                     $ordered{$type}{$num} = $item;
 2991:                 }
 2992:             }
 2993:             $total{$type} = scalar(keys(%{$settings->{$type}}));
 2994:         }
 2995:         my @jsarray = ();
 2996:         foreach my $item (sort {$a <=> $b } (keys(%{$ordered{$type}}))) {
 2997:             push(@jsarray,$ordered{$type}{$item});
 2998:         }
 2999:         $jstext{$type} = '    var '.$type.' = Array('."'".join("','",@jsarray)."'".');'."\n";
 3000:     }
 3001:     return <<"ENDSCRIPT";
 3002: <script type="text/javascript">
 3003: // <![CDATA[
 3004: function reorderBooks(form,item,caller) {
 3005:     var changedVal;
 3006: $jstext{'textbooks'};
 3007: $jstext{'templates'};
 3008:     var newpos;
 3009:     var maxh;
 3010:     if (caller == 'textbooks') {  
 3011:         newpos = 'textbooks_addbook_pos';
 3012:         maxh = 1 + $total{'textbooks'};
 3013:     } else {
 3014:         newpos = 'templates_addbook_pos';
 3015:         maxh = 1 + $total{'templates'};
 3016:     }
 3017:     var current = new Array;
 3018:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3019:     if (item == newpos) {
 3020:         changedVal = newitemVal;
 3021:     } else {
 3022:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3023:         current[newitemVal] = newpos;
 3024:     }
 3025:     if (caller == 'textbooks') {
 3026:         for (var i=0; i<textbooks.length; i++) {
 3027:             var elementName = 'textbooks_'+textbooks[i];
 3028:             if (elementName != item) {
 3029:                 if (form.elements[elementName]) {
 3030:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3031:                     current[currVal] = elementName;
 3032:                 }
 3033:             }
 3034:         }
 3035:     }
 3036:     if (caller == 'templates') {
 3037:         for (var i=0; i<templates.length; i++) {
 3038:             var elementName = 'templates_'+templates[i];
 3039:             if (elementName != item) {
 3040:                 if (form.elements[elementName]) {
 3041:                     var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3042:                     current[currVal] = elementName;
 3043:                 }
 3044:             }
 3045:         }
 3046:     }
 3047:     var oldVal;
 3048:     for (var j=0; j<maxh; j++) {
 3049:         if (current[j] == undefined) {
 3050:             oldVal = j;
 3051:         }
 3052:     }
 3053:     if (oldVal < changedVal) {
 3054:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3055:            var elementName = current[k];
 3056:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3057:         }
 3058:     } else {
 3059:         for (var k=changedVal; k<oldVal; k++) {
 3060:             var elementName = current[k];
 3061:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3062:         }
 3063:     }
 3064:     return;
 3065: }
 3066: 
 3067: // ]]>
 3068: </script>
 3069: 
 3070: ENDSCRIPT
 3071: }
 3072: 
 3073: sub ltitools_javascript {
 3074:     my ($settings) = @_;
 3075:     my $togglejs = &ltitools_toggle_js();
 3076:     unless (ref($settings) eq 'HASH') {
 3077:         return $togglejs;
 3078:     }
 3079:     my (%ordered,$total,%jstext);
 3080:     $total = 0;
 3081:     foreach my $item (keys(%{$settings})) {
 3082:         if (ref($settings->{$item}) eq 'HASH') {
 3083:             my $num = $settings->{$item}{'order'};
 3084:             $ordered{$num} = $item;
 3085:         }
 3086:     }
 3087:     $total = scalar(keys(%{$settings}));
 3088:     my @jsarray = ();
 3089:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3090:         push(@jsarray,$ordered{$item});
 3091:     }
 3092:     my $jstext = '    var ltitools = Array('."'".join("','",@jsarray)."'".');'."\n";
 3093:     return <<"ENDSCRIPT";
 3094: <script type="text/javascript">
 3095: // <![CDATA[
 3096: function reorderLTITools(form,item) {
 3097:     var changedVal;
 3098: $jstext
 3099:     var newpos = 'ltitools_add_pos';
 3100:     var maxh = 1 + $total;
 3101:     var current = new Array;
 3102:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3103:     if (item == newpos) {
 3104:         changedVal = newitemVal;
 3105:     } else {
 3106:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3107:         current[newitemVal] = newpos;
 3108:     }
 3109:     for (var i=0; i<ltitools.length; i++) {
 3110:         var elementName = 'ltitools_'+ltitools[i];
 3111:         if (elementName != item) {
 3112:             if (form.elements[elementName]) {
 3113:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3114:                 current[currVal] = elementName;
 3115:             }
 3116:         }
 3117:     }
 3118:     var oldVal;
 3119:     for (var j=0; j<maxh; j++) {
 3120:         if (current[j] == undefined) {
 3121:             oldVal = j;
 3122:         }
 3123:     }
 3124:     if (oldVal < changedVal) {
 3125:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3126:            var elementName = current[k];
 3127:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3128:         }
 3129:     } else {
 3130:         for (var k=changedVal; k<oldVal; k++) {
 3131:             var elementName = current[k];
 3132:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3133:         }
 3134:     }
 3135:     return;
 3136: }
 3137: 
 3138: // ]]>
 3139: </script>
 3140: 
 3141: $togglejs
 3142: 
 3143: ENDSCRIPT
 3144: }
 3145: 
 3146: sub ltitools_toggle_js {
 3147:     return <<"ENDSCRIPT";
 3148: <script type="text/javascript">
 3149: // <![CDATA[
 3150: 
 3151: function toggleLTITools(form,setting,item) {
 3152:     var radioname = '';
 3153:     var divid = '';
 3154:     if ((setting == 'passback') || (setting == 'roster')) {
 3155:         radioname = 'ltitools_'+setting+'_'+item;
 3156:         divid = 'ltitools_'+setting+'time_'+item;
 3157:         var num = form.elements[radioname].length;
 3158:         if (num) {
 3159:             var setvis = '';
 3160:             for (var i=0; i<num; i++) {
 3161:                 if (form.elements[radioname][i].checked) {
 3162:                     if (form.elements[radioname][i].value == '1') {
 3163:                         if (document.getElementById(divid)) {
 3164:                             document.getElementById(divid).style.display = 'inline-block';
 3165:                         }
 3166:                         setvis = 1;
 3167:                     }
 3168:                     break;
 3169:                 }
 3170:             }
 3171:         }
 3172:         if (!setvis) {
 3173:             if (document.getElementById(divid)) {
 3174:                 document.getElementById(divid).style.display = 'none';
 3175:             }
 3176:         }
 3177:     }
 3178:     if (setting == 'user') {
 3179:         divid = 'ltitools_'+setting+'_div_'+item;
 3180:         var checkid = 'ltitools_'+setting+'_field_'+item;
 3181:         if (document.getElementById(divid)) {
 3182:             if (document.getElementById(checkid)) {
 3183:                 if (document.getElementById(checkid).checked) {
 3184:                     document.getElementById(divid).style.display = 'inline-block';
 3185:                 } else {
 3186:                     document.getElementById(divid).style.display = 'none';
 3187:                 }
 3188:             }
 3189:         }
 3190:     }
 3191:     return;
 3192: }
 3193: // ]]>
 3194: </script>
 3195: 
 3196: ENDSCRIPT
 3197: }
 3198: 
 3199: sub wafproxy_javascript {
 3200:     my ($dom) = @_;
 3201:     return <<"ENDSCRIPT";
 3202: <script type="text/javascript">
 3203: // <![CDATA[
 3204: function updateWAF() {
 3205:     if (document.getElementById('wafproxy_remoteip')) {
 3206:         var wafremote = 0;
 3207:         if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value == 'h') {
 3208:             wafremote = 1;
 3209:         }
 3210:         var fields = new Array('header','trust');
 3211:         for (var i=0; i<fields.length; i++) {
 3212:             if (document.getElementById('wafproxy_'+fields[i])) {
 3213:                 if (wafremote == 1) {
 3214:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'table-row';
 3215:                 }
 3216:                 else {
 3217:                     document.getElementById('wafproxy_'+fields[i]).style.display = 'none';
 3218:                 }
 3219:             }
 3220:         }
 3221:         if (document.getElementById('wafproxyranges_$dom')) {
 3222:             if (wafremote == 1) {
 3223:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3224:             } else {
 3225:                 for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3226:                     if (document.display.wafproxy_vpnaccess[i].checked) {
 3227:                         if (document.display.wafproxy_vpnaccess[i].value == 0) {
 3228:                             document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3229:                         }
 3230:                     }
 3231:                 }
 3232:             }
 3233:         }
 3234:     }
 3235:     return;
 3236: }
 3237: 
 3238: function checkWAF() {
 3239:     if (document.getElementById('wafproxy_remoteip')) {
 3240:         var wafvpn = 0;
 3241:         for (var i=0; i<document.display.wafproxy_vpnaccess.length; i++) {
 3242:             if (document.display.wafproxy_vpnaccess[i].checked) {
 3243:                 if (document.display.wafproxy_vpnaccess[i].value == 1) {
 3244:                     wafvpn = 1;
 3245:                 }
 3246:                 break;
 3247:             }
 3248:         }
 3249:         var vpn = new Array('vpnint','vpnext');
 3250:         for (var i=0; i<vpn.length; i++) {
 3251:             if (document.getElementById('wafproxy_show_'+vpn[i])) {
 3252:                 if (wafvpn == 1) {
 3253:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'table-row';
 3254:                 }
 3255:                 else {
 3256:                     document.getElementById('wafproxy_show_'+vpn[i]).style.display = 'none';
 3257:                 }
 3258:             }
 3259:         }
 3260:         if (document.getElementById('wafproxyranges_$dom')) {
 3261:             if (wafvpn == 1) {
 3262:                 document.getElementById('wafproxyranges_$dom').style.display = 'inline-block';
 3263:             }
 3264:             else if (document.display.wafproxy_remoteip.options[document.display.wafproxy_remoteip.selectedIndex].value != 'h') {
 3265:                 document.getElementById('wafproxyranges_$dom').style.display = 'none';
 3266:             }
 3267:         }
 3268:     }
 3269:     return;
 3270: }
 3271: 
 3272: function toggleWAF() {
 3273:     if (document.getElementById('wafproxy_table')) {
 3274:         var wafproxy = 0;
 3275:         for (var i=0; i<document.display.wafproxy_${dom}.length; i++) {
 3276:              if (document.display.wafproxy_${dom}[i].checked) {
 3277:                  if (document.display.wafproxy_${dom}[i].value == 1) {
 3278:                      wafproxy = 1;
 3279:                      break;
 3280:                 }
 3281:             }
 3282:         }
 3283:         if (wafproxy == 1) {
 3284:             document.getElementById('wafproxy_table').style.display='inline';
 3285:         }
 3286:         else {
 3287:            document.getElementById('wafproxy_table').style.display='none';
 3288:         }
 3289:         if (document.getElementById('wafproxyrow_${dom}')) {
 3290:             if (wafproxy == 1) {
 3291:                 document.getElementById('wafproxyrow_${dom}').style.display = 'table-row';
 3292:             }
 3293:             else {
 3294:                 document.getElementById('wafproxyrow_${dom}').style.display = 'none';
 3295:             }
 3296:         }
 3297:         if (document.getElementById('nowafproxyrow_$dom')) {
 3298:             if (wafproxy == 1) {
 3299:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'none';
 3300:             }
 3301:             else {
 3302:                 document.getElementById('nowafproxyrow_${dom}').style.display = 'table-row';
 3303:             }
 3304:         }
 3305:     }
 3306:     return;
 3307: }
 3308: // ]]>
 3309: </script>
 3310: 
 3311: ENDSCRIPT
 3312: }
 3313: 
 3314: sub proctoring_javascript {
 3315:     my ($settings) = @_;
 3316:     my (%ordered,$total,%jstext);
 3317:     $total = 0;
 3318:     if (ref($settings) eq 'HASH') {
 3319:         foreach my $item (keys(%{$settings})) {
 3320:             if (ref($settings->{$item}) eq 'HASH') {
 3321:                 my $num = $settings->{$item}{'order'};
 3322:                 $ordered{$num} = $item;
 3323:             }
 3324:         }
 3325:         $total = scalar(keys(%{$settings}));
 3326:     } else {
 3327:         %ordered = (
 3328:                        0 => 'proctorio',
 3329:                        1 => 'examity',
 3330:                    );
 3331:         $total = 2; 
 3332:     }
 3333:     my @jsarray = ();
 3334:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3335:         push(@jsarray,$ordered{$item});
 3336:     }
 3337:     my $jstext = '    var proctors = Array('."'".join("','",@jsarray)."'".');'."\n";
 3338:     return <<"ENDSCRIPT";
 3339: <script type="text/javascript">
 3340: // <![CDATA[
 3341: function reorderProctoring(form,item) {
 3342:     var changedVal;
 3343: $jstext
 3344:     var maxh = $total;
 3345:     var current = new Array;
 3346:     var changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3347:     for (var i=0; i<proctors.length; i++) {
 3348:         var elementName = 'proctoring_pos_'+proctors[i];
 3349:         if (elementName != item) {
 3350:             if (form.elements[elementName]) {
 3351:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3352:                 current[currVal] = elementName;
 3353:             }
 3354:         }
 3355:     }
 3356:     var oldVal;
 3357:     for (var j=0; j<maxh; j++) {
 3358:         if (current[j] == undefined) {
 3359:             oldVal = j;
 3360:         }
 3361:     }
 3362:     if (oldVal < changedVal) {
 3363:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3364:            var elementName = current[k];
 3365:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3366:         }
 3367:     } else {
 3368:         for (var k=changedVal; k<oldVal; k++) {
 3369:             var elementName = current[k];
 3370:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3371:         }
 3372:     }
 3373:     return;
 3374: }
 3375: 
 3376: function toggleProctoring(form,item) {
 3377:     var fieldsets = document.getElementsByClassName('proctoring_'+item);
 3378:     if (fieldsets.length) {
 3379:         var radioname = 'proctoring_available_'+item;
 3380:         var num = form.elements[radioname].length;
 3381:         if (num) {
 3382:             var setvis = '';
 3383:             for (var i=0; i<num; i++) {
 3384:                 if (form.elements[radioname][i].checked) {
 3385:                     if (form.elements[radioname][i].value == '1') {
 3386:                        setvis = 1;
 3387:                        break;
 3388:                     }
 3389:                 }
 3390:             }
 3391:             for (var j=0; j<fieldsets.length; j++) {
 3392:                 if (setvis) {
 3393:                     fieldsets[j].style.display = 'block';
 3394:                 } else {
 3395:                     fieldsets[j].style.display = 'none';
 3396:                 }
 3397:             }
 3398:         }
 3399:     }
 3400:     return;
 3401: }
 3402: 
 3403: // ]]>
 3404: </script>
 3405: 
 3406: ENDSCRIPT
 3407: }
 3408: 
 3409: 
 3410: sub lti_javascript {
 3411:     my ($dom,$settings) = @_;
 3412:     my $togglejs = &lti_toggle_js($dom);
 3413:     unless (ref($settings) eq 'HASH') {
 3414:         return $togglejs;
 3415:     }
 3416:     my (%ordered,$total,%jstext);
 3417:     $total = scalar(keys(%{$settings}));
 3418:     foreach my $item (keys(%{$settings})) {
 3419:         if (ref($settings->{$item}) eq 'HASH') {
 3420:             my $num = $settings->{$item}{'order'};
 3421:             if ($num eq '') {
 3422:                 $num = $total - 1;
 3423:             }
 3424:             $ordered{$num} = $item;
 3425:         }
 3426:     }
 3427:     my @jsarray = ();
 3428:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3429:         push(@jsarray,$ordered{$item});
 3430:     }
 3431:     my $jstext = '    var lti = Array('."'".join("','",@jsarray)."'".');'."\n";
 3432:     return <<"ENDSCRIPT";
 3433: <script type="text/javascript">
 3434: // <![CDATA[
 3435: function reorderLTI(form,item) {
 3436:     var changedVal;
 3437: $jstext
 3438:     var newpos = 'lti_pos_add';
 3439:     var maxh = 1 + $total;
 3440:     var current = new Array;
 3441:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3442:     if (item == newpos) {
 3443:         changedVal = newitemVal;
 3444:     } else {
 3445:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3446:         current[newitemVal] = newpos;
 3447:     }
 3448:     for (var i=0; i<lti.length; i++) {
 3449:         var elementName = 'lti_pos_'+lti[i];
 3450:         if (elementName != item) {
 3451:             if (form.elements[elementName]) {
 3452:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3453:                 current[currVal] = elementName;
 3454:             }
 3455:         }
 3456:     }
 3457:     var oldVal;
 3458:     for (var j=0; j<maxh; j++) {
 3459:         if (current[j] == undefined) {
 3460:             oldVal = j;
 3461:         }
 3462:     }
 3463:     if (oldVal < changedVal) {
 3464:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3465:            var elementName = current[k];
 3466:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3467:         }
 3468:     } else {
 3469:         for (var k=changedVal; k<oldVal; k++) {
 3470:             var elementName = current[k];
 3471:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3472:         }
 3473:     }
 3474:     return;
 3475: }
 3476: // ]]>
 3477: </script>
 3478: 
 3479: $togglejs
 3480: 
 3481: ENDSCRIPT
 3482: }
 3483: 
 3484: sub lti_toggle_js {
 3485:     my ($dom) = @_;
 3486:     my %lcauthparmtext = &Apache::lonlocal::texthash (
 3487:                             localauth => 'Local auth argument',
 3488:                             krb       => 'Kerberos domain',
 3489:                          );
 3490:     my $crsincalert = &mt('"User\'s identity sent" needs to be set to "Yes" first,[_1] before setting "Course\'s identity sent" to "Yes"',"\n");
 3491:     &js_escape(\$crsincalert);
 3492:     my %servers = &Apache::lonnet::get_servers($dom,'library');
 3493:     my $primary = &Apache::lonnet::domain($dom,'primary');
 3494:     my $course_servers = "'".join("','",keys(%servers))."'";
 3495: 
 3496:     return <<"ENDSCRIPT";
 3497: <script type="text/javascript">
 3498: // <![CDATA[
 3499: 
 3500: function toggleLTI(form,setting,item) {
 3501:     if ((setting == 'requser') || (setting == 'crsinc')) {
 3502:         var usrfieldsets = document.getElementsByClassName('ltioption_usr_'+item);
 3503:         var setvis = '';
 3504:         var radioname = 'lti_requser_'+item;
 3505:         var num = form.elements[radioname].length;
 3506:         if (num) {
 3507:             for (var i=0; i<num; i++) {
 3508:                 if (form.elements[radioname][i].checked) {
 3509:                     if (form.elements[radioname][i].value == '1') {
 3510:                         setvis = 1;
 3511:                         break;
 3512:                     }
 3513:                 }
 3514:             }
 3515:         }
 3516:         if (usrfieldsets.length) {
 3517:             for (var j=0; j<usrfieldsets.length; j++) {
 3518:                 if (setvis) {
 3519:                     usrfieldsets[j].style.display = 'block';
 3520:                 } else {
 3521:                     usrfieldsets[j].style.display = 'none';
 3522:                 }
 3523:             }
 3524:         }
 3525:         var crsfieldsets = document.getElementsByClassName('ltioption_crs_'+item);
 3526:         if (crsfieldsets.length) {
 3527:             radioname = 'lti_crsinc_'+item;
 3528:             var num = form.elements[radioname].length;
 3529:             if (num) {
 3530:                 var crsvis = '';
 3531:                 for (var i=0; i<num; i++) {
 3532:                     if (form.elements[radioname][i].checked) {
 3533:                         if (form.elements[radioname][i].value == '1') {
 3534:                             if (setvis == '') {
 3535:                                 if (setting == 'crsinc'){
 3536:                                     alert("$crsincalert");
 3537:                                     form.elements[radioname][0].checked = true;
 3538:                                 }
 3539:                             } else {
 3540:                                 crsvis = 1;
 3541:                             }
 3542:                             break;
 3543:                         }
 3544:                     }
 3545:                 }
 3546:                 setvis = crsvis;
 3547:             }
 3548:             for (var j=0; j<crsfieldsets.length; j++) {
 3549:                 if (setvis) {
 3550:                     crsfieldsets[j].style.display = 'block';
 3551:                 } else {
 3552:                     crsfieldsets[j].style.display = 'none';
 3553:                 }
 3554:             }
 3555:         }
 3556:     } else if ((setting == 'user') || (setting == 'crs') || (setting == 'passback') || (setting == 'callback')) {
 3557:         var radioname = '';
 3558:         var divid = '';
 3559:         if (setting == 'user') {
 3560:             radioname = 'lti_mapuser_'+item;
 3561:             divid = 'lti_userfield_'+item;
 3562:         } else if (setting == 'crs') {
 3563:             radioname = 'lti_mapcrs_'+item;
 3564:             divid = 'lti_crsfield_'+item;
 3565:         } else if (setting == 'callback') {
 3566:             radioname = 'lti_callback_'+item;
 3567:             divid = 'lti_callbackfield_'+item;
 3568:         } else {
 3569:             radioname = 'lti_passback_'+item;
 3570:             divid =  'lti_passback_'+item;
 3571:         }
 3572:         var num = form.elements[radioname].length;
 3573:         if (num) {
 3574:             var setvis = '';
 3575:             for (var i=0; i<num; i++) {
 3576:                if (form.elements[radioname][i].checked) {
 3577:                    if ((setting == 'passback') || (setting == 'callback')) {
 3578:                        if (form.elements[radioname][i].value == '1') {
 3579:                            if (document.getElementById(divid)) {
 3580:                                document.getElementById(divid).style.display = 'inline-block';
 3581:                            }
 3582:                            setvis = 1;
 3583:                            break;
 3584:                        }
 3585:                    } else {
 3586:                        if (form.elements[radioname][i].value == 'other') {
 3587:                            if (document.getElementById(divid)) {
 3588:                                document.getElementById(divid).style.display = 'inline-block';
 3589:                            }
 3590:                            setvis = 1;
 3591:                            break;
 3592:                        }
 3593:                    }
 3594:                } 
 3595:             }
 3596:             if (!setvis) {
 3597:                 if (document.getElementById(divid)) {
 3598:                     document.getElementById(divid).style.display = 'none';
 3599:                 }
 3600:             }
 3601:         }
 3602:     } else if ((setting == 'sec') || (setting == 'secsrc')) {
 3603:         var numsec = form.elements['lti_crssec_'+item].length;
 3604:         if (numsec) {
 3605:             var setvis = '';
 3606:             for (var i=0; i<numsec; i++) {
 3607:                 if (form.elements['lti_crssec_'+item][i].checked) {
 3608:                     if (form.elements['lti_crssec_'+item][i].value == '1') {
 3609:                         if (document.getElementById('lti_crssecfield_'+item)) {
 3610:                             document.getElementById('lti_crssecfield_'+item).style.display = 'inline-block';
 3611:                             setvis = 1;
 3612:                             var numsrcsec = form.elements['lti_crssecsrc_'+item].length;
 3613:                             if (numsrcsec) {
 3614:                                 var setsrcvis = '';
 3615:                                 for (var j=0; j<numsrcsec; j++) {
 3616:                                     if (form.elements['lti_crssecsrc_'+item][j].checked) {
 3617:                                         if (form.elements['lti_crssecsrc_'+item][j].value == 'other') {
 3618:                                             if (document.getElementById('lti_secsrcfield_'+item)) {
 3619:                                                 document.getElementById('lti_secsrcfield_'+item).style.display = 'inline-block';
 3620:                                                 setsrcvis = 1;
 3621:                                             }
 3622:                                         }
 3623:                                     }
 3624:                                 }
 3625:                                 if (!setsrcvis) {
 3626:                                     if (document.getElementById('lti_secsrcfield_'+item)) {
 3627:                                         document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3628:                                     }
 3629:                                 }
 3630:                             }
 3631:                         }
 3632:                     }
 3633:                 }
 3634:             }
 3635:             if (!setvis) {
 3636:                 if (document.getElementById('lti_crssecfield_'+item)) {
 3637:                     document.getElementById('lti_crssecfield_'+item).style.display = 'none';
 3638:                 }
 3639:                 if (document.getElementById('lti_secsrcfield_'+item)) {
 3640:                     document.getElementById('lti_secsrcfield_'+item).style.display = 'none';
 3641:                 }
 3642:             }
 3643:         }
 3644:     } else if (setting == 'lcauth') {
 3645:         var numauth = form.elements['lti_lcauth_'+item].length;
 3646:         if (numauth) {
 3647:             for (var i=0; i<numauth; i++) {
 3648:                 if (form.elements['lti_lcauth_'+item][i].checked) {
 3649:                     if (document.getElementById('lti_'+setting+'_parmrow_'+item)) {
 3650:                         if ((form.elements['lti_'+setting+'_'+item][i].value == 'internal') || (form.elements['lti_'+setting+'_'+item][i].value == 'lti')) {
 3651:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'none';
 3652:                         } else {
 3653:                             document.getElementById('lti_'+setting+'_parmrow_'+item).style.display = 'table-row';
 3654:                             if (document.getElementById('lti_'+setting+'_parmtext_'+item)) {
 3655:                                 if (form.elements['lti_'+setting+'_'+item][i].value == 'localauth') {
 3656:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'localauth'}";
 3657:                                 } else {
 3658:                                     document.getElementById('lti_'+setting+'_parmtext_'+item).innerHTML = "$lcauthparmtext{'krb'}";
 3659:                                 }
 3660:                             }
 3661:                         }
 3662:                     }
 3663:                 }
 3664:             }
 3665:         }
 3666:     } else if (setting == 'lcmenu') {
 3667:         var menus = new Array('lti_topmenu_'+item,'lti_inlinemenu_'+item);
 3668:         var divid = 'lti_menufield_'+item;
 3669:         var setvis = '';
 3670:         for (var i=0; i<menus.length; i++) {
 3671:             var radioname = menus[i];  
 3672:             var num = form.elements[radioname].length;
 3673:             if (num) {
 3674:                 for (var j=0; j<num; j++) {
 3675:                     if (form.elements[radioname][j].checked) {
 3676:                         if (form.elements[radioname][j].value == '1') {
 3677:                             if (document.getElementById(divid)) {
 3678:                                 document.getElementById(divid).style.display = 'inline-block';
 3679:                             }
 3680:                             setvis = 1;
 3681:                             break;
 3682:                         }
 3683:                     }
 3684:                 }
 3685:             }
 3686:             if (setvis == 1) {
 3687:                 break;
 3688:             }
 3689:         }
 3690:         if (!setvis) {
 3691:             if (document.getElementById(divid)) {
 3692:                 document.getElementById(divid).style.display = 'none';
 3693:             }
 3694:         }
 3695:     }
 3696:     return;
 3697: }
 3698: 
 3699: function toggleLTIEncKey(form) {
 3700:     var shownhosts = new Array();
 3701:     var hiddenhosts = new Array();
 3702:     var forcourse = new Array($course_servers);
 3703:     var fromdomain = '$primary';
 3704:     var crsradio = form.elements['ltisec_crslinkprot'];
 3705:     if (crsradio.length) {
 3706:         for (var i=0; i<crsradio.length; i++) {
 3707:             if (crsradio[i].checked) {
 3708:                 if (crsradio[i].value == 1) {
 3709:                     if (forcourse.length > 0) {
 3710:                         for (var j=0; j<forcourse.length; j++) {
 3711:                             if (!shownhosts.includes(forcourse[j])) {
 3712:                                 shownhosts.push(forcourse[j]);
 3713:                             }
 3714:                         }
 3715:                     }
 3716:                 } else {
 3717:                     if (forcourse.length > 0) {
 3718:                         for (var j=0; j<forcourse.length; j++) {
 3719:                             if (!hiddenhosts.includes(forcourse[j])) { 
 3720:                                 hiddenhosts.push(forcourse[j]);
 3721:                             }
 3722:                         }
 3723:                     } 
 3724:                 }
 3725:             }
 3726:         }
 3727:     }
 3728:     var domradio = form.elements['ltisec_domlinkprot'];
 3729:     if (domradio.length) {
 3730:         for (var i=0; i<domradio.length; i++) {
 3731:             if (domradio[i].checked) {
 3732:                 if (domradio[i].value == 1) {
 3733:                     if (!shownhosts.includes(fromdomain)) { 
 3734:                         shownhosts.push(fromdomain);
 3735:                     }
 3736:                 } else {
 3737:                     if (!hiddenhosts.includes(fromdomain)) {
 3738:                         hiddenhosts.push(fromdomain);
 3739:                     }
 3740:                 }
 3741:             }
 3742:         }
 3743:     }
 3744:     var consumersradio = form.elements['ltisec_consumers'];
 3745:     if (consumersradio.length) {
 3746:         for (var i=0; i<consumersradio.length; i++) {
 3747:             if (consumersradio[i].checked) {
 3748:                 if (consumersradio[i].value == 1) {
 3749:                     if (!shownhosts.includes(fromdomain)) {     
 3750:                         shownhosts.push(fromdomain);
 3751:                     }
 3752:                 } else {
 3753:                     if (!hiddenhosts.includes(fromdomain)) {
 3754:                         hiddenhosts.push(fromdomain);
 3755:                     }
 3756:                 }
 3757:             }
 3758:         }
 3759:     }
 3760:     if (shownhosts.length > 0) {
 3761:         for (var i=0; i<shownhosts.length; i++) {
 3762:             if (document.getElementById('ltisec_info_'+shownhosts[i])) {
 3763:                 document.getElementById('ltisec_info_'+shownhosts[i]).style.display = 'block';                 
 3764:             }
 3765:         }
 3766:         if (document.getElementById('ltisec_noprivkey')) {
 3767:             document.getElementById('ltisec_noprivkey').style.display = 'none';
 3768:         }
 3769:     } else {
 3770:         if (document.getElementById('ltisec_noprivkey')) {
 3771:             document.getElementById('ltisec_noprivkey').style.display = 'inline-block';
 3772:         }
 3773:     }
 3774:     if (hiddenhosts.length > 0) {
 3775:         for (var i=0; i<hiddenhosts.length; i++) {
 3776:             if (!shownhosts.includes(hiddenhosts[i])) {
 3777:                 if (document.getElementById('ltisec_info_'+hiddenhosts[i])) {
 3778:                     document.getElementById('ltisec_info_'+hiddenhosts[i]).style.display = 'none';
 3779:                 }
 3780:             }
 3781:         }
 3782:     }
 3783:     return;
 3784: }
 3785: 
 3786: function togglePrivKey(form,hostid) {
 3787:     var radioname = '';
 3788:     var currdivid = '';
 3789:     var newdivid = '';
 3790:     if ((document.getElementById('ltisec_divcurrprivkey_'+hostid)) &&
 3791:         (document.getElementById('ltisec_divchgprivkey_'+hostid))) {
 3792:         currdivid = document.getElementById('ltisec_divcurrprivkey_'+hostid);
 3793:         newdivid = document.getElementById('ltisec_divchgprivkey_'+hostid);
 3794:         radioname = form.elements['ltisec_changeprivkey_'+hostid];
 3795:         if (radioname) {
 3796:             if (radioname.length > 0) {
 3797:                 var setvis;
 3798:                 for (var i=0; i<radioname.length; i++) {
 3799:                     if (radioname[i].checked == true) {
 3800:                         if (radioname[i].value == 1) {
 3801:                             newdivid.style.display = 'inline-block';
 3802:                             currdivid.style.display = 'none';
 3803:                             setvis = 1;
 3804:                         }
 3805:                         break;
 3806:                     }
 3807:                 }
 3808:                 if (!setvis) {
 3809:                     newdivid.style.display = 'none';
 3810:                     currdivid.style.display = 'inline-block';
 3811:                 }
 3812:             }
 3813:         }
 3814:     }
 3815: }
 3816: 
 3817: // ]]>
 3818: </script>
 3819: 
 3820: ENDSCRIPT
 3821: }
 3822: 
 3823: sub autoupdate_javascript {
 3824:     return <<"ENDSCRIPT";
 3825: <script type="text/javascript">
 3826: // <![CDATA[
 3827: function toggleLastActiveDays(form) {
 3828:     var radioname = 'lastactive';
 3829:     var divid = 'lastactive_div';
 3830:     var num = form.elements[radioname].length;
 3831:     if (num) {
 3832:         var setvis = '';
 3833:         for (var i=0; i<num; i++) {
 3834:             if (form.elements[radioname][i].checked) {
 3835:                 if (form.elements[radioname][i].value == '1') {
 3836:                     if (document.getElementById(divid)) {
 3837:                         document.getElementById(divid).style.display = 'inline-block';
 3838:                     }
 3839:                     setvis = 1;
 3840:                 }
 3841:                 break;
 3842:             }
 3843:         }
 3844:         if (!setvis) {
 3845:             if (document.getElementById(divid)) {
 3846:                 document.getElementById(divid).style.display = 'none';
 3847:             }
 3848:         }
 3849:     }
 3850:     return;
 3851: }
 3852: // ]]>
 3853: </script>
 3854: 
 3855: ENDSCRIPT
 3856: }
 3857: 
 3858: sub autoenroll_javascript {
 3859:     return <<"ENDSCRIPT";
 3860: <script type="text/javascript">
 3861: // <![CDATA[
 3862: function toggleFailsafe(form) {
 3863:     var radioname = 'autoenroll_failsafe';
 3864:     var divid = 'autoenroll_failsafe_div';
 3865:     var num = form.elements[radioname].length;
 3866:     if (num) {
 3867:         var setvis = '';
 3868:         for (var i=0; i<num; i++) {
 3869:             if (form.elements[radioname][i].checked) {
 3870:                 if ((form.elements[radioname][i].value == 'zero') || (form.elements[radioname][i].value == 'any')) {
 3871:                     if (document.getElementById(divid)) {
 3872:                         document.getElementById(divid).style.display = 'inline-block';
 3873:                     }
 3874:                     setvis = 1;
 3875:                 }
 3876:                 break;
 3877:             }
 3878:         }
 3879:         if (!setvis) {
 3880:             if (document.getElementById(divid)) {
 3881:                 document.getElementById(divid).style.display = 'none';
 3882:             }
 3883:         }
 3884:     }
 3885:     return;
 3886: }
 3887: // ]]>
 3888: </script>
 3889: 
 3890: ENDSCRIPT
 3891: }
 3892: 
 3893: sub saml_javascript {
 3894:     return <<"ENDSCRIPT";
 3895: <script type="text/javascript">
 3896: // <![CDATA[
 3897: function toggleSamlOptions(form,hostid) { 
 3898:     var radioname = 'saml_'+hostid;
 3899:     var tablecellon = 'samloptionson_'+hostid;
 3900:     var tablecelloff = 'samloptionsoff_'+hostid;
 3901:     var num = form.elements[radioname].length;
 3902:     if (num) {
 3903:         var setvis = ''; 
 3904:         for (var i=0; i<num; i++) {
 3905:             if (form.elements[radioname][i].checked) {
 3906:                 if (form.elements[radioname][i].value == '1') { 
 3907:                     if (document.getElementById(tablecellon)) {
 3908:                         document.getElementById(tablecellon).style.display='';
 3909:                     }
 3910:                     if (document.getElementById(tablecelloff)) {
 3911:                         document.getElementById(tablecelloff).style.display='none';
 3912:                     }
 3913:                     setvis = 1;
 3914:                 }
 3915:                 break;
 3916:             }
 3917:         }
 3918:         if (!setvis) {
 3919:             if (document.getElementById(tablecellon)) {
 3920:                 document.getElementById(tablecellon).style.display='none';
 3921:             }
 3922:             if (document.getElementById(tablecelloff)) {
 3923:                 document.getElementById(tablecelloff).style.display='';
 3924:             }
 3925:         }
 3926:     }
 3927:     return;
 3928: }
 3929: // ]]>
 3930: </script>
 3931: 
 3932: ENDSCRIPT
 3933: }
 3934: 
 3935: sub ipaccess_javascript {
 3936:     my ($settings) = @_;
 3937:     my (%ordered,$total,%jstext);
 3938:     $total = 0;
 3939:     if (ref($settings) eq 'HASH') {
 3940:         foreach my $item (keys(%{$settings})) {
 3941:             if (ref($settings->{$item}) eq 'HASH') {
 3942:                 my $num = $settings->{$item}{'order'};
 3943:                 $ordered{$num} = $item;
 3944:             }
 3945:         }
 3946:         $total = scalar(keys(%{$settings}));
 3947:     }
 3948:     my @jsarray = ();
 3949:     foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 3950:         push(@jsarray,$ordered{$item});
 3951:     }
 3952:     my $jstext = '    var ipaccess = Array('."'".join("','",@jsarray)."'".');'."\n";
 3953:     return <<"ENDSCRIPT";
 3954: <script type="text/javascript">
 3955: // <![CDATA[
 3956: function reorderIPaccess(form,item) {
 3957:     var changedVal;
 3958: $jstext
 3959:     var newpos = 'ipaccess_pos_add';
 3960:     var maxh = 1 + $total;
 3961:     var current = new Array;
 3962:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 3963:     if (item == newpos) {
 3964:         changedVal = newitemVal;
 3965:     } else {
 3966:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 3967:         current[newitemVal] = newpos;
 3968:     }
 3969:     for (var i=0; i<ipaccess.length; i++) {
 3970:         var elementName = 'ipaccess_pos_'+ipaccess[i];
 3971:         if (elementName != item) {
 3972:             if (form.elements[elementName]) {
 3973:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 3974:                 current[currVal] = elementName;
 3975:             }
 3976:         }
 3977:     }
 3978:     var oldVal;
 3979:     for (var j=0; j<maxh; j++) {
 3980:         if (current[j] == undefined) {
 3981:             oldVal = j;
 3982:         }
 3983:     }
 3984:     if (oldVal < changedVal) {
 3985:         for (var k=oldVal+1; k<=changedVal ; k++) {
 3986:            var elementName = current[k];
 3987:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 3988:         }
 3989:     } else {
 3990:         for (var k=changedVal; k<oldVal; k++) {
 3991:             var elementName = current[k];
 3992:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 3993:         }
 3994:     }
 3995:     return;
 3996: }
 3997: // ]]>
 3998: </script>
 3999: 
 4000: ENDSCRIPT
 4001: }
 4002: 
 4003: sub print_autoenroll {
 4004:     my ($dom,$settings,$rowtotal) = @_;
 4005:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
 4006:     my ($defdom,$runon,$runoff,$coownerson,$coownersoff,
 4007:         $failsafe,$autofailsafe,$failsafesty,%failsafechecked);
 4008:     $failsafesty = 'none';
 4009:     %failsafechecked = (
 4010:         off => ' checked="checked"',
 4011:     );
 4012:     if (ref($settings) eq 'HASH') {
 4013:         if (exists($settings->{'run'})) {
 4014:             if ($settings->{'run'} eq '0') {
 4015:                 $runoff = ' checked="checked" ';
 4016:                 $runon = ' ';
 4017:             } else {
 4018:                 $runon = ' checked="checked" ';
 4019:                 $runoff = ' ';
 4020:             }
 4021:         } else {
 4022:             if ($autorun) {
 4023:                 $runon = ' checked="checked" ';
 4024:                 $runoff = ' ';
 4025:             } else {
 4026:                 $runoff = ' checked="checked" ';
 4027:                 $runon = ' ';
 4028:             }
 4029:         }
 4030:         if (exists($settings->{'co-owners'})) {
 4031:             if ($settings->{'co-owners'} eq '0') {
 4032:                 $coownersoff = ' checked="checked" ';
 4033:                 $coownerson = ' ';
 4034:             } else {
 4035:                 $coownerson = ' checked="checked" ';
 4036:                 $coownersoff = ' ';
 4037:             }
 4038:         } else {
 4039:             $coownersoff = ' checked="checked" ';
 4040:             $coownerson = ' ';
 4041:         }
 4042:         if (exists($settings->{'sender_domain'})) {
 4043:             $defdom = $settings->{'sender_domain'};
 4044:         }
 4045:         if (exists($settings->{'failsafe'})) {
 4046:             $failsafe = $settings->{'failsafe'};
 4047:             if ($failsafe eq 'zero') {
 4048:                 $failsafechecked{'zero'} = ' checked="checked"';
 4049:                 $failsafechecked{'off'} = '';
 4050:                 $failsafesty = 'inline-block';
 4051:             } elsif ($failsafe eq 'any') {
 4052:                 $failsafechecked{'any'} = ' checked="checked"';
 4053:                 $failsafechecked{'off'} = '';
 4054:             }
 4055:             $autofailsafe = $settings->{'autofailsafe'};
 4056:         } elsif (exists($settings->{'autofailsafe'})) {
 4057:             $autofailsafe = $settings->{'autofailsafe'};
 4058:             if ($autofailsafe ne '') {
 4059:                 $failsafechecked{'zero'} = ' checked="checked"';
 4060:                 $failsafe = 'zero';
 4061:                 $failsafechecked{'off'} = '';
 4062:             }
 4063:         }
 4064:     } else {
 4065:         if ($autorun) {
 4066:             $runon = ' checked="checked" ';
 4067:             $runoff = ' ';
 4068:         } else {
 4069:             $runoff = ' checked="checked" ';
 4070:             $runon = ' ';
 4071:         }
 4072:     }
 4073:     my $domform = &Apache::loncommon::select_dom_form($defdom,'sender_domain',1);
 4074:     my $notif_sender;
 4075:     if (ref($settings) eq 'HASH') {
 4076:         $notif_sender = $settings->{'sender_uname'};
 4077:     }
 4078:     my $datatable='<tr class="LC_odd_row">'.
 4079:                   '<td>'.&mt('Auto-enrollment active?').'</td>'.
 4080:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4081:                   '<input type="radio" name="autoenroll_run"'.
 4082:                   $runon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4083:                   '<label><input type="radio" name="autoenroll_run"'.
 4084:                   $runoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4085:                   '</tr><tr>'.
 4086:                   '<td>'.&mt('Notification messages - sender').
 4087:                   '</td><td class="LC_right_item"><span class="LC_nobreak">'.
 4088:                   &mt('username').':&nbsp;'.
 4089:                   '<input type="text" name="sender_uname" value="'.
 4090:                   $notif_sender.'" size="10" />&nbsp;&nbsp;'.&mt('domain').
 4091:                   ':&nbsp;'.$domform.'</span></td></tr>'.
 4092:                   '<tr class="LC_odd_row">'.
 4093:                   '<td>'.&mt('Automatically assign co-ownership').'</td>'.
 4094:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4095:                   '<input type="radio" name="autoassign_coowners"'.
 4096:                   $coownerson.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4097:                   '<label><input type="radio" name="autoassign_coowners"'.
 4098:                   $coownersoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4099:                   '</tr><tr>'.
 4100:                   '<td>'.&mt('Failsafe for no drops when institutional data missing').'</td>'.
 4101:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 4102:                   '<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; '.
 4103:                   '<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 />'.
 4104:                   '<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>'.
 4105:                   '<div class="LC_floatleft" style="display:'.$failsafesty.';" id="autoenroll_failsafe_div">'.
 4106:                   '<span class="LC_nobreak">'.
 4107:                   &mt('Threshold for number of students in section to drop: [_1]',
 4108:                       '<input type="text" name="autoenroll_autofailsafe" value="'.$autofailsafe.'" size="4" />').
 4109:                   '</span></div></td></tr>';
 4110:     $$rowtotal += 4;
 4111:     return $datatable;
 4112: }
 4113: 
 4114: sub print_autoupdate {
 4115:     my ($position,$dom,$settings,$rowtotal) = @_;
 4116:     my ($enable,$datatable);
 4117:     if ($position eq 'top') {
 4118:         my %choices = &Apache::lonlocal::texthash (
 4119:                           run        => 'Auto-update active?',
 4120:                           classlists => 'Update information in classlists?',
 4121:                           unexpired  => 'Skip updates for users without active or future roles?',
 4122:                           lastactive => 'Skip updates for inactive users?',
 4123:         );
 4124:         my $itemcount = 0;
 4125:         my $updateon = ' ';
 4126:         my $updateoff = ' checked="checked" ';
 4127:         if (ref($settings) eq 'HASH') {
 4128:             if ($settings->{'run'} eq '1') {
 4129:                 $updateon = $updateoff;
 4130:                 $updateoff = ' ';
 4131:             }
 4132:         }
 4133:         $enable = '<tr class="LC_odd_row">'.
 4134:                   '<td>'.$choices{'run'}.'</td>'.
 4135:                   '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4136:                   '<input type="radio" name="autoupdate_run"'.
 4137:                   $updateoff.'value="0" />'.&mt('No').'</label>&nbsp;'.
 4138:                   '<label><input type="radio" name="autoupdate_run"'.
 4139:                   $updateon.'value="1" />'.&mt('Yes').'</label></span></td>'.
 4140:                   '</tr>';
 4141:         my @toggles = ('classlists','unexpired');
 4142:         my %defaultchecked = ('classlists' => 'off',
 4143:                               'unexpired'  => 'off'
 4144:                               );
 4145:         $$rowtotal ++;
 4146:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4147:                                                      \%choices,$itemcount,'','','left','no');
 4148:         $datatable = $enable.$datatable;
 4149:         $$rowtotal += $itemcount;
 4150:         my $lastactiveon = ' ';
 4151:         my $lastactiveoff = ' checked="checked" ';
 4152:         my $lastactivestyle = 'none';
 4153:         my $lastactivedays;
 4154:         my $onclick = ' onclick="javascript:toggleLastActiveDays(this.form);"';
 4155:         if (ref($settings) eq 'HASH') {
 4156:             if ($settings->{'lastactive'} =~ /^\d+$/) {
 4157:                 $lastactiveon = $lastactiveoff;
 4158:                 $lastactiveoff = ' ';
 4159:                 $lastactivestyle = 'inline-block';
 4160:                 $lastactivedays = $settings->{'lastactive'};
 4161:             }
 4162:         }
 4163:         my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 4164:         $datatable .= '<tr'.$css_class.'>'.
 4165:                       '<td>'.$choices{'lastactive'}.'</td>'.
 4166:                       '<td class="LC_left_item"><span class="LC_nobreak"><label>'.
 4167:                       '<input type="radio" name="lastactive"'.
 4168:                       $lastactiveoff.'value="0"'.$onclick.' />'.&mt('No').'</label>'.
 4169:                       '&nbsp;<label>'.
 4170:                       '<input type="radio" name="lastactive"'.
 4171:                       $lastactiveon.' value="1"'.$onclick.' />'.&mt('Yes').'</label>'.
 4172:                       '<div id="lastactive_div" style="display:'.$lastactivestyle.';">'.
 4173:                       ':&nbsp;'.&mt('inactive = no activity in last [_1] days',
 4174:                           '<input type="text" size="5" name="lastactivedays" value="'.
 4175:                           $lastactivedays.'" />').
 4176:                       '</span></td>'.
 4177:                       '</tr>';
 4178:         $$rowtotal ++;
 4179:     } elsif ($position eq 'middle') {
 4180:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4181:         my $numinrow = 3;
 4182:         my $locknamesettings;
 4183:         $datatable .= &insttypes_row($settings,$types,$usertypes,
 4184:                                      $dom,$numinrow,$othertitle,
 4185:                                     'lockablenames',$rowtotal);
 4186:         $$rowtotal ++;
 4187:     } else {
 4188:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4189:         my @fields = ('lastname','firstname','middlename','generation',
 4190:                       'permanentemail','id');
 4191:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 4192:         my $numrows = 0;
 4193:         if (ref($types) eq 'ARRAY') {
 4194:             if (@{$types} > 0) {
 4195:                 $datatable = 
 4196:                     &usertype_update_row($settings,$usertypes,\%fieldtitles,
 4197:                                          \@fields,$types,\$numrows);
 4198:                     $$rowtotal += @{$types}; 
 4199:             }
 4200:         }
 4201:         $datatable .= 
 4202:             &usertype_update_row($settings,{'default' => $othertitle},
 4203:                                  \%fieldtitles,\@fields,['default'],
 4204:                                  \$numrows);
 4205:         $$rowtotal ++;     
 4206:     }
 4207:     return $datatable;
 4208: }
 4209: 
 4210: sub print_autocreate {
 4211:     my ($dom,$settings,$rowtotal) = @_;
 4212:     my (%createon,%createoff,%currhash);
 4213:     my @types = ('xml','req');
 4214:     if (ref($settings) eq 'HASH') {
 4215:         foreach my $item (@types) {
 4216:             $createoff{$item} = ' checked="checked" ';
 4217:             $createon{$item} = ' ';
 4218:             if (exists($settings->{$item})) {
 4219:                 if ($settings->{$item}) {
 4220:                     $createon{$item} = ' checked="checked" ';
 4221:                     $createoff{$item} = ' ';
 4222:                 }
 4223:             }
 4224:         }
 4225:         if ($settings->{'xmldc'} ne '') {
 4226:             $currhash{$settings->{'xmldc'}} = 1;
 4227:         }
 4228:     } else {
 4229:         foreach my $item (@types) {
 4230:             $createoff{$item} = ' checked="checked" ';
 4231:             $createon{$item} = ' ';
 4232:         }
 4233:     }
 4234:     $$rowtotal += 2;
 4235:     my $numinrow = 2;
 4236:     my $datatable='<tr class="LC_odd_row">'.
 4237:                   '<td>'.&mt('Create pending official courses from XML files').'</td>'.
 4238:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4239:                   '<input type="radio" name="autocreate_xml"'.
 4240:                   $createon{'xml'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4241:                   '<label><input type="radio" name="autocreate_xml"'.
 4242:                   $createoff{'xml'}.' value="0" />'.&mt('No').'</label></span>'.
 4243:                   '</td></tr><tr>'.
 4244:                   '<td>'.&mt('Create pending requests for official courses (if validated)').'</td>'.
 4245:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4246:                   '<input type="radio" name="autocreate_req"'.
 4247:                   $createon{'req'}.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4248:                   '<label><input type="radio" name="autocreate_req"'.
 4249:                   $createoff{'req'}.' value="0" />'.&mt('No').'</label></span>';
 4250:     my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 4251:                                                    'autocreate_xmldc',%currhash);
 4252:     $datatable .= '</td></tr><tr class="LC_odd_row"><td>';
 4253:     if ($numdc > 1) {
 4254:         $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)').
 4255:                       '</td><td class="LC_left_item">';
 4256:     } else {
 4257:         $datatable .= &mt('Course creation processed as:').
 4258:                       '</td><td class="LC_right_item">';
 4259:     }
 4260:     $datatable .= $dctable.'</td></tr>';
 4261:     $$rowtotal += $rows;
 4262:     return $datatable;
 4263: }
 4264: 
 4265: sub print_directorysrch {
 4266:     my ($position,$dom,$settings,$rowtotal) = @_;
 4267:     my $datatable;
 4268:     if ($position eq 'top') {
 4269:         my $instsrchon = ' ';
 4270:         my $instsrchoff = ' checked="checked" ';
 4271:         my ($exacton,$containson,$beginson);
 4272:         my $instlocalon = ' ';
 4273:         my $instlocaloff = ' checked="checked" ';
 4274:         if (ref($settings) eq 'HASH') {
 4275:             if ($settings->{'available'} eq '1') {
 4276:                 $instsrchon = $instsrchoff;
 4277:                 $instsrchoff = ' ';
 4278:             }
 4279:             if ($settings->{'localonly'} eq '1') {
 4280:                 $instlocalon = $instlocaloff;
 4281:                 $instlocaloff = ' ';
 4282:             }
 4283:             if (ref($settings->{'searchtypes'}) eq 'ARRAY') {
 4284:                 foreach my $type (@{$settings->{'searchtypes'}}) {
 4285:                     if ($type eq 'exact') {
 4286:                         $exacton = ' checked="checked" ';
 4287:                     } elsif ($type eq 'contains') {
 4288:                         $containson = ' checked="checked" ';
 4289:                     } elsif ($type eq 'begins') {
 4290:                         $beginson = ' checked="checked" ';
 4291:                     }
 4292:                 }
 4293:             } else {
 4294:                 if ($settings->{'searchtypes'} eq 'exact') {
 4295:                     $exacton = ' checked="checked" ';
 4296:                 } elsif ($settings->{'searchtypes'} eq 'contains') {
 4297:                     $containson = ' checked="checked" ';
 4298:                 } elsif ($settings->{'searchtypes'} eq 'specify') {
 4299:                     $exacton = ' checked="checked" ';
 4300:                     $containson = ' checked="checked" ';
 4301:                 }
 4302:             }
 4303:         }
 4304:         my ($searchtitles,$titleorder) = &sorted_searchtitles();
 4305:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4306: 
 4307:         my $numinrow = 4;
 4308:         my $cansrchrow = 0;
 4309:         $datatable='<tr class="LC_odd_row">'.
 4310:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Institutional directory search available?').'</span></td>'.
 4311:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4312:                    '<input type="radio" name="dirsrch_available"'.
 4313:                    $instsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4314:                    '<label><input type="radio" name="dirsrch_available"'.
 4315:                    $instsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4316:                    '</tr><tr>'.
 4317:                    '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search institution?').'</span></td>'.
 4318:                    '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4319:                    '<input type="radio" name="dirsrch_instlocalonly"'.
 4320:                    $instlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4321:                    '<label><input type="radio" name="dirsrch_instlocalonly"'.
 4322:                    $instlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4323:                    '</tr>';
 4324:         $$rowtotal += 2;
 4325:         if (ref($usertypes) eq 'HASH') {
 4326:             if (keys(%{$usertypes}) > 0) {
 4327:                 $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4328:                                              $numinrow,$othertitle,'cansearch',
 4329:                                              $rowtotal);
 4330:                 $cansrchrow = 1;
 4331:             }
 4332:         }
 4333:         if ($cansrchrow) {
 4334:             $$rowtotal ++;
 4335:             $datatable .= '<tr>';
 4336:         } else {
 4337:             $datatable .= '<tr class="LC_odd_row">';
 4338:         }
 4339:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Supported search methods').
 4340:                       '</span></td><td class="LC_left_item" colspan="2"><table><tr>';
 4341:         foreach my $title (@{$titleorder}) {
 4342:             if (defined($searchtitles->{$title})) {
 4343:                 my $check = ' ';
 4344:                 if (ref($settings) eq 'HASH') {
 4345:                     if (ref($settings->{'searchby'}) eq 'ARRAY') {
 4346:                         if (grep(/^\Q$title\E$/,@{$settings->{'searchby'}})) {
 4347:                             $check = ' checked="checked" ';
 4348:                         }
 4349:                     }
 4350:                 }
 4351:                 $datatable .= '<td class="LC_left_item">'.
 4352:                               '<span class="LC_nobreak"><label>'.
 4353:                               '<input type="checkbox" name="searchby" '.
 4354:                               'value="'.$title.'"'.$check.'/>'.
 4355:                               $searchtitles->{$title}.'</label></span></td>';
 4356:             }
 4357:         }
 4358:         $datatable .= '</tr></table></td></tr>';
 4359:         $$rowtotal ++;
 4360:         if ($cansrchrow) {
 4361:             $datatable .= '<tr class="LC_odd_row">';
 4362:         } else {
 4363:             $datatable .= '<tr>';
 4364:         }
 4365:         $datatable .= '<td><span class ="LC_nobreak">'.&mt('Search latitude').'</span></td>'.   
 4366:                       '<td class="LC_left_item" colspan="2">'.
 4367:                       '<span class="LC_nobreak"><label>'.
 4368:                       '<input type="checkbox" name="searchtypes" '.
 4369:                       $exacton.' value="exact" />'.&mt('Exact match').
 4370:                       '</label>&nbsp;'.
 4371:                       '<label><input type="checkbox" name="searchtypes" '.
 4372:                       $beginson.' value="begins" />'.&mt('Begins with').
 4373:                       '</label>&nbsp;'.
 4374:                       '<label><input type="checkbox" name="searchtypes" '.
 4375:                       $containson.' value="contains" />'.&mt('Contains').
 4376:                       '</label></span></td></tr>';
 4377:         $$rowtotal ++;
 4378:     } else {
 4379:         my $domsrchon = ' checked="checked" ';
 4380:         my $domsrchoff = ' ';
 4381:         my $domlocalon = ' ';
 4382:         my $domlocaloff = ' checked="checked" ';
 4383:         if (ref($settings) eq 'HASH') {
 4384:             if ($settings->{'lclocalonly'} eq '1') {
 4385:                 $domlocalon = $domlocaloff;
 4386:                 $domlocaloff = ' ';
 4387:             }
 4388:             if ($settings->{'lcavailable'} eq '0') {
 4389:                 $domsrchoff = $domsrchon;
 4390:                 $domsrchon = ' ';
 4391:             }
 4392:         }
 4393:         $datatable='<tr class="LC_odd_row">'.
 4394:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('LON-CAPA directory search available?').'</span></td>'.
 4395:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4396:                       '<input type="radio" name="dirsrch_domavailable"'.
 4397:                       $domsrchon.' value="1" />'.&mt('Yes').'</label>&nbsp;'.
 4398:                       '<label><input type="radio" name="dirsrch_domavailable"'.
 4399:                       $domsrchoff.' value="0" />'.&mt('No').'</label></span></td>'.
 4400:                       '</tr><tr>'.
 4401:                       '<td colspan="2"><span class ="LC_nobreak">'.&mt('Other domains can search LON-CAPA domain?').'</span></td>'.
 4402:                       '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
 4403:                       '<input type="radio" name="dirsrch_domlocalonly"'.
 4404:                       $domlocaloff.' value="0" />'.&mt('Yes').'</label>&nbsp;'.
 4405:                       '<label><input type="radio" name="dirsrch_domlocalonly"'.
 4406:                       $domlocalon.' value="1" />'.&mt('No').'</label></span></td>'.
 4407:                       '</tr>';
 4408:         $$rowtotal += 2;
 4409:     }
 4410:     return $datatable;
 4411: }
 4412: 
 4413: sub print_contacts {
 4414:     my ($position,$dom,$settings,$rowtotal) = @_;
 4415:     my $datatable;
 4416:     my @contacts = ('adminemail','supportemail');
 4417:     my (%checked,%to,%otheremails,%bccemails,%includestr,%includeloc,%currfield,
 4418:         $maxsize,$fields,$fieldtitles,$fieldoptions,$possoptions,@mailings,%lonstatus);
 4419:     if ($position eq 'top') {
 4420:         if (ref($settings) eq 'HASH') {
 4421:             foreach my $item (@contacts) {
 4422:                 if (exists($settings->{$item})) {
 4423:                     $to{$item} = $settings->{$item};
 4424:                 }
 4425:             }
 4426:         }
 4427:     } elsif ($position eq 'middle') {
 4428:         @mailings = ('errormail','packagesmail','lonstatusmail','requestsmail',
 4429:                      'updatesmail','idconflictsmail','hostipmail');
 4430:         foreach my $type (@mailings) {
 4431:             $otheremails{$type} = '';
 4432:         }
 4433:     } elsif ($position eq 'lower') {
 4434:         if (ref($settings) eq 'HASH') {
 4435:             if (ref($settings->{'lonstatus'}) eq 'HASH') {
 4436:                 %lonstatus = %{$settings->{'lonstatus'}};
 4437:             }
 4438:         }
 4439:     } else {
 4440:         @mailings = ('helpdeskmail','otherdomsmail');
 4441:         foreach my $type (@mailings) {
 4442:             $otheremails{$type} = '';
 4443:         }
 4444:         $bccemails{'helpdeskmail'} = '';
 4445:         $bccemails{'otherdomsmail'} = '';
 4446:         $includestr{'helpdeskmail'} = '';
 4447:         $includestr{'otherdomsmail'} = '';
 4448:         ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
 4449:     }
 4450:     if (ref($settings) eq 'HASH') {
 4451:         unless (($position eq 'top') || ($position eq 'lower')) {
 4452:             foreach my $type (@mailings) {
 4453:                 if (exists($settings->{$type})) {
 4454:                     if (ref($settings->{$type}) eq 'HASH') {
 4455:                         foreach my $item (@contacts) {
 4456:                             if ($settings->{$type}{$item}) {
 4457:                                 $checked{$type}{$item} = ' checked="checked" ';
 4458:                             }
 4459:                         }
 4460:                         $otheremails{$type} = $settings->{$type}{'others'};
 4461:                         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4462:                             $bccemails{$type} = $settings->{$type}{'bcc'};
 4463:                             if ($settings->{$type}{'include'} ne '') {
 4464:                                 ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4465:                                 $includestr{$type} = &unescape($includestr{$type});
 4466:                             }
 4467:                         }
 4468:                     }
 4469:                 } elsif ($type eq 'lonstatusmail') {
 4470:                     $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4471:                 }
 4472:             }
 4473:         }
 4474:         if ($position eq 'bottom') {
 4475:             foreach my $type (@mailings) {
 4476:                 $bccemails{$type} = $settings->{$type}{'bcc'};
 4477:                 if ($settings->{$type}{'include'} ne '') {
 4478:                     ($includeloc{$type},$includestr{$type}) = split(/:/,$settings->{$type}{'include'},2);
 4479:                     $includestr{$type} = &unescape($includestr{$type});
 4480:                 }
 4481:             }
 4482:             if (ref($settings->{'helpform'}) eq 'HASH') {
 4483:                 if (ref($fields) eq 'ARRAY') {
 4484:                     foreach my $field (@{$fields}) {
 4485:                         $currfield{$field} = $settings->{'helpform'}{$field};
 4486:                     }
 4487:                 }
 4488:                 if (exists($settings->{'helpform'}{'maxsize'})) {
 4489:                     $maxsize = $settings->{'helpform'}{'maxsize'};
 4490:                 } else {
 4491:                     $maxsize = '1.0';
 4492:                 }
 4493:             } else {
 4494:                 if (ref($fields) eq 'ARRAY') {
 4495:                     foreach my $field (@{$fields}) {
 4496:                         $currfield{$field} = 'yes';
 4497:                     }
 4498:                 }
 4499:                 $maxsize = '1.0';
 4500:             }
 4501:         }
 4502:     } else {
 4503:         if ($position eq 'top') {
 4504:             $to{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
 4505:             $to{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
 4506:             $checked{'errormail'}{'adminemail'} = ' checked="checked" ';
 4507:             $checked{'packagesmail'}{'adminemail'} = ' checked="checked" ';
 4508:             $checked{'lonstatusmail'}{'adminemail'} = ' checked="checked" ';
 4509:             $checked{'requestsmail'}{'adminemail'} = ' checked="checked" ';
 4510:             $checked{'updatesmail'}{'adminemail'} = ' checked="checked" ';
 4511:             $checked{'idconflictsmail'}{'adminemail'} = ' checked="checked" ';
 4512:             $checked{'hostipmail'}{'adminemail'} = ' checked="checked" ';
 4513:         } elsif ($position eq 'bottom') {
 4514:             $checked{'helpdeskmail'}{'supportemail'} = ' checked="checked" ';
 4515:             $checked{'otherdomsmail'}{'supportemail'} = ' checked="checked" ';
 4516:             if (ref($fields) eq 'ARRAY') {
 4517:                 foreach my $field (@{$fields}) {
 4518:                     $currfield{$field} = 'yes';
 4519:                 }
 4520:             }
 4521:             $maxsize = '1.0';
 4522:         }
 4523:     }
 4524:     my ($titles,$short_titles) = &contact_titles();
 4525:     my $rownum = 0;
 4526:     my $css_class;
 4527:     if ($position eq 'top') {
 4528:         foreach my $item (@contacts) {
 4529:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4530:             $datatable .= '<tr'.$css_class.'>'. 
 4531:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
 4532:                           '</span></td><td class="LC_right_item">'.
 4533:                           '<input type="text" name="'.$item.'" value="'.
 4534:                           $to{$item}.'" /></td></tr>';
 4535:             $rownum ++;
 4536:         }
 4537:     } elsif ($position eq 'bottom') {
 4538:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4539:         $datatable .= '<tr'.$css_class.'>'.
 4540:                       '<td>'.&mt('Extra helpdesk form fields:').'<br />'.
 4541:                       &mt('(e-mail, subject, and description always shown)').
 4542:                       '</td><td class="LC_left_item">';
 4543:         if ((ref($fields) eq 'ARRAY') && (ref($fieldtitles) eq 'HASH') &&
 4544:             (ref($fieldoptions) eq 'HASH') && (ref($possoptions) eq 'HASH')) {
 4545:             $datatable .= '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Status').'</th></tr>';
 4546:             foreach my $field (@{$fields}) {
 4547:                 $datatable .= '<tr><td>'.$fieldtitles->{$field};
 4548:                 if (($field eq 'screenshot') || ($field eq 'cc')) {
 4549:                     $datatable .= ' '.&mt('(logged-in users)');
 4550:                 }
 4551:                 $datatable .='</td><td>';
 4552:                 my $clickaction;
 4553:                 if ($field eq 'screenshot') {
 4554:                     $clickaction = ' onclick="screenshotSize(this);"';
 4555:                 }
 4556:                 if (ref($possoptions->{$field}) eq 'ARRAY') {
 4557:                     foreach my $option (@{$possoptions->{$field}}) {
 4558:                         my $checked;
 4559:                         if ($currfield{$field} eq $option) {
 4560:                             $checked = ' checked="checked"';
 4561:                         }
 4562:                         $datatable .= '<span class="LC_nobreak"><label>'.
 4563:                                       '<input type="radio" name="helpform_'.$field.'" '.
 4564:                                       'value="'.$option.'"'.$checked.$clickaction.' />'.$fieldoptions->{$option}.
 4565:                                       '</label></span>'.('&nbsp;'x2);
 4566:                     }
 4567:                 }
 4568:                 if ($field eq 'screenshot') {
 4569:                     my $display;
 4570:                     if ($currfield{$field} eq 'no') {
 4571:                         $display = ' style="display:none"';
 4572:                     }
 4573:                     $datatable .= '</td></tr><tr id="help_screenshotsize"'.$display.'>'.
 4574:                                   '<td>'.&mt('Maximum size for upload (MB)').'</td><td>'.
 4575:                                   '<input type="text" size="5" name="helpform_maxsize" value="'.$maxsize.'" />';
 4576:                 }
 4577:                 $datatable .= '</td></tr>';
 4578:             }
 4579:             $datatable .= '</table>';
 4580:         }
 4581:         $datatable .= '</td></tr>'."\n";
 4582:         $rownum ++;
 4583:     }
 4584:     unless (($position eq 'top') || ($position eq 'lower')) {
 4585:         foreach my $type (@mailings) {
 4586:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4587:             $datatable .= '<tr'.$css_class.'>'.
 4588:                           '<td><span class="LC_nobreak">'.
 4589:                           $titles->{$type}.': </span></td>'.
 4590:                           '<td class="LC_left_item">';
 4591:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4592:                 $datatable .= '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>';
 4593:             }
 4594:             $datatable .= '<span class="LC_nobreak">';
 4595:             foreach my $item (@contacts) {
 4596:                 $datatable .= '<label>'.
 4597:                               '<input type="checkbox" name="'.$type.'"'.
 4598:                               $checked{$type}{$item}.
 4599:                               ' value="'.$item.'" />'.$short_titles->{$item}.
 4600:                               '</label>&nbsp;';
 4601:             }
 4602:             $datatable .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4603:                           '<input type="text" name="'.$type.'_others" '.
 4604:                           'value="'.$otheremails{$type}.'"  />';
 4605:             my %locchecked;
 4606:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
 4607:                 foreach my $loc ('s','b') {
 4608:                     if ($includeloc{$type} eq $loc) {
 4609:                         $locchecked{$loc} = ' checked="checked"';
 4610:                         last;
 4611:                     }
 4612:                 }
 4613:                 $datatable .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4614:                               '<input type="text" name="'.$type.'_bcc" '.
 4615:                               'value="'.$bccemails{$type}.'"  /></fieldset>'.
 4616:                               '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4617:                               &mt('Text automatically added to e-mail:').' '.
 4618:                               '<input type="text" name="'.$type.'_includestr" value="'.$includestr{$type}.'" /><br />'.
 4619:                               '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4620:                               '<label><input type="radio" name="'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4621:                               ('&nbsp;'x2).
 4622:                               '<label><input type="radio" name="'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4623:                               '</span></fieldset>';
 4624:             }
 4625:             $datatable .= '</td></tr>'."\n";
 4626:             $rownum ++;
 4627:         }
 4628:     }
 4629:     if ($position eq 'middle') {
 4630:         my %choices;
 4631:         my $corelink = &core_link_msu();
 4632:         $choices{'reporterrors'} = &mt('E-mail error reports to [_1]',$corelink);
 4633:         $choices{'reportupdates'} = &mt('E-mail record of completed LON-CAPA updates to [_1]',
 4634:                                         $corelink);
 4635:         $choices{'reportstatus'} = &mt('E-mail status if errors above threshold to [_1]',$corelink);
 4636:         my @toggles = ('reporterrors','reportupdates','reportstatus');
 4637:         my %defaultchecked = ('reporterrors'  => 'on',
 4638:                               'reportupdates' => 'on',
 4639:                               'reportstatus'  => 'on');
 4640:         (my $reports,$rownum) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4641:                                                    \%choices,$rownum);
 4642:         $datatable .= $reports;
 4643:     } elsif ($position eq 'lower') {
 4644:         my (%current,%excluded,%weights);
 4645:         my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 4646:         if ($lonstatus{'threshold'} =~ /^\d+$/) {
 4647:             $current{'errorthreshold'} = $lonstatus{'threshold'};
 4648:         } else {
 4649:             $current{'errorthreshold'} = $defaults->{'threshold'};
 4650:         }
 4651:         if ($lonstatus{'sysmail'} =~ /^\d+$/) {
 4652:             $current{'errorsysmail'} = $lonstatus{'sysmail'};
 4653:         } else {
 4654:             $current{'errorsysmail'} = $defaults->{'sysmail'};
 4655:         }
 4656:         if (ref($lonstatus{'weights'}) eq 'HASH') {
 4657:             foreach my $type ('E','W','N','U') {
 4658:                 if ($lonstatus{'weights'}{$type} =~ /^\d+$/) {
 4659:                     $weights{$type} = $lonstatus{'weights'}{$type};
 4660:                 } else {
 4661:                     $weights{$type} = $defaults->{$type};
 4662:                 }
 4663:             }
 4664:         } else {
 4665:             foreach my $type ('E','W','N','U') {
 4666:                 $weights{$type} = $defaults->{$type};
 4667:             }
 4668:         }
 4669:         if (ref($lonstatus{'excluded'}) eq 'ARRAY') {
 4670:             if (@{$lonstatus{'excluded'}} > 0) {
 4671:                 map {$excluded{$_} = 1; } @{$lonstatus{'excluded'}};
 4672:             }
 4673:         }
 4674:         foreach my $item ('errorthreshold','errorsysmail') { 
 4675:             $css_class = $rownum%2?' class="LC_odd_row"':'';
 4676:             $datatable .= '<tr'.$css_class.'>'.
 4677:                           '<td class="LC_left_item"><span class="LC_nobreak">'.
 4678:                           $titles->{$item}.
 4679:                           '</span></td><td class="LC_left_item">'.
 4680:                           '<input type="text" name="'.$item.'" value="'.
 4681:                           $current{$item}.'" size="5" /></td></tr>';
 4682:             $rownum ++;
 4683:         }
 4684:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4685:         $datatable .= '<tr'.$css_class.'>'.
 4686:                       '<td class="LC_left_item">'.
 4687:                       '<span class="LC_nobreak">'.$titles->{'errorweights'}.
 4688:                       '</span></td><td class="LC_left_item"><table><tr>';
 4689:         foreach my $type ('E','W','N','U') {
 4690:             $datatable .= '<td>'.$names->{$type}.'<br />'.
 4691:                           '<input type="text" name="errorweights_'.$type.'" value="'.
 4692:                           $weights{$type}.'" size="5" /></td>';
 4693:         }
 4694:         $datatable .= '</tr></table></tr>';
 4695:         $rownum ++;
 4696:         $css_class = $rownum%2?' class="LC_odd_row"':'';
 4697:         $datatable .= '<tr'.$css_class.'><td class="LC_left_item">'.
 4698:                       $titles->{'errorexcluded'}.'</td>'.
 4699:                       '<td class="LC_left_item"><table>';
 4700:         my $numinrow = 4;
 4701:         my @ids = sort(values(%Apache::lonnet::serverhomeIDs));
 4702:         for (my $i=0; $i<@ids; $i++) {
 4703:             my $rem = $i%($numinrow);
 4704:             if ($rem == 0) {
 4705:                 if ($i > 0) {
 4706:                     $datatable .= '</tr>';
 4707:                 }
 4708:                 $datatable .= '<tr>';
 4709:             }
 4710:             my $check;
 4711:             if ($excluded{$ids[$i]}) {
 4712:                 $check = ' checked="checked" ';
 4713:             }
 4714:             $datatable .= '<td class="LC_left_item">'.
 4715:                           '<span class="LC_nobreak"><label>'.
 4716:                           '<input type="checkbox" name="errorexcluded" '.
 4717:                           'value="'.$ids[$i].'"'.$check.' />'.
 4718:                           $ids[$i].'</label></span></td>';
 4719:         }
 4720:         my $colsleft = $numinrow - @ids%($numinrow);
 4721:         if ($colsleft > 1 ) {
 4722:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 4723:                           '&nbsp;</td>';
 4724:         } elsif ($colsleft == 1) {
 4725:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 4726:         }
 4727:         $datatable .= '</tr></table></td></tr>';
 4728:         $rownum ++;
 4729:     } elsif ($position eq 'bottom') {
 4730:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4731:         my (@posstypes,%usertypeshash);
 4732:         if (ref($types) eq 'ARRAY') {
 4733:             @posstypes = @{$types};
 4734:         }
 4735:         if (@posstypes) {
 4736:             if (ref($usertypes) eq 'HASH') {
 4737:                 %usertypeshash = %{$usertypes};
 4738:             }
 4739:             my @overridden;
 4740:             my $numinrow = 4;
 4741:             if (ref($settings) eq 'HASH') {
 4742:                 if (ref($settings->{'overrides'}) eq 'HASH') {
 4743:                     foreach my $key (sort(keys(%{$settings->{'overrides'}}))) {
 4744:                         if (ref($settings->{'overrides'}{$key}) eq 'HASH') {
 4745:                             push(@overridden,$key);
 4746:                             foreach my $item (@contacts) {
 4747:                                 if ($settings->{'overrides'}{$key}{$item}) {
 4748:                                     $checked{'override_'.$key}{$item} = ' checked="checked" ';
 4749:                                 }
 4750:                             }
 4751:                             $otheremails{'override_'.$key} = $settings->{'overrides'}{$key}{'others'};
 4752:                             $bccemails{'override_'.$key} = $settings->{'overrides'}{$key}{'bcc'};
 4753:                             $includeloc{'override_'.$key} = '';
 4754:                             $includestr{'override_'.$key} = '';
 4755:                             if ($settings->{'overrides'}{$key}{'include'} ne '') {
 4756:                                 ($includeloc{'override_'.$key},$includestr{'override_'.$key}) = 
 4757:                                     split(/:/,$settings->{'overrides'}{$key}{'include'},2);
 4758:                                 $includestr{'override_'.$key} = &unescape($includestr{'override_'.$key});
 4759:                             }
 4760:                         }
 4761:                     }
 4762:                 }
 4763:             }
 4764:             my $customclass = 'LC_helpdesk_override';
 4765:             my $optionsprefix = 'LC_options_helpdesk_';
 4766: 
 4767:             my $onclicktypes = "toggleHelpdeskRow(this.form,'overrides','$customclass','$optionsprefix');";
 4768:  
 4769:             $datatable .= &insttypes_row($settings,$types,$usertypes,$dom,
 4770:                                          $numinrow,$othertitle,'overrides',
 4771:                                          \$rownum,$onclicktypes,$customclass);
 4772:             $rownum ++;
 4773:             $usertypeshash{'default'} = $othertitle;
 4774:             foreach my $status (@posstypes) {
 4775:                 my $css_class;
 4776:                 if ($rownum%2) {
 4777:                     $css_class = 'LC_odd_row ';
 4778:                 }
 4779:                 $css_class .= $customclass;
 4780:                 my $rowid = $optionsprefix.$status;
 4781:                 my $hidden = 1;
 4782:                 my $currstyle = 'display:none';
 4783:                 if (grep(/^\Q$status\E$/,@overridden)) {
 4784:                     $currstyle = 'display:table-row';
 4785:                     $hidden = 0;
 4786:                 }
 4787:                 my $key = 'override_'.$status;
 4788:                 $datatable .= &overridden_helpdesk($checked{$key},$otheremails{$key},$bccemails{$key},
 4789:                                                   $includeloc{$key},$includestr{$key},$status,$rowid,
 4790:                                                   $usertypeshash{$status},$css_class,$currstyle,
 4791:                                                   \@contacts,$short_titles);
 4792:                 unless ($hidden) {
 4793:                     $rownum ++;
 4794:                 }
 4795:             }
 4796:         }
 4797:     }
 4798:     $$rowtotal += $rownum;
 4799:     return $datatable;
 4800: }
 4801: 
 4802: sub core_link_msu {
 4803:     return &Apache::loncommon::modal_link('http://loncapa.org/core.html',
 4804:                                           &mt('LON-CAPA core group - MSU'),600,500);
 4805: }
 4806: 
 4807: sub overridden_helpdesk {
 4808:     my ($checked,$otheremails,$bccemails,$includeloc,$includestr,$type,$rowid,
 4809:         $typetitle,$css_class,$rowstyle,$contacts,$short_titles) = @_;
 4810:     my $class = 'LC_left_item';
 4811:     if ($css_class) {
 4812:         $css_class = ' class="'.$css_class.'"';
 4813:     }
 4814:     if ($rowid) {
 4815:         $rowid = ' id="'.$rowid.'"';
 4816:     }
 4817:     if ($rowstyle) {
 4818:         $rowstyle = ' style="'.$rowstyle.'"';
 4819:     }
 4820:     my ($output,$description);
 4821:     $description = &mt('Helpdesk requests from: [_1] in this domain (overrides default)',"<b>$typetitle</b>");
 4822:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
 4823:               "<td>$description</td>\n".
 4824:               '<td class="'.$class.'" colspan="2">'.
 4825:               '<fieldset><legend>'.&mt('E-mail recipient(s)').'</legend>'.
 4826:               '<span class="LC_nobreak">';
 4827:     if (ref($contacts) eq 'ARRAY') {
 4828:         foreach my $item (@{$contacts}) {
 4829:             my $check;
 4830:             if (ref($checked) eq 'HASH') {
 4831:                $check = $checked->{$item};
 4832:             }
 4833:             my $title;
 4834:             if (ref($short_titles) eq 'HASH') {
 4835:                 $title = $short_titles->{$item}; 
 4836:             }
 4837:             $output .= '<label>'.
 4838:                        '<input type="checkbox" name="override_'.$type.'"'.$check.
 4839:                        ' value="'.$item.'" />'.$title.'</label>&nbsp;';
 4840:         }
 4841:     }
 4842:     $output .= '</span><br />'.&mt('Others').':&nbsp;&nbsp;'.
 4843:                '<input type="text" name="override_'.$type.'_others" '.
 4844:                'value="'.$otheremails.'"  />';
 4845:     my %locchecked;
 4846:     foreach my $loc ('s','b') {
 4847:         if ($includeloc eq $loc) {
 4848:             $locchecked{$loc} = ' checked="checked"';
 4849:             last;
 4850:         }
 4851:     }
 4852:     $output .= '<br />'.&mt('Bcc:').('&nbsp;'x6).
 4853:                '<input type="text" name="override_'.$type.'_bcc" '.
 4854:                'value="'.$bccemails.'"  /></fieldset>'.
 4855:                '<fieldset><legend>'.&mt('Optional added text').'</legend>'.
 4856:                &mt('Text automatically added to e-mail:').' '.
 4857:                '<input type="text" name="override_'.$type.'_includestr" value="'.$includestr.'" /><br />'.
 4858:                '<span class="LC_nobreak">'.&mt('Location:').'&nbsp;'.
 4859:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="s"'.$locchecked{'s'}.' />'.&mt('in subject').'</label>'.
 4860:                ('&nbsp;'x2).
 4861:                '<label><input type="radio" name="override_'.$type.'_includeloc" value="b"'.$locchecked{'b'}.' />'.&mt('in body').'</label>'.
 4862:                '</span></fieldset>'.
 4863:                '</td></tr>'."\n";
 4864:     return $output;
 4865: }
 4866: 
 4867: sub contacts_javascript {
 4868:     return <<"ENDSCRIPT";
 4869: 
 4870: <script type="text/javascript">
 4871: // <![CDATA[
 4872: 
 4873: function screenshotSize(field) {
 4874:     if (document.getElementById('help_screenshotsize')) {
 4875:         if (field.value == 'no') {
 4876:             document.getElementById('help_screenshotsize').style.display="none";
 4877:         } else {
 4878:             document.getElementById('help_screenshotsize').style.display="";
 4879:         }
 4880:     }
 4881:     return;
 4882: }
 4883: 
 4884: function toggleHelpdeskRow(form,checkbox,target,prefix,docount) {
 4885:     if (form.elements[checkbox].length != undefined) {
 4886:         var count = 0;
 4887:         if (docount) {
 4888:             for (var i=0; i<form.elements[checkbox].length; i++) {
 4889:                 if (form.elements[checkbox][i].checked) {
 4890:                     count ++;
 4891:                 }
 4892:             }
 4893:         }
 4894:         for (var i=0; i<form.elements[checkbox].length; i++) {
 4895:             var type = form.elements[checkbox][i].value;
 4896:             if (document.getElementById(prefix+type)) {
 4897:                 if (form.elements[checkbox][i].checked) {
 4898:                     document.getElementById(prefix+type).style.display = 'table-row';
 4899:                     if (count % 2 == 1) {
 4900:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
 4901:                     } else {
 4902:                         document.getElementById(prefix+type).className = target;
 4903:                     }
 4904:                     count ++;
 4905:                 } else {
 4906:                     document.getElementById(prefix+type).style.display = 'none';
 4907:                 }
 4908:             }
 4909:         }
 4910:     }
 4911:     return;
 4912: }
 4913: 
 4914: 
 4915: // ]]>
 4916: </script>
 4917: 
 4918: ENDSCRIPT
 4919: }
 4920: 
 4921: sub print_helpsettings {
 4922:     my ($position,$dom,$settings,$rowtotal) = @_;
 4923:     my $confname = $dom.'-domainconfig';
 4924:     my $formname = 'display';
 4925:     my ($datatable,$itemcount);
 4926:     if ($position eq 'top') {
 4927:         $itemcount = 1;
 4928:         my (%choices,%defaultchecked,@toggles);
 4929:         $choices{'submitbugs'} = &mt('Display link to: [_1]?',
 4930:                                      &Apache::loncommon::modal_link('http://bugs.loncapa.org',
 4931:                                      &mt('LON-CAPA bug tracker'),600,500));
 4932:         %defaultchecked = ('submitbugs' => 'on');
 4933:         @toggles = ('submitbugs');
 4934:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 4935:                                                      \%choices,$itemcount);
 4936:         $$rowtotal ++;
 4937:     } else {
 4938:         my $css_class;
 4939:         my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
 4940:         my (%customroles,%ordered,%current);
 4941:         if (ref($settings) eq 'HASH') {
 4942:             if (ref($settings->{'adhoc'}) eq 'HASH') {
 4943:                 %current = %{$settings->{'adhoc'}};
 4944:             }
 4945:         }
 4946:         my $count = 0;
 4947:         foreach my $key (sort(keys(%existing))) {
 4948:             if ($key=~/^rolesdef\_(\w+)$/) {
 4949:                 my $rolename = $1;
 4950:                 my (%privs,$order);
 4951:                 ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
 4952:                 $customroles{$rolename} = \%privs;
 4953:                 if (ref($current{$rolename}) eq 'HASH') {
 4954:                     $order = $current{$rolename}{'order'};
 4955:                 }
 4956:                 if ($order eq '') {
 4957:                     $order = $count;
 4958:                 }
 4959:                 $ordered{$order} = $rolename;
 4960:                 $count++;
 4961:             }
 4962:         }
 4963:         my $maxnum = scalar(keys(%ordered));
 4964:         my @roles_by_num = ();
 4965:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4966:             push(@roles_by_num,$item);
 4967:         }
 4968:         my $context = 'domprefs';
 4969:         my $crstype = 'Course';
 4970:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 4971:         my @accesstypes = ('all','dh','da','none');
 4972:         my ($numstatustypes,@jsarray);
 4973:         if (ref($types) eq 'ARRAY') {
 4974:             if (@{$types} > 0) {
 4975:                 $numstatustypes = scalar(@{$types});
 4976:                 push(@accesstypes,'status');
 4977:                 @jsarray = ('bystatus');
 4978:             }
 4979:         }
 4980:         my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
 4981:         if (keys(%domhelpdesk)) {
 4982:             push(@accesstypes,('inc','exc'));
 4983:             push(@jsarray,('notinc','notexc'));
 4984:         }
 4985:         my $hiddenstr = join("','",@jsarray);
 4986:         my $context = 'domprefs';
 4987:         my $crstype = 'Course';
 4988:         my $prefix = 'helproles_';
 4989:         my $add_class = 'LC_hidden';
 4990:         foreach my $num (@roles_by_num) {
 4991:             my $role = $ordered{$num};
 4992:             my ($desc,$access,@statuses);
 4993:             if (ref($current{$role}) eq 'HASH') {
 4994:                 $desc = $current{$role}{'desc'};
 4995:                 $access = $current{$role}{'access'};
 4996:                 if (ref($current{$role}{'insttypes'}) eq 'ARRAY') {
 4997:                     @statuses = @{$current{$role}{'insttypes'}};
 4998:                 }
 4999:             }
 5000:             if ($desc eq '') {
 5001:                 $desc = $role;
 5002:             }
 5003:             my $identifier = 'custhelp'.$num;
 5004:             my %full=();
 5005:             my %levels= (
 5006:                          course => {},
 5007:                          domain => {},
 5008:                          system => {},
 5009:                         );
 5010:             my %levelscurrent=(
 5011:                                course => {},
 5012:                                domain => {},
 5013:                                system => {},
 5014:                               );
 5015:             &Apache::lonuserutils::custom_role_privs($customroles{$role},\%full,\%levels,\%levelscurrent);
 5016:             my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5017:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5018:             my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$num."_pos'".');"';
 5019:             $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><b>'.$role.'</b><br />'.
 5020:                           '<select name="helproles_'.$num.'_pos"'.$chgstr.'>';
 5021:             for (my $k=0; $k<=$maxnum; $k++) {
 5022:                 my $vpos = $k+1;
 5023:                 my $selstr;
 5024:                 if ($k == $num) {
 5025:                     $selstr = ' selected="selected" ';
 5026:                 }
 5027:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5028:             }
 5029:             $datatable .= '</select>'.('&nbsp;'x2).
 5030:                           '<input type="hidden" name="helproles_'.$num.'" value="'.$role.'" />'.
 5031:                           '</td>'.
 5032:                           '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5033:                           &mt('Name shown to users:').
 5034:                           '<input type="text" name="helproles_'.$num.'_desc" value="'.$desc.'" />'.
 5035:                           '</fieldset>'.
 5036:                           &helpdeskroles_access($dom,$prefix,$num,$add_class,$current{$role},\@accesstypes,
 5037:                                                 $othertitle,$usertypes,$types,\%domhelpdesk).
 5038:                           '<fieldset>'.
 5039:                           '<legend>'.&mt('Role privileges').&adhocbutton($prefix,$num,'privs','show').'</legend>'.
 5040:                           &Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
 5041:                                                                    \%levelscurrent,$identifier,
 5042:                                                                    'LC_hidden',$prefix.$num.'_privs').
 5043:                           '</fieldset></td>';
 5044:             $itemcount ++;
 5045:         }
 5046:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5047:         my $newcust = 'custhelp'.$count;
 5048:         my (%privs,%levelscurrent);
 5049:         my %full=();
 5050:         my %levels= (
 5051:                      course => {},
 5052:                      domain => {},
 5053:                      system => {},
 5054:                     );
 5055:         &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
 5056:         my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
 5057:         my $chgstr = ' onchange="javascript:reorderHelpRoles(this.form,'."'helproles_".$count."_pos'".');"';
 5058:         $datatable .= '<tr '.$css_class.'><td style="vertical-align: top"><span class="LC_nobreak"><label>'.
 5059:                       '<input type="hidden" name="helproles_maxnum" value="'.$maxnum.'" />'."\n".
 5060:                       '<select name="helproles_'.$count.'_pos"'.$chgstr.'>';
 5061:         for (my $k=0; $k<$maxnum+1; $k++) {
 5062:             my $vpos = $k+1;
 5063:             my $selstr;
 5064:             if ($k == $maxnum) {
 5065:                 $selstr = ' selected="selected" ';
 5066:             }
 5067:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5068:         }
 5069:         $datatable .= '</select>&nbsp;'."\n".
 5070:                       '<input type="checkbox" name="newcusthelp" value="'.$count.'" />'. &mt('Add').
 5071:                       '</label></span></td>'.
 5072:                       '<td><fieldset><legend>'.&mt('Role name').'</legend>'.
 5073:                       '<span class="LC_nobreak">'.
 5074:                       &mt('Internal name:').
 5075:                       '<input type="text" size="10" name="custhelpname'.$count.'" value="" />'.
 5076:                       '</span>'.('&nbsp;'x4).
 5077:                       '<span class="LC_nobreak">'.
 5078:                       &mt('Name shown to users:').
 5079:                       '<input type="text" size="20" name="helproles_'.$count.'_desc" value="" />'.
 5080:                       '</span></fieldset>'.
 5081:                        &helpdeskroles_access($dom,$prefix,$count,'',undef,\@accesstypes,$othertitle,
 5082:                                              $usertypes,$types,\%domhelpdesk).
 5083:                       '<fieldset><legend>'.&mt('Role privileges').'</legend>'.
 5084:                       &Apache::lonuserutils::custom_role_header($context,$crstype,
 5085:                                                                 \@templateroles,$newcust).
 5086:                       &Apache::lonuserutils::custom_role_table('Course',\%full,\%levels,
 5087:                                                                \%levelscurrent,$newcust).
 5088:                       '</fieldset>'.
 5089:                       &helpsettings_javascript(\@roles_by_num,$maxnum,$hiddenstr,$formname).
 5090:                       '</td></tr>';
 5091:         $count ++;
 5092:         $$rowtotal += $count;
 5093:     }
 5094:     return $datatable;
 5095: }
 5096: 
 5097: sub adhocbutton {
 5098:     my ($prefix,$num,$field,$visibility) = @_;
 5099:     my %lt = &Apache::lonlocal::texthash(
 5100:                                           show => 'Show details',
 5101:                                           hide => 'Hide details',
 5102:                                         );
 5103:     return '<span style="text-decoration:line-through; font-weight: normal;">'.('&nbsp;'x10).
 5104:            '</span>'.('&nbsp;'x2).'<input type="button" id="'.$prefix.$num.'_'.$field.'_vis"'.
 5105:            ' value="'.$lt{$visibility}.'" style="height:20px;" '.
 5106:            'onclick="toggleHelpdeskItem('."'$num','$field'".');" />'.('&nbsp;'x2);
 5107: }
 5108: 
 5109: sub helpsettings_javascript {
 5110:     my ($roles_by_num,$total,$hiddenstr,$formname) = @_;
 5111:     return unless(ref($roles_by_num) eq 'ARRAY');
 5112:     my %html_js_lt = &Apache::lonlocal::texthash(
 5113:                                           show => 'Show details',
 5114:                                           hide => 'Hide details',
 5115:                                         );
 5116:     &html_escape(\%html_js_lt);
 5117:     my $jstext = '    var helproles = Array('."'".join("','",@{$roles_by_num})."'".');'."\n";
 5118:     return <<"ENDSCRIPT";
 5119: <script type="text/javascript">
 5120: // <![CDATA[
 5121: 
 5122: function reorderHelpRoles(form,item) {
 5123:     var changedVal;
 5124: $jstext
 5125:     var newpos = 'helproles_${total}_pos';
 5126:     var maxh = 1 + $total;
 5127:     var current = new Array();
 5128:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
 5129:     if (item == newpos) {
 5130:         changedVal = newitemVal;
 5131:     } else {
 5132:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
 5133:         current[newitemVal] = newpos;
 5134:     }
 5135:     for (var i=0; i<helproles.length; i++) {
 5136:         var elementName = 'helproles_'+helproles[i]+'_pos';
 5137:         if (elementName != item) {
 5138:             if (form.elements[elementName]) {
 5139:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
 5140:                 current[currVal] = elementName;
 5141:             }
 5142:         }
 5143:     }
 5144:     var oldVal;
 5145:     for (var j=0; j<maxh; j++) {
 5146:         if (current[j] == undefined) {
 5147:             oldVal = j;
 5148:         }
 5149:     }
 5150:     if (oldVal < changedVal) {
 5151:         for (var k=oldVal+1; k<=changedVal ; k++) {
 5152:            var elementName = current[k];
 5153:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
 5154:         }
 5155:     } else {
 5156:         for (var k=changedVal; k<oldVal; k++) {
 5157:             var elementName = current[k];
 5158:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
 5159:         }
 5160:     }
 5161:     return;
 5162: }
 5163: 
 5164: function helpdeskAccess(num) {
 5165:     var curraccess = null;
 5166:     if (document.$formname.elements['helproles_'+num+'_access'].length) {
 5167:         for (var i=0; i<document.$formname.elements['helproles_'+num+'_access'].length; i++) {
 5168:             if (document.$formname.elements['helproles_'+num+'_access'][i].checked) {
 5169:                 curraccess = document.$formname.elements['helproles_'+num+'_access'][i].value;
 5170:             }
 5171:         }
 5172:     }
 5173:     var shown = Array();
 5174:     var hidden = Array();
 5175:     if (curraccess == 'none') {
 5176:         hidden = Array('$hiddenstr');
 5177:     } else {
 5178:         if (curraccess == 'status') {
 5179:             shown = Array('bystatus');
 5180:             hidden = Array('notinc','notexc');
 5181:         } else {
 5182:             if (curraccess == 'exc') {
 5183:                 shown = Array('notexc');
 5184:                 hidden = Array('notinc','bystatus');
 5185:             }
 5186:             if (curraccess == 'inc') {
 5187:                 shown = Array('notinc');
 5188:                 hidden = Array('notexc','bystatus');
 5189:             }
 5190:             if ((curraccess == 'all') || (curraccess == 'dh') || (curraccess == 'da')) {
 5191:                 hidden = Array('notinc','notexc','bystatus');
 5192:             }
 5193:         }
 5194:     }
 5195:     if (hidden.length > 0) {
 5196:         for (var i=0; i<hidden.length; i++) {
 5197:             if (document.getElementById('helproles_'+num+'_'+hidden[i])) {
 5198:                 document.getElementById('helproles_'+num+'_'+hidden[i]).style.display = 'none';
 5199:             }
 5200:         }
 5201:     }
 5202:     if (shown.length > 0) {
 5203:         for (var i=0; i<shown.length; i++) {
 5204:             if (document.getElementById('helproles_'+num+'_'+shown[i])) {
 5205:                 if (shown[i] == 'privs') {
 5206:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'block';
 5207:                 } else {
 5208:                     document.getElementById('helproles_'+num+'_'+shown[i]).style.display = 'inline-block';
 5209:                 }
 5210:             }
 5211:         }
 5212:     }
 5213:     return;
 5214: }
 5215: 
 5216: function toggleHelpdeskItem(num,field) {
 5217:     if (document.getElementById('helproles_'+num+'_'+field)) {
 5218:         if (document.getElementById('helproles_'+num+'_'+field).className.match(/(?:^|\\s)LC_hidden(?!\\S)/)) {
 5219:             document.getElementById('helproles_'+num+'_'+field).className =
 5220:                 document.getElementById('helproles_'+num+'_'+field).className.replace(/(?:^|\\s)LC_hidden(?!\\S)/g ,'');
 5221:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5222:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{hide}';
 5223:             }
 5224:         } else {
 5225:             document.getElementById('helproles_'+num+'_'+field).className += ' LC_hidden';
 5226:             if (document.getElementById('helproles_'+num+'_'+field+'_vis')) {
 5227:                 document.getElementById('helproles_'+num+'_'+field+'_vis').value = '$html_js_lt{show}';
 5228:             }
 5229:         }
 5230:     }
 5231:     return;
 5232: }
 5233: 
 5234: // ]]>
 5235: </script>
 5236: 
 5237: ENDSCRIPT
 5238: }
 5239: 
 5240: sub helpdeskroles_access {
 5241:     my ($dom,$prefix,$num,$add_class,$current,$accesstypes,$othertitle,
 5242:         $usertypes,$types,$domhelpdesk) = @_;
 5243:     return unless ((ref($accesstypes) eq 'ARRAY') && (ref($domhelpdesk) eq 'HASH'));
 5244:     my %lt = &Apache::lonlocal::texthash(
 5245:                     'rou'    => 'Role usage',
 5246:                     'whi'    => 'Which helpdesk personnel may use this role?',
 5247:                     'all'    => 'All with domain helpdesk or helpdesk assistant role',
 5248:                     'dh'     => 'All with domain helpdesk role',
 5249:                     'da'     => 'All with domain helpdesk assistant role',
 5250:                     'none'   => 'None',
 5251:                     'status' => 'Determined based on institutional status',
 5252:                     'inc'    => 'Include all, but exclude specific personnel',
 5253:                     'exc'    => 'Exclude all, but include specific personnel',
 5254:                   );
 5255:     my %usecheck = (
 5256:                      all => ' checked="checked"',
 5257:                    );
 5258:     my %displaydiv = (
 5259:                       status => 'none',
 5260:                       inc    => 'none',
 5261:                       exc    => 'none',
 5262:                       priv   => 'block',
 5263:                      );
 5264:     my $output;
 5265:     if (ref($current) eq 'HASH') {
 5266:         if (($current->{'access'} ne '') && ($current->{'access'} ne 'all')) {
 5267:             if (grep(/^\Q$current->{access}\E$/,@{$accesstypes})) {
 5268:                 $usecheck{$current->{access}} = $usecheck{'all'};
 5269:                 delete($usecheck{'all'});
 5270:                 if ($current->{access} =~ /^(status|inc|exc)$/) {
 5271:                     my $access = $1;
 5272:                     $displaydiv{$access} = 'inline';
 5273:                 } elsif ($current->{access} eq 'none') {
 5274:                     $displaydiv{'priv'} = 'none';
 5275:                 }
 5276:             }
 5277:         }
 5278:     }
 5279:     $output = '<fieldset id="'.$prefix.$num.'_usage"><legend>'.$lt{'rou'}.'</legend>'.
 5280:               '<p>'.$lt{'whi'}.'</p>';
 5281:     foreach my $access (@{$accesstypes}) {
 5282:         $output .= '<p><label><input type="radio" name="'.$prefix.$num.'_access" value="'.$access.'" '.$usecheck{$access}.
 5283:                    ' onclick="helpdeskAccess('."'$num'".');" />'.
 5284:                    $lt{$access}.'</label>';
 5285:         if ($access eq 'status') {
 5286:             $output .= '<div id="'.$prefix.$num.'_bystatus" style="display:'.$displaydiv{$access}.'">'.
 5287:                        &Apache::lonuserutils::adhoc_status_types($dom,$prefix,$num,$current->{$access},
 5288:                                                                  $othertitle,$usertypes,$types).
 5289:                        '</div>';
 5290:         } elsif (($access eq 'inc') && (keys(%{$domhelpdesk}) > 0)) {
 5291:             $output .= '<div id="'.$prefix.$num.'_notinc" style="display:'.$displaydiv{$access}.'">'.
 5292:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5293:                        '</div>';
 5294:         } elsif (($access eq 'exc') && (keys(%{$domhelpdesk}) > 0)) {
 5295:             $output .= '<div id="'.$prefix.$num.'_notexc" style="display:'.$displaydiv{$access}.'">'.
 5296:                        &Apache::lonuserutils::adhoc_staff($access,$prefix,$num,$current->{$access},$domhelpdesk).
 5297:                        '</div>';
 5298:         }
 5299:         $output .= '</p>';
 5300:     }
 5301:     $output .= '</fieldset>';
 5302:     return $output;
 5303: }
 5304: 
 5305: sub radiobutton_prefs {
 5306:     my ($settings,$toggles,$defaultchecked,$choices,$itemcount,$onclick,
 5307:         $additional,$align,$firstval) = @_;
 5308:     return unless ((ref($toggles) eq 'ARRAY') && (ref($defaultchecked) eq 'HASH') &&
 5309:                    (ref($choices) eq 'HASH'));
 5310: 
 5311:     my (%checkedon,%checkedoff,$datatable,$css_class);
 5312: 
 5313:     foreach my $item (@{$toggles}) {
 5314:         if ($defaultchecked->{$item} eq 'on') {
 5315:             $checkedon{$item} = ' checked="checked" ';
 5316:             $checkedoff{$item} = ' ';
 5317:         } elsif ($defaultchecked->{$item} eq 'off') {
 5318:             $checkedoff{$item} = ' checked="checked" ';
 5319:             $checkedon{$item} = ' ';
 5320:         }
 5321:     }
 5322:     if (ref($settings) eq 'HASH') {
 5323:         foreach my $item (@{$toggles}) {
 5324:             if ($settings->{$item} eq '1') {
 5325:                 $checkedon{$item} =  ' checked="checked" ';
 5326:                 $checkedoff{$item} = ' ';
 5327:             } elsif ($settings->{$item} eq '0') {
 5328:                 $checkedoff{$item} =  ' checked="checked" ';
 5329:                 $checkedon{$item} = ' ';
 5330:             }
 5331:         }
 5332:     }
 5333:     if ($onclick) {
 5334:         $onclick = ' onclick="'.$onclick.'"';
 5335:     }
 5336:     foreach my $item (@{$toggles}) {
 5337:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5338:         $datatable .=
 5339:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 5340:             '<span class="LC_nobreak">'.$choices->{$item}.
 5341:             '</span></td>';
 5342:         if ($align eq 'left') {
 5343:             $datatable .= '<td class="LC_left_item">';
 5344:         } else {
 5345:             $datatable .= '<td class="LC_right_item">';
 5346:         }
 5347:         $datatable .= '<span class="LC_nobreak">';
 5348:         if ($firstval eq 'no') {
 5349:             $datatable .=
 5350:                 '<label><input type="radio" name="'.
 5351:                 $item.'" '.$checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').
 5352:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5353:                 $checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').'</label>';
 5354:         } else {
 5355:             $datatable .=
 5356:                 '<label><input type="radio" name="'.
 5357:                 $item.'" '.$checkedon{$item}.' value="1"'.$onclick.' />'.&mt('Yes').
 5358:                 '</label>&nbsp;<label><input type="radio" name="'.$item.'" '.
 5359:                 $checkedoff{$item}.' value="0"'.$onclick.' />'.&mt('No').'</label>';
 5360:         }
 5361:         $datatable .= '</span>'.$additional.'</td></tr>';
 5362:         $itemcount ++;
 5363:     }
 5364:     return ($datatable,$itemcount);
 5365: }
 5366: 
 5367: sub print_ltitools {
 5368:     my ($dom,$settings,$rowtotal) = @_;
 5369:     my $rownum = 0;
 5370:     my $css_class;
 5371:     my $itemcount = 1;
 5372:     my $maxnum = 0;
 5373:     my %ordered;
 5374:     if (ref($settings) eq 'HASH') {
 5375:         foreach my $item (keys(%{$settings})) {
 5376:             if (ref($settings->{$item}) eq 'HASH') {
 5377:                 my $num = $settings->{$item}{'order'};
 5378:                 $ordered{$num} = $item;
 5379:             }
 5380:         }
 5381:     }
 5382:     my $confname = $dom.'-domainconfig';
 5383:     my $switchserver = &check_switchserver($dom,$confname);
 5384:     my $maxnum = scalar(keys(%ordered));
 5385:     my $datatable;
 5386:     my %lt = &ltitools_names();
 5387:     my @courseroles = ('cc','in','ta','ep','st');
 5388:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
 5389:     my @fields = ('fullname','firstname','lastname','email','roles','user');
 5390:     if (keys(%ordered)) {
 5391:         my @items = sort { $a <=> $b } keys(%ordered);
 5392:         for (my $i=0; $i<@items; $i++) {
 5393:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5394:             my $item = $ordered{$items[$i]};
 5395:             my ($title,$key,$secret,$url,$lifetime,$imgsrc,%sigsel);
 5396:             if (ref($settings->{$item}) eq 'HASH') {
 5397:                 $title = $settings->{$item}->{'title'};
 5398:                 $url = $settings->{$item}->{'url'};
 5399:                 $key = $settings->{$item}->{'key'};
 5400:                 $secret = $settings->{$item}->{'secret'};
 5401:                 $lifetime = $settings->{$item}->{'lifetime'};
 5402:                 my $image = $settings->{$item}->{'image'};
 5403:                 if ($image ne '') {
 5404:                     $imgsrc = '<img src="'.$image.'" alt="'.&mt('Tool Provider icon').'" />';
 5405:                 }
 5406:                 if ($settings->{$item}->{'sigmethod'} eq 'HMAC-256') {
 5407:                     $sigsel{'HMAC-256'} = ' selected="selected"';
 5408:                 } else {
 5409:                     $sigsel{'HMAC-SHA1'} = ' selected="selected"';
 5410:                 }
 5411:             }
 5412:             my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_".$item."'".');"';
 5413:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5414:                          .'<select name="ltitools_'.$item.'"'.$chgstr.'>';
 5415:             for (my $k=0; $k<=$maxnum; $k++) {
 5416:                 my $vpos = $k+1;
 5417:                 my $selstr;
 5418:                 if ($k == $i) {
 5419:                     $selstr = ' selected="selected" ';
 5420:                 }
 5421:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5422:             }
 5423:             $datatable .= '</select>'.('&nbsp;'x2).
 5424:                 '<label><input type="checkbox" name="ltitools_del" value="'.$item.'" />'.
 5425:                 &mt('Delete?').'</label></span></td>'.
 5426:                 '<td colspan="2">'.
 5427:                 '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5428:                 '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_title_'.$i.'" value="'.$title.'" /></span> '.
 5429:                 ('&nbsp;'x2).
 5430:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_version_'.$i.'">'.
 5431:                 '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 5432:                 ('&nbsp;'x2).
 5433:                 '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_msgtype_'.$i.'">'.
 5434:                 '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5435:                 ('&nbsp;'x2).
 5436:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_sigmethod_'.$i.'">'.
 5437:                 '<option value="HMAC-SHA1"'.$sigsel{'HMAC-SHA1'}.'>HMAC-SHA1</option>'.
 5438:                 '<option value="HMAC-SHA256"'.$sigsel{'HMAC-SHA256'}.'>HMAC-SHA256</option></select></span>'.
 5439:                 '<br /><br />'.
 5440:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_url_'.$i.'"'.
 5441:                 ' value="'.$url.'" /></span>'.
 5442:                 ('&nbsp;'x2).
 5443:                 '<span class="LC_nobreak">'.$lt{'key'}.':'.
 5444:                 '<input type="text" size="25" name="ltitools_key_'.$i.'" value="'.$key.'" /></span> '.
 5445:                 ('&nbsp;'x2).
 5446:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':'.
 5447:                 '<input type="text" size="5" name="ltitools_lifetime_'.$i.'" value="'.$lifetime.'" /></span> '.
 5448:                 ('&nbsp;'x2).
 5449:                 '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 5450:                 '<input type="password" size="20" name="ltitools_secret_'.$i.'" value="'.$secret.'" />'.
 5451:                 '<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>'.
 5452:                 '<input type="hidden" name="ltitools_id_'.$i.'" value="'.$item.'" /></span>'.
 5453:                 '</fieldset>'.
 5454:                 '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5455:                 '<span class="LC_nobreak">'.&mt('Display target:');
 5456:             my %currdisp;
 5457:             if (ref($settings->{$item}->{'display'}) eq 'HASH') {
 5458:                 if ($settings->{$item}->{'display'}->{'target'} eq 'window') {
 5459:                     $currdisp{'window'} = ' checked="checked"';
 5460:                 } elsif ($settings->{$item}->{'display'}->{'target'} eq 'tab') {
 5461:                     $currdisp{'tab'} = ' checked="checked"';
 5462:                 } else {
 5463:                     $currdisp{'iframe'} = ' checked="checked"';
 5464:                 }
 5465:                 if ($settings->{$item}->{'display'}->{'width'} =~ /^(\d+)$/) {
 5466:                     $currdisp{'width'} = $1;
 5467:                 }
 5468:                 if ($settings->{$item}->{'display'}->{'height'} =~ /^(\d+)$/) {
 5469:                      $currdisp{'height'} = $1;
 5470:                 }
 5471:                 $currdisp{'linktext'} = $settings->{$item}->{'display'}->{'linktext'};
 5472:                 $currdisp{'explanation'} = $settings->{$item}->{'display'}->{'explanation'};
 5473:             } else {
 5474:                 $currdisp{'iframe'} = ' checked="checked"';
 5475:             }
 5476:             foreach my $disp ('iframe','tab','window') {
 5477:                 $datatable .= '<label><input type="radio" name="ltitools_target_'.$i.'" value="'.$disp.'"'.$currdisp{$disp}.' />'.
 5478:                               $lt{$disp}.'</label>'.('&nbsp;'x2);
 5479:             }
 5480:             $datatable .= ('&nbsp;'x4);
 5481:             foreach my $dimen ('width','height') {
 5482:                 $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5483:                               '<input type="text" name="ltitools_'.$dimen.'_'.$i.'" size="5" value="'.$currdisp{$dimen}.'" /></label>'.
 5484:                               ('&nbsp;'x2);
 5485:             }
 5486:             $datatable .= '</span><br />'.
 5487:                           '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5488:                           '<input type="text" name="ltitools_linktext_'.$i.'" size="25" value="'.$currdisp{'linktext'}.'" /></div>'.
 5489:                           '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5490:                           '<textarea name="ltitools_explanation_'.$i.'" rows="5" cols="40">'.$currdisp{'explanation'}.
 5491:                           '</textarea></div><div style=""></div><br />';
 5492:             my %units = (
 5493:                           'passback' => 'days',
 5494:                           'roster'   => 'seconds',
 5495:                         );
 5496:             foreach my $extra ('passback','roster') {
 5497:                 my $validsty = 'none';
 5498:                 my $currvalid;
 5499:                 my $checkedon = '';
 5500:                 my $checkedoff = ' checked="checked"';
 5501:                 if ($settings->{$item}->{$extra}) {
 5502:                     $checkedon = $checkedoff;
 5503:                     $checkedoff = '';
 5504:                     $validsty = 'inline-block';
 5505:                     if ($settings->{$item}->{$extra.'valid'} =~ /^\d+\.?\d*$/) {
 5506:                         $currvalid = $settings->{$item}->{$extra.'valid'};
 5507:                     }
 5508:                 }
 5509:                 my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','$i'".');"';
 5510:                 $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5511:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="0"'.$checkedoff.$onclick.' />'.
 5512:                               &mt('No').'</label>'.('&nbsp;'x2).
 5513:                               '<label><input type="radio" name="ltitools_'.$extra.'_'.$i.'" value="1"'.$checkedon.$onclick.' />'.
 5514:                               &mt('Yes').'</label></span></div>'.
 5515:                               '<div class="LC_floatleft" style="display:'.$validsty.';" id="ltitools_'.$extra.'time_'.$i.'">'.
 5516:                               '<span class="LC_nobreak">'.
 5517:                               &mt("at least [_1] $units{$extra} after launch",
 5518:                                   '<input type="text" name="ltitools_'.$extra.'valid_'.$i.'" value="'.$currvalid.'" />').
 5519:                               '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5520:             }
 5521:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 5522:             if ($imgsrc) {
 5523:                 $datatable .= $imgsrc.
 5524:                               '<label><input type="checkbox" name="ltitools_image_del"'.
 5525:                               ' value="'.$item.'" />'.&mt('Delete?').'</label></span> '.
 5526:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:').'&nbsp;';
 5527:             } else {
 5528:                 $datatable .= '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5529:             }
 5530:             if ($switchserver) {
 5531:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5532:             } else {
 5533:                 $datatable .= '<input type="file" name="ltitools_image_'.$i.'" value="" />';
 5534:             }
 5535:             $datatable .= '</span></fieldset>';
 5536:             my (%checkedfields,%rolemaps,$userincdom);
 5537:             if (ref($settings->{$item}) eq 'HASH') {
 5538:                 if (ref($settings->{$item}->{'fields'}) eq 'HASH') {
 5539:                     %checkedfields = %{$settings->{$item}->{'fields'}};
 5540:                 }
 5541:                 $userincdom = $settings->{$item}->{'incdom'};
 5542:                 if (ref($settings->{$item}->{'roles'}) eq 'HASH') {
 5543:                     %rolemaps = %{$settings->{$item}->{'roles'}};
 5544:                     $checkedfields{'roles'} = 1;
 5545:                 }
 5546:             }
 5547:             $datatable .= '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5548:                           '<span class="LC_nobreak">';
 5549:             my $userfieldstyle = 'display:none;';
 5550:             my $seluserdom = '';
 5551:             my $unseluserdom = ' selected="selected"';
 5552:             foreach my $field (@fields) {
 5553:                 my ($checked,$onclick,$id,$spacer);
 5554:                 if ($checkedfields{$field}) {
 5555:                     $checked = ' checked="checked"';
 5556:                 }
 5557:                 if ($field eq 'user') {
 5558:                     $id = ' id="ltitools_user_field_'.$i.'"';
 5559:                     $onclick = ' onclick="toggleLTITools(this.form,'."'$field','$i'".')"';
 5560:                     if ($checked) {
 5561:                         $userfieldstyle = 'display:inline-block';
 5562:                         if ($userincdom) {
 5563:                             $seluserdom = $unseluserdom;
 5564:                             $unseluserdom = '';
 5565:                         }
 5566:                     }
 5567:                 } else {
 5568:                     $spacer = ('&nbsp;' x2);
 5569:                 }
 5570:                 $datatable .= '<label>'.
 5571:                               '<input type="checkbox" name="ltitools_fields_'.$i.'" value="'.$field.'"'.$id.$checked.$onclick.' />'.
 5572:                               $lt{$field}.'</label>'.$spacer;
 5573:             }
 5574:             $datatable .= '</span>';
 5575:             $datatable .= '<div style="'.$userfieldstyle.'" id="ltitools_user_div_'.$i.'">'.
 5576:                           '<span class="LC_nobreak"> : '.
 5577:                           '<select name="ltitools_userincdom_'.$i.'">'.
 5578:                           '<option value="">'.&mt('Select').'</option>'.
 5579:                           '<option value="0"'.$unseluserdom.'>'.&mt('username').'</option>'.
 5580:                           '<option value="1"'.$seluserdom.'>'.&mt('username:domain').'</option>'.
 5581:                           '</select></span></div>';
 5582:             $datatable .= '</fieldset>'.
 5583:                           '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5584:             foreach my $role (@courseroles) {
 5585:                 my ($selected,$selectnone);
 5586:                 if (!$rolemaps{$role}) {
 5587:                     $selectnone = ' selected="selected"';
 5588:                 }
 5589:                 $datatable .= '<td style="text-align: center">'. 
 5590:                               &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5591:                               '<select name="ltitools_roles_'.$role.'_'.$i.'">'.
 5592:                               '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 5593:                 foreach my $ltirole (@ltiroles) {
 5594:                     unless ($selectnone) {
 5595:                         if ($rolemaps{$role} eq $ltirole) {
 5596:                             $selected = ' selected="selected"';
 5597:                         } else {
 5598:                             $selected = '';
 5599:                         }
 5600:                     }
 5601:                     $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 5602:                 }
 5603:                 $datatable .= '</select></td>';
 5604:             }
 5605:             $datatable .= '</tr></table></fieldset>';
 5606:             my %courseconfig;
 5607:             if (ref($settings->{$item}) eq 'HASH') {
 5608:                 if (ref($settings->{$item}->{'crsconf'}) eq 'HASH') {
 5609:                     %courseconfig = %{$settings->{$item}->{'crsconf'}};
 5610:                 }
 5611:             }
 5612:             $datatable .= '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5613:             foreach my $item ('label','title','target','linktext','explanation','append') {
 5614:                 my $checked;
 5615:                 if ($courseconfig{$item}) {
 5616:                     $checked = ' checked="checked"';
 5617:                 }
 5618:                 $datatable .= '<label>'.
 5619:                        '<input type="checkbox" name="ltitools_courseconfig_'.$i.'" value="'.$item.'"'.$checked.' />'.
 5620:                        $lt{'crs'.$item}.'</label>&nbsp; '."\n";
 5621:             }
 5622:             $datatable .= '</span></fieldset>'.
 5623:                           '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5624:                           '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>';
 5625:             if (ref($settings->{$item}->{'custom'}) eq 'HASH') {
 5626:                 my %custom = %{$settings->{$item}->{'custom'}};
 5627:                 if (keys(%custom) > 0) {
 5628:                     foreach my $key (sort(keys(%custom))) {
 5629:                         $datatable .= '<tr><td><span class="LC_nobreak">'.
 5630:                                       '<label><input type="checkbox" name="ltitools_customdel_'.$i.'" value="'.
 5631:                                       $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 5632:                                       '<td><input type="text" name="ltitools_customval_'.$key.'_'.$i.'"'.
 5633:                                       ' value="'.$custom{$key}.'" /></td></tr>';
 5634:                     }
 5635:                 }
 5636:             }
 5637:             $datatable .= '<tr><td><span class="LC_nobreak">'.
 5638:                           '<label><input type="checkbox" name="ltitools_customadd" value="'.$i.'" />'.
 5639:                           &mt('Add').'</label></span></td><td><input type="text" name="ltitools_custom_name_'.$i.'" />'.
 5640:                           '</td><td><input type="text" name="ltitools_custom_value_'.$i.'" /></td></tr>';
 5641:             $datatable .= '</table></fieldset></td></tr>'."\n";
 5642:             $itemcount ++;
 5643:         }
 5644:     }
 5645:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5646:     my $chgstr = ' onchange="javascript:reorderLTITools(this.form,'."'ltitools_add_pos'".');"';
 5647:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 5648:                   '<input type="hidden" name="ltitools_maxnum" value="'.$maxnum.'" />'."\n".
 5649:                   '<select name="ltitools_add_pos"'.$chgstr.'>';
 5650:     for (my $k=0; $k<$maxnum+1; $k++) {
 5651:         my $vpos = $k+1;
 5652:         my $selstr;
 5653:         if ($k == $maxnum) {
 5654:             $selstr = ' selected="selected" ';
 5655:         }
 5656:         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5657:     }
 5658:     $datatable .= '</select>&nbsp;'."\n".
 5659:                   '<input type="checkbox" name="ltitools_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 5660:                   '<td colspan="2">'.
 5661:                   '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 5662:                   '<span class="LC_nobreak">'.$lt{'title'}.':<input type="text" size="20" name="ltitools_add_title" value="" /></span> '."\n".
 5663:                   ('&nbsp;'x2).
 5664:                   '<span class="LC_nobreak">'.$lt{'version'}.':<select name="ltitools_add_version">'.
 5665:                   '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 5666:                   ('&nbsp;'x2).
 5667:                   '<span class="LC_nobreak">'.$lt{'msgtype'}.':<select name="ltitools_add_msgtype">'.
 5668:                   '<option value="basic-lti-launch-request" selected="selected">Launch</option></select></span> '.
 5669:                   '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="ltitools_add_sigmethod">'.
 5670:                   '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5671:                   '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5672:                   '<br />'.
 5673:                   '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="ltitools_add_url" value="" /></span> '."\n".
 5674:                   ('&nbsp;'x2).
 5675:                   '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="ltitools_add_key" value="" /></span> '."\n".
 5676:                   ('&nbsp;'x2).
 5677:                   '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="ltitools_add_lifetime" value="300" /></span> '."\n".
 5678:                   ('&nbsp;'x2).
 5679:                   '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="ltitools_add_secret" value="" />'.
 5680:                   '<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".
 5681:                   '</fieldset>'.
 5682:                   '<fieldset><legend>'.&mt('Optional settings').'</legend>'.
 5683:                   '<span class="LC_nobreak">'.&mt('Display target:');
 5684:     my %defaultdisp;
 5685:     $defaultdisp{'iframe'} = ' checked="checked"';
 5686:     foreach my $disp ('iframe','tab','window') {
 5687:         $datatable .= '<label><input type="radio" name="ltitools_add_target" value="'.$disp.'"'.$defaultdisp{$disp}.' />'.
 5688:                       $lt{$disp}.'</label>'.('&nbsp;'x2);
 5689:     }
 5690:     $datatable .= ('&nbsp;'x4);
 5691:     foreach my $dimen ('width','height') {
 5692:         $datatable .= '<label>'.$lt{$dimen}.'&nbsp;'.
 5693:                       '<input type="text" name="ltitools_add_'.$dimen.'" size="5" /></label>'.
 5694:                       ('&nbsp;'x2);
 5695:     }
 5696:     $datatable .= '</span><br />'.
 5697:                   '<div class="LC_left_float">'.$lt{'linktext'}.'<br />'.
 5698:                   '<input type="text" name="ltitools_add_linktext" size="5" /></div>'.
 5699:                   '<div class="LC_left_float">'.$lt{'explanation'}.'<br />'.
 5700:                   '<textarea name="ltitools_add_explanation" rows="5" cols="40"></textarea>'.
 5701:                   '</div><div style=""></div><br />';
 5702:     my %units = (
 5703:                   'passback' => 'days',
 5704:                   'roster'   => 'seconds',
 5705:                 );
 5706:     my %defaulttimes = (
 5707:                      'passback' => '7',
 5708:                      'roster'   => '300',
 5709:                    );
 5710:     foreach my $extra ('passback','roster') {
 5711:         my $onclick = ' onclick="toggleLTITools(this.form,'."'$extra','add'".');"';
 5712:         $datatable .= '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{$extra}.'&nbsp;'.
 5713:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="0" checked="checked"'.$onclick.' />'.
 5714:                       &mt('No').'</label></span>'.('&nbsp;'x2).'<span class="LC_nobreak">'.
 5715:                       '<label><input type="radio" name="ltitools_'.$extra.'_add" value="1"'.$onclick.' />'.
 5716:                       &mt('Yes').'</label></span></div>'.
 5717:                       '<div class="LC_floatleft" style="display:none;" id="ltitools_'.$extra.'time_add">'.
 5718:                       '<span class="LC_nobreak">'.
 5719:                       &mt("at least [_1] $units{$extra} after launch",
 5720:                           '<input type="text" name="ltitools_'.$extra.'valid_add" value="'.$defaulttimes{$extra}.'" />').
 5721:                       '</span></div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 5722:     }
 5723:     $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;'.
 5724:                   '('.&mt('if larger than 21x21 pixels, image will be scaled').')&nbsp;';
 5725:     if ($switchserver) {
 5726:         $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 5727:     } else {
 5728:         $datatable .= '<input type="file" name="ltitools_add_image" value="" />';
 5729:     }
 5730:     $datatable .= '</span></fieldset>'.
 5731:                   '<fieldset><legend>'.&mt('User data sent on launch').'</legend>'.
 5732:                   '<span class="LC_nobreak">';
 5733:     foreach my $field (@fields) {
 5734:         my ($id,$onclick,$spacer);
 5735:         if ($field eq 'user') {
 5736:             $id = ' id="ltitools_user_field_add"';
 5737:             $onclick = ' onclick="toggleLTITools(this.form,'."'$field','add'".')"';
 5738:         } else {
 5739:             $spacer = ('&nbsp;' x2);
 5740:         }
 5741:         $datatable .= '<label>'.
 5742:                       '<input type="checkbox" name="ltitools_add_fields" value="'.$field.'"'.$id.$onclick.' />'.
 5743:                       $lt{$field}.'</label>'.$spacer;
 5744:     }
 5745:     $datatable .= '</span>'.
 5746:                   '<div style="display:none;" id="ltitools_user_div_add">'.
 5747:                   '<span class="LC_nobreak"> : '.
 5748:                   '<select name="ltitools_userincdom_add">'.
 5749:                   '<option value="" selected="selected">'.&mt('Select').'</option>'.
 5750:                   '<option value="0">'.&mt('username').'</option>'.
 5751:                   '<option value="1">'.&mt('username:domain').'</option>'.
 5752:                   '</select></span></div></fieldset>';
 5753:     $datatable .= '<fieldset><legend>'.&mt('Role mapping').'</legend><table><tr>';
 5754:     foreach my $role (@courseroles) {
 5755:         my ($checked,$checkednone);
 5756:         $datatable .= '<td style="text-align: center">'.
 5757:                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 5758:                       '<select name="ltitools_add_roles_'.$role.'">'.
 5759:                       '<option value="" selected="selected">'.&mt('Select').'</option>';
 5760:         foreach my $ltirole (@ltiroles) {
 5761:             $datatable .= '<option value="'.$ltirole.'">'.$ltirole.'</option>';
 5762:         }
 5763:         $datatable .= '</select></td>';
 5764:     }
 5765:     $datatable .= '</tr></table></fieldset>'.
 5766:                   '<fieldset><legend>'.&mt('Configurable in course').'</legend><span class="LC_nobreak">';
 5767:     foreach my $item ('label','title','target','linktext','explanation','append') {
 5768:         $datatable .= '<label>'.
 5769:                       '<input type="checkbox" name="ltitools_courseconfig" value="'.$item.'" checked="checked" />'.
 5770:                       $lt{'crs'.$item}.'</label>'.('&nbsp;' x2)."\n";
 5771:     }
 5772:     $datatable .= '</span></fieldset>'.
 5773:                   '<fieldset><legend>'.&mt('Custom items sent on launch').'</legend>'.
 5774:                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 5775:                   '<tr><td><span class="LC_nobreak">'.
 5776:                   '<label><input type="checkbox" name="ltitools_add_custom" value="1" />'.
 5777:                   &mt('Add').'</label></span></td><td><input type="text" name="ltitools_add_custom_name" />'.
 5778:                   '</td><td><input type="text" name="ltitools_add_custom_value" /></td></tr>'.
 5779:                   '</table></fieldset>'."\n".
 5780:                   '</td>'."\n".
 5781:                   '</tr>'."\n";
 5782:     $itemcount ++;
 5783:     return $datatable;
 5784: }
 5785: 
 5786: sub ltitools_names {
 5787:     my %lt = &Apache::lonlocal::texthash(
 5788:                                           'title'          => 'Title',
 5789:                                           'version'        => 'Version',
 5790:                                           'msgtype'        => 'Message Type',
 5791:                                           'sigmethod'      => 'Signature Method',
 5792:                                           'url'            => 'URL',
 5793:                                           'key'            => 'Key',
 5794:                                           'lifetime'       => 'Nonce lifetime (s)',
 5795:                                           'secret'         => 'Secret',
 5796:                                           'icon'           => 'Icon',   
 5797:                                           'user'           => 'User',
 5798:                                           'fullname'       => 'Full Name',
 5799:                                           'firstname'      => 'First Name',
 5800:                                           'lastname'       => 'Last Name',
 5801:                                           'email'          => 'E-mail',
 5802:                                           'roles'          => 'Role',
 5803:                                           'window'         => 'Window',
 5804:                                           'tab'            => 'Tab',
 5805:                                           'iframe'         => 'iFrame',
 5806:                                           'height'         => 'Height',
 5807:                                           'width'          => 'Width',
 5808:                                           'linktext'       => 'Default Link Text',
 5809:                                           'explanation'    => 'Default Explanation',
 5810:                                           'passback'       => 'Tool can return grades:',
 5811:                                           'roster'         => 'Tool can retrieve roster:',
 5812:                                           'crstarget'      => 'Display target',
 5813:                                           'crslabel'       => 'Course label',
 5814:                                           'crstitle'       => 'Course title', 
 5815:                                           'crslinktext'    => 'Link Text',
 5816:                                           'crsexplanation' => 'Explanation',
 5817:                                           'crsappend'      => 'Provider URL',
 5818:                                         );
 5819:     return %lt;
 5820: }
 5821: 
 5822: sub print_proctoring {
 5823:     my ($dom,$settings,$rowtotal) = @_;
 5824:     my $itemcount = 1;
 5825:     my (%ordered,%providernames,%current,%currentdef);
 5826:     my $confname = $dom.'-domainconfig';
 5827:     my $switchserver = &check_switchserver($dom,$confname);
 5828:     if (ref($settings) eq 'HASH') {
 5829:         foreach my $item (keys(%{$settings})) {
 5830:             if (ref($settings->{$item}) eq 'HASH') {
 5831:                 my $num = $settings->{$item}{'order'};
 5832:                 $ordered{$num} = $item;
 5833:             }
 5834:         }
 5835:     } else {
 5836:         %ordered = (
 5837:                      1 => 'proctorio',
 5838:                      2 => 'examity',
 5839:                    );
 5840:     }
 5841:     %providernames = &proctoring_providernames();
 5842:     my $maxnum = scalar(keys(%ordered));
 5843:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
 5844:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
 5845:     if (ref($requref) eq 'HASH') {
 5846:         %requserfields = %{$requref};
 5847:     }
 5848:     if (ref($opturef) eq 'HASH') {
 5849:         %optuserfields = %{$opturef};
 5850:     }
 5851:     if (ref($defref) eq 'HASH') {
 5852:         %defaults = %{$defref};
 5853:     }
 5854:     if (ref($extref) eq 'HASH') {
 5855:         %extended = %{$extref};
 5856:     }
 5857:     if (ref($crsref) eq 'HASH') {
 5858:         %crsconf = %{$crsref};
 5859:     }
 5860:     if (ref($rolesref) eq 'ARRAY') {
 5861:         @courseroles = @{$rolesref};
 5862:     }
 5863:     if (ref($ltiref) eq 'ARRAY') {
 5864:         @ltiroles = @{$ltiref};
 5865:     }
 5866:     my $datatable;
 5867:     my $css_class;
 5868:     if (keys(%ordered)) {
 5869:         my @items = sort { $a <=> $b } keys(%ordered);
 5870:         for (my $i=0; $i<@items; $i++) {
 5871:             $css_class = $itemcount%2?' class="LC_odd_row"':'';
 5872:             my $provider = $ordered{$items[$i]};
 5873:             my $optionsty = 'none';
 5874:             my ($available,$version,$lifetime,$imgsrc,$userincdom,$showroles,
 5875:                 %checkedfields,%rolemaps,%inuse,%crsconfig,%current);
 5876:             if (ref($settings) eq 'HASH') {
 5877:                 if (ref($settings->{$provider}) eq 'HASH') {
 5878:                     %current = %{$settings->{$provider}};
 5879:                     if ($current{'available'}) {
 5880:                         $optionsty = 'block';
 5881:                         $available = 1;
 5882:                     }
 5883:                     if ($current{'lifetime'} =~ /^\d+$/) {
 5884:                         $lifetime = $current{'lifetime'};
 5885:                     }
 5886:                     if ($current{'version'} =~ /^\d+\.\d+$/) {
 5887:                         $version = $current{'version'};
 5888:                     }
 5889:                     if ($current{'image'} ne '') {
 5890:                         $imgsrc = '<img src="'.$current{'image'}.'" alt="'.&mt('Proctoring service icon').'" />';
 5891:                     }
 5892:                     if (ref($current{'fields'}) eq 'ARRAY') {
 5893:                         map { $checkedfields{$_} = 1; } @{$current{'fields'}};
 5894:                     }
 5895:                     $userincdom = $current{'incdom'};
 5896:                     if (ref($current{'roles'}) eq 'HASH') {
 5897:                         %rolemaps = %{$current{'roles'}};
 5898:                         $checkedfields{'roles'} = 1;
 5899:                     }
 5900:                     if (ref($current{'defaults'}) eq 'ARRAY') {
 5901:                         foreach my $val (@{$current{'defaults'}}) {
 5902:                             if (grep(/^\Q$val\E$/,@{$defaults{$provider}})) {
 5903:                                 $inuse{$val} = 1;
 5904:                             } else {
 5905:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5906:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5907:                                         if (grep(/^\Q$val\E$/,@{$extended{$provider}{$poss}})) {
 5908:                                             $inuse{$poss} = $val;
 5909:                                             last;
 5910:                                         }
 5911:                                     }
 5912:                                 }
 5913:                             }
 5914:                         }
 5915:                     } elsif (ref($current{'defaults'}) eq 'HASH') {
 5916:                         foreach my $key (keys(%{$current{'defaults'}})) {
 5917:                             my $currval = $current{'defaults'}{$key}; 
 5918:                             if (grep(/^\Q$key\E$/,@{$defaults{$provider}})) {
 5919:                                 $inuse{$key} = 1;
 5920:                             } else {
 5921:                                 my $match;
 5922:                                 foreach my $poss (keys(%{$extended{$provider}})) {
 5923:                                     if (ref($extended{$provider}{$poss}) eq 'ARRAY') {
 5924:                                         if (grep(/^\Q$key\E$/,@{$extended{$provider}{$poss}})) {
 5925:                                             $inuse{$poss} = $key;
 5926:                                             last;
 5927:                                         }
 5928:                                     } elsif (ref($extended{$provider}{$poss}) eq 'HASH') {
 5929:                                         foreach my $inner (sort(keys(%{$extended{$provider}{$poss}}))) {
 5930:                                             if (ref($extended{$provider}{$poss}{$inner}) eq 'ARRAY') {
 5931:                                                 if (grep(/^\Q$currval\E$/,@{$extended{$provider}{$poss}{$inner}})) {
 5932:                                                     $currentdef{$inner} = $currval;
 5933:                                                     $match = 1;
 5934:                                                     last;
 5935:                                                 }
 5936:                                             } elsif ($inner eq $key) {
 5937:                                                 $currentdef{$key} = $currval;
 5938:                                                 $match = 1;
 5939:                                                 last;
 5940:                                             }
 5941:                                         }
 5942:                                     }
 5943:                                     last if ($match);
 5944:                                 }
 5945:                             }
 5946:                         }
 5947:                     }
 5948:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
 5949:                         map { $crsconfig{$_} = 1; } @{$current{'crsconf'}};
 5950:                     }
 5951:                 }
 5952:             }
 5953:             my %lt = &proctoring_titles($provider);
 5954:             my %fieldtitles = &proctoring_fieldtitles($provider);
 5955:             my $onclickavailable = ' onclick="toggleProctoring(this.form,'."'$provider'".');"';
 5956:             my %checkedavailable = (
 5957:                                    yes => '',
 5958:                                    no  => ' checked="checked"',
 5959:                                  );
 5960:             if ($available) {
 5961:                 $checkedavailable{'yes'} = $checkedavailable{'no'};
 5962:                 $checkedavailable{'no'} = '';
 5963:             }
 5964:             my $chgstr = ' onchange="javascript:reorderProctoring(this.form,'."'proctoring_pos_".$provider."'".');"';
 5965:             $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 5966:                          .'<select name="proctoring_pos_'.$provider.'"'.$chgstr.'>';
 5967:             for (my $k=0; $k<$maxnum; $k++) {
 5968:                 my $vpos = $k+1;
 5969:                 my $selstr;
 5970:                 if ($k == $i) {
 5971:                     $selstr = ' selected="selected" ';
 5972:                 }
 5973:                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 5974:             }
 5975:             if ($version eq '') {
 5976:                 if ($provider eq 'proctorio') {
 5977:                     $version = '1.0';
 5978:                 } elsif ($provider eq 'examity') {
 5979:                     $version = '1.1';
 5980:                 }
 5981:             }
 5982:             if ($lifetime eq '') {
 5983:                 $lifetime = '300';
 5984:             }
 5985:             $datatable .=
 5986:                 '</select>'.('&nbsp;'x2).'<b>'.$providernames{$provider}.'</b></span><br />'.
 5987:                 '<span class="LC_nobreak">'.$lt{'avai'}.'&nbsp;'.
 5988:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="1"'.$onclickavailable.$checkedavailable{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 5989:                 '<label><input type="radio" name="proctoring_available_'.$provider.'" value="0"'.$onclickavailable.$checkedavailable{no}.' />'.&mt('No').'</label></span>'."\n".
 5990:                 '</td>'.
 5991:                 '<td colspan="2">'.
 5992:                 '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'base'}.'</legend>'.
 5993:                 '<span class="LC_nobreak">'.$lt{'version'}.':<select name="proctoring_'.$provider.'_version">'.
 5994:                 '<option value="'.$version.'" selected="selected">'.$version.'</option></select></span> '."\n".
 5995:                 ('&nbsp;'x2).
 5996:                 '<span class="LC_nobreak">'.$lt{'sigmethod'}.':<select name="proctoring_'.$provider.'_sigmethod">'.
 5997:                 '<option value="HMAC-SHA1" selected="selected">HMAC-SHA1</option>'.
 5998:                 '<option value="HMAC-SHA256">HMAC-SHA256</option></select></span>'.
 5999:                 ('&nbsp;'x2).
 6000:                 '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="5" name="proctoring_'.$provider.'_lifetime" value="'.$lifetime.'" /></span> '."\n".
 6001:                 '<br />'.
 6002:                 '<span class="LC_nobreak">'.$lt{'url'}.':<input type="text" size="40" name="proctoring_'.$provider.'_url" value="'.$current{'url'}.'" /></span> '."\n".
 6003:                 '<br />'.
 6004:                 '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="proctoring_'.$provider.'_key" value="'.$current{'key'}.'" /></span> '."\n".
 6005:                 ('&nbsp;'x2).
 6006:                 '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="proctoring_'.$provider.'_secret" value="'.$current{'secret'}.'" />'.
 6007:                 '<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";
 6008:             $datatable .= '<span class="LC_nobreak">'.$lt{'icon'}.':&nbsp;';
 6009:             if ($imgsrc) {
 6010:                 $datatable .= $imgsrc.
 6011:                               '<label><input type="checkbox" name="proctoring_image_del"'.
 6012:                               ' value="'.$provider.'" />'.&mt('Delete?').'</label></span> '.
 6013:                               '<span class="LC_nobreak">&nbsp;'.&mt('Replace:');
 6014:             }
 6015:             $datatable .= '&nbsp;';
 6016:             if ($switchserver) {
 6017:                 $datatable .= &mt('Upload to library server: [_1]',$switchserver);
 6018:             } else {
 6019:                 $datatable .= '<input type="file" name="proctoring_image_'.$provider.'" value="" />';
 6020:             }
 6021:             unless ($imgsrc) {
 6022:                 $datatable .= '<br />('.&mt('if larger than 21x21 pixels, image will be scaled').')';
 6023:             }
 6024:             $datatable .= '</fieldset>'."\n";
 6025:             if (ref($requserfields{$provider}) eq 'ARRAY') {
 6026:                 if (@{$requserfields{$provider}} > 0) {
 6027:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'requ'}.'</legend>';
 6028:                     foreach my $field (@{$requserfields{$provider}}) {
 6029:                         $datatable .= '<span class="LC_nobreak">'.
 6030:                                       '<label><input type="checkbox" name="proctoring_reqd_'.$provider.'" value="'.$field.'" checked="checked" disabled="disabled" />'.
 6031:                                       $lt{$field}.'</label>';
 6032:                         if ($field eq 'user') {
 6033:                             my $seluserdom = '';
 6034:                             my $unseluserdom = ' selected="selected"';
 6035:                             if ($userincdom) {
 6036:                                 $seluserdom = $unseluserdom;
 6037:                                 $unseluserdom = '';
 6038:                             }
 6039:                             $datatable .= ':&nbsp;'.
 6040:                                 '<select name="proctoring_userincdom_'.$provider.'">'.
 6041:                                 '<option value="0"'.$unseluserdom.'>'.$lt{'username'}.'</option>'.
 6042:                                 '<option value="1"'.$seluserdom.'>'.$lt{'uname:dom'}.'</option>'.
 6043:                                 '</select>&nbsp;';
 6044:                         } else {
 6045:                             $datatable .= '&nbsp;';
 6046:                             if ($field eq 'roles') {
 6047:                                 $showroles = 1; 
 6048:                             } 
 6049:                         }
 6050:                         $datatable .= '</span> ';
 6051:                     }
 6052:                 }
 6053:                 $datatable .= '</fieldset>'."\n";
 6054:             }
 6055:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
 6056:                 if (@{$optuserfields{$provider}} > 0) {
 6057:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'optu'}.'</legend>'; 
 6058:                     foreach my $field (@{$optuserfields{$provider}}) {
 6059:                         my $checked;
 6060:                         if ($checkedfields{$field}) {
 6061:                             $checked = ' checked="checked"';
 6062:                         }
 6063:                         $datatable .= '<span class="LC_nobreak">'.
 6064:                                       '<label><input type="checkbox" name="proctoring_optional_'.$provider.'" value="'.$field.'"'.$checked.' />'.$lt{$field}.'</label></span>&nbsp; ';
 6065:                     }
 6066:                     $datatable .= '</fieldset>'."\n";
 6067:                 }
 6068:             }
 6069:             if (ref($defaults{$provider}) eq 'ARRAY') {
 6070:                 if (@{$defaults{$provider}}) {
 6071:                     my (%options,@selectboxes);
 6072:                     if (ref($extended{$provider}) eq 'HASH') {
 6073:                         %options = %{$extended{$provider}};
 6074:                     }
 6075:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'"><legend>'.$lt{'defa'}.'</legend>';
 6076:                     my ($rem,$numinrow,$dropdowns);
 6077:                     if ($provider eq 'proctorio') { 
 6078:                         $datatable .= '<table>';
 6079:                         $numinrow = 4;
 6080:                     }
 6081:                     my $i = 0;
 6082:                     foreach my $field (@{$defaults{$provider}}) {
 6083:                         my $checked;
 6084:                         if ($inuse{$field}) {
 6085:                             $checked = ' checked="checked"';
 6086:                         }
 6087:                         if ($provider eq 'examity') {
 6088:                             if ($field eq 'display') {
 6089:                                 $datatable .= '<span class="LC_nobreak">'.&mt('Display target:');
 6090:                                 foreach my $option ('iframe','tab','window') {
 6091:                                     my $checkdisp;
 6092:                                     if ($currentdef{'target'} eq $option) {
 6093:                                         $checkdisp = ' checked="checked"';
 6094:                                     }
 6095:                                     $datatable .= '<label><input type="radio" name="proctoring_target_'.$provider.'" value="'.$option.'"'.$checkdisp.' />'.
 6096:                                     $fieldtitles{$option}.'</label>'.('&nbsp;'x2);
 6097:                                 }
 6098:                                 $datatable .= ('&nbsp;'x4);
 6099:                                 foreach my $dimen ('width','height') {
 6100:                                     $datatable .= '<label>'.$fieldtitles{$dimen}.'&nbsp;'.
 6101:                                                   '<input type="text" name="proctoring_'.$dimen.'_'.$provider.'" size="5" '.
 6102:                                                   'value="'.$currentdef{$dimen}.'" /></label>'.
 6103:                                                   ('&nbsp;'x2);
 6104:                                 }
 6105:                                 $datatable .= '</span><br />'.
 6106:                                               '<div class="LC_left_float">'.$fieldtitles{'linktext'}.'<br />'.
 6107:                                               '<input type="text" name="proctoring_linktext_'.$provider.'" '.
 6108:                                               'size="25" value="'.$currentdef{'linktext'}.'" /></div>'.
 6109:                                               '<div class="LC_left_float">'.$fieldtitles{'explanation'}.'<br />'.
 6110:                                               '<textarea name="proctoring_explanation_'.$provider.'" rows="5" cols="40">'.
 6111:                                               $currentdef{'explanation'}.
 6112:                                               '</textarea></div><div style=""></div><br />';
 6113:                             }
 6114:                         } else {
 6115:                             if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
 6116:                                 my ($output,$selnone);
 6117:                                 unless ($checked) {
 6118:                                     $selnone = ' selected="selected"';
 6119:                                 }
 6120:                                 $output .= '<span class="LC_nobreak">'.$fieldtitles{$field}.': '.
 6121:                                            '<select name="proctoring_defaults_'.$field.'_'.$provider.'">'.
 6122:                                            '<option value=""'.$selnone.'>'.&mt('Not in use').'</option>'; 
 6123:                                 foreach my $option (@{$options{$field}}) {
 6124:                                     my $sel; 
 6125:                                     if ($inuse{$field} eq $option) {
 6126:                                         $sel = ' selected="selected"';
 6127:                                     }
 6128:                                     $output .= '<option value="'.$option.'"'.$sel.'>'.$fieldtitles{$option}.'</option>';
 6129:                                 }
 6130:                                 $output .= '</select></span>';
 6131:                                 push(@selectboxes,$output);
 6132:                             } else {
 6133:                                 $rem = $i%($numinrow);
 6134:                                 if ($rem == 0) {
 6135:                                     if ($i > 0) {
 6136:                                         $datatable .= '</tr>';
 6137:                                     }
 6138:                                     $datatable .= '<tr>';
 6139:                                 }
 6140:                                 $datatable .= '<td class="LC_left_item">'.
 6141:                                               '<span class="LC_nobreak">'.
 6142:                                               '<label><input type="checkbox" name="proctoring_defaults_'.$provider.'" value="'.$field.'"'.$checked.' />'.
 6143:                                               $fieldtitles{$field}.'</label></span></td>';
 6144:                                 $i++;
 6145:                             }
 6146:                         }
 6147:                     }
 6148:                     if ($provider eq 'proctorio') {
 6149:                         if ($numinrow) {
 6150:                             $rem = $i%$numinrow;
 6151:                         }
 6152:                         my $colsleft = $numinrow - $rem;
 6153:                         if ($colsleft > 1) {
 6154:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6155:                         } else {
 6156:                             $datatable .= '<td class="LC_left_item">';
 6157:                         }
 6158:                         $datatable .= '&nbsp;'.
 6159:                                       '</td></tr></table>';
 6160:                         if (@selectboxes) {
 6161:                             $datatable .= '<hr /><table>';
 6162:                             $numinrow = 2;
 6163:                             for (my $i=0; $i<@selectboxes; $i++) {
 6164:                                 $rem = $i%($numinrow);
 6165:                                 if ($rem == 0) {
 6166:                                     if ($i > 0) {
 6167:                                         $datatable .= '</tr>';
 6168:                                     }
 6169:                                     $datatable .= '<tr>';
 6170:                                 }
 6171:                                 $datatable .= '<td class="LC_left_item">'.
 6172:                                               $selectboxes[$i].'</td>';
 6173:                             }
 6174:                             if ($numinrow) {
 6175:                                 $rem = $i%$numinrow;
 6176:                             }
 6177:                             $colsleft = $numinrow - $rem;
 6178:                             if ($colsleft > 1) {
 6179:                                 $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6180:                             } else {
 6181:                                 $datatable .= '<td class="LC_left_item">';
 6182:                             }
 6183:                             $datatable .= '&nbsp;'.
 6184:                                           '</td></tr></table>';
 6185:                         }
 6186:                     }
 6187:                     $datatable .= '</fieldset>';
 6188:                 }
 6189:                 if (ref($crsconf{$provider}) eq 'ARRAY') {
 6190:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6191:                                   '<legend>'.&mt('Configurable in course').'</legend>';
 6192:                     my ($rem,$numinrow);
 6193:                     if ($provider eq 'proctorio') {
 6194:                         $datatable .= '<table>';
 6195:                         $numinrow = 4;
 6196:                     }
 6197:                     my $i = 0;
 6198:                     foreach my $item (@{$crsconf{$provider}}) {
 6199:                         my $name;
 6200:                         if ($provider eq 'examity') {
 6201:                             $name = $lt{'crs'.$item};
 6202:                         } elsif ($provider eq 'proctorio') {
 6203:                             $name = $fieldtitles{$item};
 6204:                             $rem = $i%($numinrow);
 6205:                             if ($rem == 0) {
 6206:                                 if ($i > 0) {
 6207:                                     $datatable .= '</tr>';
 6208:                                 }
 6209:                                 $datatable .= '<tr>';
 6210:                             }
 6211:                             $datatable .= '<td class="LC_left_item>';
 6212:                         }
 6213:                         my $checked;
 6214:                         if ($crsconfig{$item}) {
 6215:                             $checked = ' checked="checked"';
 6216:                         }
 6217:                         $datatable .= '<span class="LC_nobreak"><label>'.
 6218:                                       '<input type="checkbox" name="proctoring_crsconf_'.$provider.'" value="'.$item.'"'.$checked.' />'.
 6219:                                       $name.'</label></span>';
 6220:                         if ($provider eq 'examity') {
 6221:                             $datatable .= '&nbsp; ';
 6222:                         }
 6223:                         $datatable .= "\n";
 6224:                         $i++;
 6225:                     }
 6226:                     if ($provider eq 'proctorio') {
 6227:                         if ($numinrow) {
 6228:                             $rem = $i%$numinrow;
 6229:                         }
 6230:                         my $colsleft = $numinrow - $rem;
 6231:                         if ($colsleft > 1) {
 6232:                             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
 6233:                         } else {
 6234:                             $datatable .= '<td class="LC_left_item">';
 6235:                         }
 6236:                         $datatable .= '&nbsp;'.
 6237:                                       '</td></tr></table>';
 6238:                     }
 6239:                     $datatable .= '</fieldset>';
 6240:                 }
 6241:                 if ($showroles) {
 6242:                     $datatable .= '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6243:                                   '<legend>'.&mt('Role mapping').'</legend><table><tr>';
 6244:                     foreach my $role (@courseroles) {
 6245:                         my ($selected,$selectnone);
 6246:                         if (!$rolemaps{$role}) {
 6247:                             $selectnone = ' selected="selected"';
 6248:                         }
 6249:                         $datatable .= '<td style="text-align: center">'.
 6250:                                       &Apache::lonnet::plaintext($role,'Course').'<br />'.
 6251:                                       '<select name="proctoring_roles_'.$role.'_'.$provider.'">'.
 6252:                                       '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 6253:                         foreach my $ltirole (@ltiroles) {
 6254:                             unless ($selectnone) {
 6255:                                 if ($rolemaps{$role} eq $ltirole) {
 6256:                                     $selected = ' selected="selected"';
 6257:                                 } else {
 6258:                                     $selected = '';
 6259:                                 }
 6260:                             }
 6261:                             $datatable .= '<option value="'.$ltirole.'"'.$selected.'>'.$ltirole.'</option>';
 6262:                         }
 6263:                         $datatable .= '</select></td>';
 6264:                     }
 6265:                     $datatable .= '</tr></table></fieldset>'.
 6266:                                   '<fieldset class="proctoring_'.$provider.'" style="display:'.$optionsty.'">'.
 6267:                                   '<legend>'.&mt('Custom items sent on launch').'</legend>'.
 6268:                                   '<table><tr><th>'.&mt('Action').'</th><th>'.&mt('Name').'</th><th>'.&mt('Value').'</th></tr>'.
 6269:                                   '<tr><td></td><td>lms</td>'.
 6270:                                   '<td><input type="text" name="proctoring_customval_lms_'.$provider.'"'.
 6271:                                   ' value="Loncapa" disabled="disabled"/></td></tr>';
 6272:                     if ((ref($settings) eq 'HASH') && (ref($settings->{$provider}) eq 'HASH') &&
 6273:                         (ref($settings->{$provider}->{'custom'}) eq 'HASH')) {
 6274:                         my %custom = %{$settings->{$provider}->{'custom'}};
 6275:                         if (keys(%custom) > 0) {
 6276:                             foreach my $key (sort(keys(%custom))) {
 6277:                                 next if ($key eq 'lms');
 6278:                                 $datatable .= '<tr><td><span class="LC_nobreak">'.
 6279:                                               '<label><input type="checkbox" name="proctoring_customdel_'.$provider.'" value="'.
 6280:                                               $key.'" />'.&mt('Delete').'</label></span></td><td>'.$key.'</td>'.
 6281:                                               '<td><input type="text" name="proctoring_customval_'.$key.'_'.$provider.'"'.
 6282:                                               ' value="'.$custom{$key}.'" /></td></tr>';
 6283:                             }
 6284:                         }
 6285:                     }
 6286:                     $datatable .= '<tr><td><span class="LC_nobreak">'.
 6287:                                   '<label><input type="checkbox" name="proctoring_customadd" value="'.$provider.'" />'.
 6288:                                   &mt('Add more').'</label></span></td><td><input type="text" name="proctoring_custom_name_'.$provider.'" />'.
 6289:                                   '</td><td><input type="text" name="proctoring_custom_value_'.$provider.'" /></td></tr>'.
 6290:                                   '</table></fieldset></td></tr>'."\n";
 6291:                 }
 6292:                 $datatable .= '</td></tr>';
 6293:             }
 6294:             $itemcount ++;
 6295:         }
 6296:     }
 6297:     return $datatable;
 6298: }
 6299: 
 6300: sub proctoring_data {
 6301:     my $requserfields = {
 6302:                       proctorio => ['user'],
 6303:                       examity   => ['roles','user'],
 6304:                      };
 6305:     my $optuserfields = {
 6306:                         proctorio => ['fullname'],
 6307:                         examity   => ['fullname','firstname','lastname','email'],
 6308:                      };
 6309:     my $defaults = {
 6310:                   proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6311:                                 'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6312:                                 'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6313:                                 'closetabs','onescreen','print','downloads','cache','rightclick',
 6314:                                 'reentry','calculator','whiteboard'],
 6315:                   examity   => ['display'],
 6316:                 };
 6317:     my $extended = { 
 6318:                   proctorio => {
 6319:                                  verifyid => ['verifyidauto','verifyidlive'],
 6320:                                  fullscreen => ['fullscreenlenient','fullscreenmoderate','fullscreensever'],
 6321:                                  tabslinks => ['notabs','linksonly'],
 6322:                                  reentry => ['noreentry','agentreentry'],
 6323:                                  calculator => ['calculatorbasic','calculatorsci'],
 6324:                                },
 6325:                   examity => {
 6326:                                display => {
 6327:                                            target      => ['iframe','tab','window'],
 6328:                                            width       => '',
 6329:                                            height      => '',
 6330:                                            linktext    => '',
 6331:                                            explanation => '',
 6332:                                           },
 6333:                              },
 6334:                 };
 6335:     my $crsconf = {
 6336:                  proctorio => ['recordvideo','recordaudio','recordscreen','recordwebtraffic',
 6337:                                'recordroomstart','verifyvideo','verifyaudio','verifydesktop',
 6338:                                'verifyid','verifysignature','fullscreen','clipboard','tabslinks',
 6339:                                'closetabs','onescreen','print','downloads','cache','rightclick',
 6340:                                'reentry','calculator','whiteboard'],
 6341:                  examity => ['label','title','target','linktext','explanation','append'],
 6342:                };
 6343:     my $courseroles = ['cc','in','ta','ep','st'];
 6344:     my $ltiroles = ['Instructor','ContentDeveloper','TeachingAssistant','Learner'];
 6345:     return ($requserfields,$optuserfields,$defaults,$extended,$crsconf,$courseroles,$ltiroles);
 6346: }
 6347: 
 6348: sub proctoring_titles {
 6349:     my ($item) = @_;
 6350:     my (%common_lt,%custom_lt);
 6351:     %common_lt = &Apache::lonlocal::texthash (
 6352:                      'avai'      => 'Available?',
 6353:                      'base'      => 'Basic Settings',
 6354:                      'requ'      => 'User data required to be sent on launch',
 6355:                      'optu'      => 'User data optionally sent on launch',
 6356:                      'udsl'      => 'User data sent on launch',
 6357:                      'defa'      => 'Defaults for items configurable in course',
 6358:                      'sigmethod' => 'Signature Method',
 6359:                      'key'       => 'Key',
 6360:                      'lifetime'  => 'Nonce lifetime (s)',
 6361:                      'secret'    => 'Secret',
 6362:                      'icon'      => 'Icon',
 6363:                      'fullname'  => 'Full Name',
 6364:                      'visible'   => 'Visible input',
 6365:                      'username'  => 'username',
 6366:                      'user'      => 'User',
 6367:                  );
 6368:     if ($item eq 'proctorio') {
 6369:         %custom_lt = &Apache::lonlocal::texthash (
 6370:                          'version'        => 'OAuth version',
 6371:                          'url'            => 'API URL',
 6372:                          'uname:dom'      => 'username-domain',
 6373:         );
 6374:     } elsif ($item eq 'examity') {
 6375:         %custom_lt = &Apache::lonlocal::texthash (
 6376:                          'version'        => 'LTI Version',
 6377:                          'url'            => 'URL',
 6378:                          'uname:dom'      => 'username:domain',
 6379:                          'msgtype'        => 'Message Type',
 6380:                          'firstname'      => 'First Name',
 6381:                          'lastname'       => 'Last Name',
 6382:                          'email'          => 'E-mail',
 6383:                          'roles'          => 'Role',
 6384:                          'crstarget'      => 'Display target',
 6385:                          'crslabel'       => 'Course label',
 6386:                          'crstitle'       => 'Course title', 
 6387:                          'crslinktext'    => 'Link Text',
 6388:                          'crsexplanation' => 'Explanation',
 6389:                          'crsappend'      => 'Provider URL',
 6390:         );
 6391:     }
 6392:     my %lt = (%common_lt,%custom_lt);
 6393:     return %lt;
 6394: }
 6395: 
 6396: sub proctoring_fieldtitles {
 6397:     my ($item) = @_;
 6398:     if ($item eq 'proctorio') {
 6399:         return &Apache::lonlocal::texthash (
 6400:                   'recordvideo' => 'Record video',
 6401:                   'recordaudio' => 'Record audio',
 6402:                   'recordscreen' => 'Record screen',
 6403:                   'recordwebtraffic' => 'Record web traffic',
 6404:                   'recordroomstart' => 'Record room scan',
 6405:                   'verifyvideo' => 'Verify webcam',
 6406:                   'verifyaudio' => 'Verify microphone',
 6407:                   'verifydesktop' => 'Verify desktop recording',
 6408:                   'verifyid' => 'Photo ID verification',
 6409:                   'verifysignature' => 'Require signature',
 6410:                   'fullscreen' => 'Fullscreen',
 6411:                   'clipboard' => 'Disable copy/paste',
 6412:                   'tabslinks' => 'New tabs/windows',
 6413:                   'closetabs' => 'Close other tabs',
 6414:                   'onescreen' => 'Limit to single screen',
 6415:                   'print' => 'Disable Printing',
 6416:                   'downloads' => 'Disable Downloads',
 6417:                   'cache' => 'Empty cache after exam',
 6418:                   'rightclick' => 'Disable right click',
 6419:                   'reentry' => 'Re-entry to exam',
 6420:                   'calculator' => 'Onscreen calculator',
 6421:                   'whiteboard' => 'Onscreen whiteboard',
 6422:                   'verifyidauto' => 'Automated verification',
 6423:                   'verifyidlive' => 'Live agent verification',
 6424:                   'fullscreenlenient' => 'Forced, but can navigate away for up to 30s',
 6425:                   'fullscreenmoderate' => 'Forced, but can navigate away for up to 15s',
 6426:                   'fullscreensever' => 'Forced, navigation away ends exam',
 6427:                   'notabs' => 'Disaallowed',
 6428:                   'linksonly' => 'Allowed from links in exam',
 6429:                   'noreentry' => 'Disallowed',
 6430:                   'agentreentry' => 'Agent required for re-entry',
 6431:                   'calculatorbasic' => 'Basic',
 6432:                   'calculatorsci' => 'Scientific',
 6433:         );
 6434:     } elsif ($item eq 'examity') {
 6435:         return &Apache::lonlocal::texthash (
 6436:                 'target'         => 'Display target',   
 6437:                 'window'         => 'Window',
 6438:                 'tab'            => 'Tab',
 6439:                 'iframe'         => 'iFrame',
 6440:                 'height'         => 'Height (pixels)',
 6441:                 'width'          => 'Width (pixels)',
 6442:                 'linktext'       => 'Default Link Text',
 6443:                 'explanation'    => 'Default Explanation',
 6444:                 'append'         => 'Provider URL',
 6445:         );
 6446:     }
 6447: }
 6448: 
 6449: sub proctoring_providernames {
 6450:     return (
 6451:              proctorio => 'Proctorio',
 6452:              examity   => 'Examity',
 6453:            );
 6454: }
 6455: 
 6456: sub print_lti {
 6457:     my ($position,$dom,$settings,$rowtotal) = @_;
 6458:     my $itemcount = 1;
 6459:     my ($datatable,$css_class);
 6460:     my (%rules,%encrypt,%privkeys,%linkprot);
 6461:     if (ref($settings) eq 'HASH') {
 6462:         if ($position eq 'top') {
 6463:             if (exists($settings->{'encrypt'})) {
 6464:                 if (ref($settings->{'encrypt'}) eq 'HASH') {
 6465:                     foreach my $key (keys(%{$settings->{'encrypt'}})) {
 6466:                         if ($key eq 'consumers') {
 6467:                             $encrypt{'ltisec_'.$key} = $settings->{'encrypt'}{$key};
 6468:                         } else {
 6469:                             $encrypt{'ltisec_'.$key.'linkprot'} = $settings->{'encrypt'}{$key};
 6470:                         }
 6471:                     }
 6472:                 }
 6473:             }
 6474:             if (exists($settings->{'private'})) {
 6475:                 if (ref($settings->{'private'}) eq 'HASH') {
 6476:                     if (ref($settings->{'private'}) eq 'HASH') {
 6477:                         if (ref($settings->{'private'}{'keys'}) eq 'ARRAY') {
 6478:                             map { $privkeys{$_} = 1; } (@{$settings->{'private'}{'keys'}});
 6479:                         }
 6480:                     }
 6481:                 }
 6482:             }
 6483:         } elsif ($position eq 'middle') {
 6484:             if (exists($settings->{'rules'})) {
 6485:                 if (ref($settings->{'rules'}) eq 'HASH') {
 6486:                     %rules = %{$settings->{'rules'}};
 6487:                 }
 6488:             }
 6489:         } elsif ($position eq 'lower') {
 6490:             if (exists($settings->{'linkprot'})) {
 6491:                 if (ref($settings->{'linkprot'}) eq 'HASH') {
 6492:                     %linkprot = %{$settings->{'linkprot'}};
 6493:                 }
 6494:             }
 6495:         } else {
 6496:             foreach my $key ('encrypt','private','rules','linkprot') {
 6497:                 if (exists($settings->{$key})) {
 6498:                     delete($settings->{$key});
 6499:                 }
 6500:             }
 6501:         }
 6502:     }
 6503:     if ($position eq 'top') {
 6504:         my @ids=&Apache::lonnet::current_machine_ids();
 6505:         my %servers = &Apache::lonnet::get_servers($dom,'library');
 6506:         my $primary = &Apache::lonnet::domain($dom,'primary');
 6507:         my ($extra,$numshown);
 6508:         foreach my $hostid (sort(keys(%servers))) {
 6509:             my ($showextra,$divsty,$switch);
 6510:             if ($hostid eq $primary) {
 6511:                 if (($encrypt{'ltisec_consumers'}) || ($encrypt{'ltisec_domlinkprot'})) {
 6512:                     $showextra = 1;
 6513:                 }
 6514:             }
 6515:             if ($encrypt{'ltisec_crslinkprot'}) {
 6516:                 $showextra = 1;
 6517:             }
 6518:             unless (grep(/^\Q$hostid\E$/,@ids)) {
 6519:                 $switch = 1;
 6520:             }
 6521:             if ($showextra) {
 6522:                 $numshown ++;
 6523:                 $divsty = 'display:inline-block'; 
 6524:             } else {
 6525:                 $divsty = 'display:none';
 6526:             } 
 6527:             $extra .= '<fieldset id="ltisec_info_'.$hostid.'" style="'.$divsty.'">'.
 6528:                       '<legend>'.$hostid.'</legend>';
 6529:             if ($switch) {
 6530:                 my $switchserver = '<a href="/adm/switchserver?otherserver='.$hostid.'&amp;role='.
 6531:                                    &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 6532:                                    '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 6533:                 if (exists($privkeys{$hostid})) {
 6534:                     $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" />'.
 6535:                               '<span class="LC_nobreak">'.
 6536:                               &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6537:                               '<span class="LC_nobreak">'.&mt('Change?').
 6538:                               '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6539:                               ('&nbsp;'x2).
 6540:                               '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6541:                               '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6542:                               '<span class="LC_nobreak"> - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6543:                               '</span></div>';
 6544:                 } else {
 6545:                     $extra .= '<span class="LC_nobreak">'.
 6546:                               &mt('Key required').' - '.&mt('submit from server ([_1]): [_2].',$hostid,$switchserver).
 6547:                               '</span>'."\n";
 6548:                 }
 6549:             } elsif (exists($privkeys{$hostid})) {
 6550:                 $extra .= '<div id="ltisec_divcurrprivkey_'.$hostid.'" style="display:inline-block" /><span class="LC_nobreak">'.
 6551:                           &mt('Encryption Key').': ['.&mt('not shown').'] '.('&nbsp;'x2).'</span></div>'.
 6552:                           '<span class="LC_nobreak">'.&mt('Change?').
 6553:                           '<label><input type="radio" value="0" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" checked="checked" />'.&mt('No').'</label>'.
 6554:                           ('&nbsp;'x2).
 6555:                           '<label><input type="radio" value="1" name="ltisec_changeprivkey_'.$hostid.'" onclick="javascript:togglePrivKey(this.form,'."'$hostid'".');" />'.&mt('Yes').
 6556:                           '</label>&nbsp;&nbsp;</span><div id="ltisec_divchgprivkey_'.$hostid.'" style="display:none" />'.
 6557:                           '<span class="LC_nobreak">'.&mt('New Key').':'.
 6558:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6559:                           '<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>'.
 6560:                           '</span></div>';
 6561:             } else {
 6562:                 $extra .= '<span class="LC_nobreak">'.&mt('Encryption Key').':'.
 6563:                           '<input type="password" size="20" name="ltisec_privkey_'.$hostid.'" value="" autocomplete="off" />'.
 6564:                           '<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>';
 6565:             }
 6566:             $extra .= '</fieldset>';
 6567:         }
 6568:         my %choices = &Apache::lonlocal::texthash (
 6569:                                                       ltisec_crslinkprot => 'Encrypt stored link protection secrets defined in courses',
 6570:                                                       ltisec_domlinkprot => 'Encrypt stored link protection secrets defined in domain',
 6571:                                                       ltisec_consumers   => 'Encrypt stored consumer secrets defined in domain',
 6572:                                                   );
 6573:         my @toggles = qw(ltisec_crslinkprot ltisec_domlinkprot ltisec_consumers);
 6574:         my %defaultchecked = (
 6575:                                'ltisec_crslinkprot' => 'off',
 6576:                                'ltisec_domlinkprot' => 'off',
 6577:                                'ltisec_consumers'   => 'off',
 6578:                              );
 6579:         my ($onclick,$itemcount);
 6580:         $onclick = 'javascript:toggleLTIEncKey(this.form);';
 6581:         ($datatable,$itemcount) = &radiobutton_prefs(\%encrypt,\@toggles,\%defaultchecked,
 6582:                                                      \%choices,$itemcount,$onclick,'','left','no');
 6583: 
 6584:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6585:         my $noprivkeysty = 'display:inline-block';
 6586:         if ($numshown) {
 6587:             $noprivkeysty = 'display:none'; 
 6588:         }
 6589:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.&mt('Encryption Key(s)').'</td>'.
 6590:                       '<td><div id="ltisec_noprivkey" style="'.$noprivkeysty.'" >'.
 6591:                       '<span class="LC_nobreak">'.&mt('Not in use').'</span></div>'.
 6592:                       $extra.
 6593:                       '</td></tr>';
 6594:         $itemcount ++;                
 6595:         $$rowtotal += $itemcount;
 6596:     } elsif ($position eq 'middle') {
 6597:         $datatable = &password_rules('secrets',\$itemcount,\%rules);
 6598:     } elsif ($position eq 'lower') {
 6599:         $datatable .= '<tr><td>Not set yet</td><td>To be done</td></tr>';
 6600:     } else {
 6601:         my $maxnum = 0;
 6602:         my %ordered;
 6603:         if (ref($settings) eq 'HASH') {
 6604:             foreach my $item (keys(%{$settings})) {
 6605:                 if (ref($settings->{$item}) eq 'HASH') {
 6606:                     my $num = $settings->{$item}{'order'};
 6607:                     if ($num eq '') {
 6608:                         $num = scalar(keys(%{$settings}));
 6609:                     }
 6610:                     $ordered{$num} = $item;
 6611:                 }
 6612:             }
 6613:         }
 6614:         $maxnum = scalar(keys(%ordered));
 6615:         my %lt = &lti_names();
 6616:         if (keys(%ordered)) {
 6617:             my @items = sort { $a <=> $b } keys(%ordered);
 6618:             for (my $i=0; $i<@items; $i++) {
 6619:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6620:                 my $item = $ordered{$items[$i]};
 6621:                 my ($key,$secret,$lifetime,$consumer,$requser,$crsinc,$current);
 6622:                 if (ref($settings->{$item}) eq 'HASH') {
 6623:                     $key = $settings->{$item}->{'key'};
 6624:                     $secret = $settings->{$item}->{'secret'};
 6625:                     $lifetime = $settings->{$item}->{'lifetime'};
 6626:                     $consumer = $settings->{$item}->{'consumer'};
 6627:                     $requser = $settings->{$item}->{'requser'};
 6628:                     $crsinc = $settings->{$item}->{'crsinc'};
 6629:                     $current = $settings->{$item};
 6630:                 }
 6631:                 my $onclickrequser = ' onclick="toggleLTI(this.form,'."'requser','$i'".');"';
 6632:                 my %checkedrequser = (
 6633:                                        yes => ' checked="checked"',
 6634:                                        no  => '',
 6635:                                      );
 6636:                 if (!$requser) {
 6637:                     $checkedrequser{'no'} = $checkedrequser{'yes'};
 6638:                     $checkedrequser{'yes'} = '';
 6639:                 }
 6640:                 my $onclickcrsinc = ' onclick="toggleLTI(this.form,'."'crsinc','$i'".');"';
 6641:                 my %checkedcrsinc = (
 6642:                                       yes => ' checked="checked"',
 6643:                                       no  => '',
 6644:                                     );
 6645:                 if (!$crsinc) {
 6646:                     $checkedcrsinc{'no'} = $checkedcrsinc{'yes'};
 6647:                     $checkedcrsinc{'yes'} = '';
 6648:                 }
 6649:                 my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_".$item."'".');"';
 6650:                 $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
 6651:                              .'<select name="lti_pos_'.$item.'"'.$chgstr.'>';
 6652:                 for (my $k=0; $k<=$maxnum; $k++) {
 6653:                     my $vpos = $k+1;
 6654:                     my $selstr;
 6655:                     if ($k == $i) {
 6656:                         $selstr = ' selected="selected" ';
 6657:                     }
 6658:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6659:                 }
 6660:                 $datatable .= '</select>'.('&nbsp;'x2).
 6661:                     '<label><input type="checkbox" name="lti_del" value="'.$item.'" />'.
 6662:                     &mt('Delete?').'</label></span></td>'.
 6663:                     '<td colspan="2">'.
 6664:                     '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6665:                     '<span class="LC_nobreak">'.$lt{'consumer'}.
 6666:                     ':<input type="text" size="15" name="lti_consumer_'.$i.'" value="'.$consumer.'" /></span> '.
 6667:                     ('&nbsp;'x2).
 6668:                     '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_'.$i.'">'.
 6669:                     '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '.
 6670:                     ('&nbsp;'x2).
 6671:                     '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" name="lti_lifetime_'.$i.'"'.
 6672:                     'value="'.$lifetime.'" size="3" /></span>'.
 6673:                     ('&nbsp;'x2).
 6674:                     '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6675:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="1"'.$onclickrequser.$checkedrequser{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6676:                     '<label><input type="radio" name="lti_requser_'.$i.'" value="0"'.$onclickrequser.$checkedrequser{no}.' />'.&mt('No').'</label></span>'."\n".
 6677:                     '<br /><br />'.
 6678:                     '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6679:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="1"'.$onclickcrsinc.$checkedcrsinc{yes}.' />'.&mt('Yes').'</label>&nbsp;'."\n".
 6680:                     '<label><input type="radio" name="lti_crsinc_'.$i.'" value="0"'.$onclickcrsinc.$checkedcrsinc{no}.' />'.&mt('No').'</label></span>'."\n".
 6681:                     ('&nbsp;'x4).
 6682:                     '<span class="LC_nobreak">'.$lt{'key'}.
 6683:                     ':<input type="text" size="25" name="lti_key_'.$i.'" value="'.$key.'" /></span> '.
 6684:                     ('&nbsp;'x2).
 6685:                     '<span class="LC_nobreak">'.$lt{'secret'}.':'.
 6686:                     '<input type="password" size="20" name="lti_secret_'.$i.'" value="'.$secret.'" />'.
 6687:                     '<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>'.
 6688:                     '<input type="hidden" name="lti_id_'.$i.'" value="'.$item.'" /></span>'.
 6689:                     '</fieldset>'.&lti_options($i,$current,$itemcount,%lt).'</td></tr>';
 6690:                 $itemcount ++;
 6691:             }
 6692:         }
 6693:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 6694:         my $chgstr = ' onchange="javascript:reorderLTI(this.form,'."'lti_pos_add'".');"';
 6695:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'."\n".
 6696:                       '<input type="hidden" name="lti_maxnum" value="'.$maxnum.'" />'."\n".
 6697:                       '<select name="lti_pos_add"'.$chgstr.'>';
 6698:         for (my $k=0; $k<$maxnum+1; $k++) {
 6699:             my $vpos = $k+1;
 6700:             my $selstr;
 6701:             if ($k == $maxnum) {
 6702:                 $selstr = ' selected="selected" ';
 6703:             }
 6704:             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
 6705:         }
 6706:         $datatable .= '</select>&nbsp;'."\n".
 6707:                       '<input type="checkbox" name="lti_add" value="1" />'.&mt('Add').'</span></td>'."\n".
 6708:                       '<td colspan="2">'.
 6709:                       '<fieldset><legend>'.&mt('Required settings').'</legend>'.
 6710:                       '<span class="LC_nobreak">'.$lt{'consumer'}.
 6711:                       ':<input type="text" size="15" name="lti_consumer_add" value="" /></span> '."\n".
 6712:                       ('&nbsp;'x2).
 6713:                       '<span class="LC_nobreak">'.$lt{'version'}.':<select name="lti_version_add">'.
 6714:                       '<option value="LTI-1p0" selected="selected">1.1</option></select></span> '."\n".
 6715:                       ('&nbsp;'x2).
 6716:                       '<span class="LC_nobreak">'.$lt{'lifetime'}.':<input type="text" size="3" name="lti_lifetime_add" value="300" /></span> '."\n".
 6717:                       ('&nbsp;'x2).
 6718:                       '<span class="LC_nobreak">'.$lt{'requser'}.':'.
 6719:                       '<label><input type="radio" name="lti_requser_add" value="1" onclick="toggleLTI(this.form,'."'requser','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6720:                       '<label><input type="radio" name="lti_requser_add" value="0" onclick="toggleLTI(this.form,'."'requser','add'".');" />'.&mt('No').'</label></span>'."\n".
 6721:                       '<br /><br />'.
 6722:                       '<span class="LC_nobreak">'.$lt{'crsinc'}.':'.
 6723:                       '<label><input type="radio" name="lti_crsinc_add" value="1" onclick="toggleLTI(this.form,'."'crsinc','add'".');" checked="checked" />'.&mt('Yes').'</label>&nbsp;'."\n".
 6724:                       '<label><input type="radio" name="lti_crsinc_add" value="0" onclick="toggleLTI(this.form,'."'crsinc','add'".');" />'.&mt('No').'</label></span>'."\n".
 6725:                       ('&nbsp;'x4).
 6726:                       '<span class="LC_nobreak">'.$lt{'key'}.':<input type="text" size="25" name="lti_key_add" value="" /></span> '."\n".
 6727:                       ('&nbsp;'x2).
 6728:                       '<span class="LC_nobreak">'.$lt{'secret'}.':<input type="password" size="20" name="lti_secret_add" value="" />'.
 6729:                       '<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".
 6730:                       '</fieldset>'.&lti_options('add',undef,$itemcount,%lt).
 6731:                       '</td>'."\n".
 6732:                       '</tr>'."\n";
 6733:         $itemcount ++;
 6734:     }
 6735:     $$rowtotal += $itemcount;
 6736:     return $datatable;
 6737: }
 6738: 
 6739: sub lti_names {
 6740:     my %lt = &Apache::lonlocal::texthash(
 6741:                                           'version'   => 'LTI Version',
 6742:                                           'url'       => 'URL',
 6743:                                           'key'       => 'Key',
 6744:                                           'lifetime'  => 'Nonce lifetime (s)',
 6745:                                           'consumer'  => 'Consumer',
 6746:                                           'secret'    => 'Secret',
 6747:                                           'requser'   => "User's identity sent",
 6748:                                           'crsinc'    => "Course's identity sent",
 6749:                                           'email'     => 'Email address',
 6750:                                           'sourcedid' => 'User ID',
 6751:                                           'other'     => 'Other',
 6752:                                           'passback'  => 'Can return grades to Consumer:',
 6753:                                           'roster'    => 'Can retrieve roster from Consumer:',
 6754:                                           'topmenu'   => 'Display LON-CAPA page header',
 6755:                                           'inlinemenu'=> 'Display LON-CAPA inline menu',
 6756:                                         );
 6757:     return %lt;
 6758: }
 6759: 
 6760: sub lti_options {
 6761:     my ($num,$current,$itemcount,%lt) = @_;
 6762:     my (%checked,%rolemaps,$crssecsrc,$userfield,$cidfield,$callback);
 6763:     $checked{'mapuser'}{'sourcedid'} = ' checked="checked"';
 6764:     $checked{'mapcrs'}{'course_offering_sourcedid'} = ' checked="checked"';
 6765:     $checked{'storecrs'}{'Y'} = ' checked="checked"';
 6766:     $checked{'makecrs'}{'N'} = ' checked="checked"';
 6767:     $checked{'mapcrstype'} = {};
 6768:     $checked{'makeuser'} = {};
 6769:     $checked{'selfenroll'} = {};
 6770:     $checked{'crssec'} = {};
 6771:     $checked{'crssecsrc'} = {};
 6772:     $checked{'lcauth'} = {};
 6773:     $checked{'menuitem'} = {};
 6774:     if ($num eq 'add') {
 6775:         $checked{'lcauth'}{'lti'} = ' checked="checked"';
 6776:     }
 6777:     my $userfieldsty = 'none';
 6778:     my $crsfieldsty = 'none';
 6779:     my $crssecfieldsty = 'none';
 6780:     my $secsrcfieldsty = 'none';
 6781:     my $callbacksty = 'none';
 6782:     my $passbacksty = 'none';
 6783:     my $optionsty = 'block';
 6784:     my $crssty = 'block';
 6785:     my $lcauthparm;
 6786:     my $lcauthparmstyle = 'display:none';
 6787:     my $lcauthparmtext;
 6788:     my $menusty;
 6789:     my $numinrow = 4;
 6790:     my %menutitles = &ltimenu_titles();
 6791: 
 6792:     if (ref($current) eq 'HASH') {
 6793:         if (!$current->{'requser'}) {
 6794:             $optionsty = 'none';
 6795:             $crssty = 'none';
 6796:         } elsif (!$current->{'crsinc'}) {
 6797:             $crssty = 'none';
 6798:         }
 6799:         if (($current->{'mapuser'} ne '') && ($current->{'mapuser'} ne 'lis_person_sourcedid')) {
 6800:             $checked{'mapuser'}{'sourcedid'} = '';
 6801:             if ($current->{'mapuser'} eq 'lis_person_contact_email_primary') {
 6802:                 $checked{'mapuser'}{'email'} = ' checked="checked"'; 
 6803:             } else {
 6804:                 $checked{'mapuser'}{'other'} = ' checked="checked"';
 6805:                 $userfield = $current->{'mapuser'};
 6806:                 $userfieldsty = 'inline-block';
 6807:             }
 6808:         }
 6809:         if (($current->{'mapcrs'} ne '') && ($current->{'mapcrs'} ne 'course_offering_sourcedid')) {
 6810:             $checked{'mapcrs'}{'course_offering_sourcedid'} = '';
 6811:             if ($current->{'mapcrs'} eq 'context_id') {
 6812:                 $checked{'mapcrs'}{'context_id'} = ' checked="checked"'; 
 6813:             } else {
 6814:                 $checked{'mapcrs'}{'other'} = ' checked="checked"';
 6815:                 $cidfield = $current->{'mapcrs'};
 6816:                 $crsfieldsty = 'inline-block';
 6817:             }
 6818:         }
 6819:         if (ref($current->{'mapcrstype'}) eq 'ARRAY') {
 6820:             foreach my $type (@{$current->{'mapcrstype'}}) {
 6821:                 $checked{'mapcrstype'}{$type} = ' checked="checked"';
 6822:             }
 6823:         }
 6824:         if (!$current->{'storecrs'}) {
 6825:             $checked{'storecrs'}{'N'} = $checked{'storecrs'}{'Y'};
 6826:             $checked{'storecrs'}{'Y'} = '';
 6827:         }
 6828:         if ($current->{'makecrs'}) {
 6829:             $checked{'makecrs'}{'Y'} = '  checked="checked"';
 6830:         }
 6831:         if (ref($current->{'makeuser'}) eq 'ARRAY') {
 6832:             foreach my $role (@{$current->{'makeuser'}}) {
 6833:                 $checked{'makeuser'}{$role} = ' checked="checked"';
 6834:             }
 6835:         }
 6836:         if ($current->{'lcauth'} =~ /^(internal|localauth|krb4|krb5|lti)$/) {
 6837:             $checked{'lcauth'}{$1} = ' checked="checked"';
 6838:             unless (($current->{'lcauth'} eq 'lti') || ($current->{'lcauth'} eq 'internal')) {
 6839:                 $lcauthparm = $current->{'lcauthparm'};
 6840:                 $lcauthparmstyle = 'display:table-row'; 
 6841:                 if ($current->{'lcauth'} eq 'localauth') {
 6842:                     $lcauthparmtext = &mt('Local auth argument');
 6843:                 } else {
 6844:                     $lcauthparmtext = &mt('Kerberos domain');
 6845:                 }
 6846:             }
 6847:         }
 6848:         if (ref($current->{'selfenroll'}) eq 'ARRAY') {
 6849:             foreach my $role (@{$current->{'selfenroll'}}) {
 6850:                 $checked{'selfenroll'}{$role} = ' checked="checked"';
 6851:             }
 6852:         }
 6853:         if (ref($current->{'maproles'}) eq 'HASH') {
 6854:             %rolemaps = %{$current->{'maproles'}};
 6855:         }
 6856:         if ($current->{'section'} ne '') {
 6857:             $checked{'crssec'}{'Y'} = '  checked="checked"'; 
 6858:             $crssecfieldsty = 'inline-block';
 6859:             if ($current->{'section'} eq 'course_section_sourcedid') {
 6860:                 $checked{'crssecsrc'}{'sourcedid'} = ' checked="checked"';
 6861:             } else {
 6862:                 $checked{'crssecsrc'}{'other'} = ' checked="checked"';
 6863:                 $crssecsrc = $current->{'section'};
 6864:                 $secsrcfieldsty = 'inline-block';
 6865:             }
 6866:         } else {
 6867:             $checked{'crssec'}{'N'} = ' checked="checked"';
 6868:         }
 6869:         if ($current->{'callback'} ne '') {
 6870:             $callback = $current->{'callback'};
 6871:             $checked{'callback'}{'Y'} = ' checked="checked"';
 6872:             $callbacksty = 'inline-block';
 6873:         } else {
 6874:             $checked{'callback'}{'N'} = ' checked="checked"';
 6875:         }
 6876:         if ($current->{'topmenu'}) {
 6877:             $checked{'topmenu'}{'Y'} = ' checked="checked"';
 6878:         } else {
 6879:             $checked{'topmenu'}{'N'} = ' checked="checked"';
 6880:         }
 6881:         if ($current->{'inlinemenu'}) {
 6882:             $checked{'inlinemenu'}{'Y'} = ' checked="checked"';
 6883:         } else {
 6884:             $checked{'inlinemenu'}{'N'} = ' checked="checked"';
 6885:         }
 6886:         if (($current->{'topmenu'}) || ($current->{'inlinemenu'})) {
 6887:             $menusty = 'inline-block';
 6888:             if (ref($current->{'lcmenu'}) eq 'ARRAY') {
 6889:                 foreach my $item (@{$current->{'lcmenu'}}) {
 6890:                     if (exists($menutitles{$item})) {
 6891:                         $checked{'menuitem'}{$item} = ' checked="checked"';
 6892:                     }
 6893:                 }
 6894:             }
 6895:         } else {
 6896:             $menusty = 'none';
 6897:         }
 6898:     } else {
 6899:         $checked{'makecrs'}{'N'} = ' checked="checked"';
 6900:         $checked{'crssec'}{'N'} = ' checked="checked"';
 6901:         $checked{'callback'}{'N'} = ' checked="checked"';
 6902:         $checked{'topmenu'}{'N'} = ' checked="checked"';
 6903:         $checked{'inlinemenu'}{'Y'} = ' checked="checked"'; 
 6904:         $checked{'menuitem'}{'grades'} = ' checked="checked"';
 6905:         $menusty = 'inline-block'; 
 6906:     }
 6907:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
 6908:     my %coursetypetitles = &Apache::lonlocal::texthash (
 6909:                                official   => 'Official',
 6910:                                unofficial => 'Unofficial',
 6911:                                community  => 'Community',
 6912:                                textbook   => 'Textbook',
 6913:                                placement  => 'Placement Test',
 6914:                                lti        => 'LTI Provider',
 6915:     );
 6916:     my @authtypes = ('internal','krb4','krb5','localauth');
 6917:     my %shortauth = (
 6918:                      internal => 'int',
 6919:                      krb4 => 'krb4',
 6920:                      krb5 => 'krb5',
 6921:                      localauth  => 'loc'
 6922:                     );
 6923:     my %authnames = &authtype_names();
 6924:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
 6925:     my @lticourseroles = qw(Learner Instructor TeachingAssistant Mentor);
 6926:     my @courseroles = ('cc','in','ta','ep','st');
 6927:     my $onclickuser = ' onclick="toggleLTI(this.form,'."'user','$num'".');"';
 6928:     my $onclickcrs = ' onclick="toggleLTI(this.form,'."'crs','$num'".');"';
 6929:     my $onclicksec = ' onclick="toggleLTI(this.form,'."'sec','$num'".');"';
 6930:     my $onclickcallback = ' onclick="toggleLTI(this.form,'."'callback','$num'".');"';
 6931:     my $onclicksecsrc = ' onclick="toggleLTI(this.form,'."'secsrc','$num'".')"';
 6932:     my $onclicklcauth = ' onclick="toggleLTI(this.form,'."'lcauth','$num'".')"';
 6933:     my $onclickmenu = ' onclick="toggleLTI(this.form,'."'lcmenu','$num'".');"';
 6934:     my $output = '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Logout options').'</legend>'.
 6935:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Callback to logout LON-CAPA on log out from Consumer').':&nbsp;'.
 6936:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="0"'.
 6937:                  $checked{'callback'}{'N'}.$onclickcallback.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6938:                  '<label><input type="radio" name="lti_callback_'.$num.'" value="1"'.
 6939:                  $checked{'callback'}{'Y'}.$onclickcallback.' />'.&mt('Yes').'</label></span></div>'.
 6940:                  '<div class="LC_floatleft" style="display:'.$callbacksty.';" id="lti_callbackfield_'.$num.'">'.
 6941:                  '<span class="LC_nobreak">'.&mt('Parameter').': '.
 6942:                  '<input type="text" name="lti_callbackparam_'.$num.'" value="'.$callback.'" /></span>'.
 6943:                  '</div><div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>'.
 6944:                  '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Mapping users').'</legend>'.
 6945:                  '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('LON-CAPA username').':&nbsp;';
 6946:     foreach my $option ('sourcedid','email','other') {
 6947:         $output .= '<label><input type="radio" name="lti_mapuser_'.$num.'" value="'.$option.'"'.
 6948:                    $checked{'mapuser'}{$option}.$onclickuser.' />'.$lt{$option}.'</label>'.
 6949:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 6950:     }
 6951:     $output .= '</span></div>'.
 6952:                '<div class="LC_floatleft" style="display:'.$userfieldsty.';" id="lti_userfield_'.$num.'">'.
 6953:                '<input type="text" name="lti_customuser_'.$num.'" '.
 6954:                'value="'.$userfield.'" /></div></fieldset>'.
 6955:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('Roles which may create user accounts').'</legend>';
 6956:     foreach my $ltirole (@ltiroles) {
 6957:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_makeuser_'.$num.'" value="'.$ltirole.'"'.
 6958:                    $checked{'makeuser'}{$ltirole}.' />'.$ltirole.'</label>&nbsp;</span> ';     
 6959:     }
 6960:     $output .= '</fieldset>'.
 6961:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.&mt('New user accounts created for LTI users').'</legend>'.
 6962:                '<table>'.
 6963:                &modifiable_userdata_row('lti','instdata_'.$num,$current,$numinrow,$itemcount).
 6964:                '</table>'.
 6965:                '<table class="LC_nested"><tr><td class="LC_left_item">LON-CAPA Authentication</td>'.
 6966:                '<td class="LC_left_item">';
 6967:     foreach my $auth ('lti',@authtypes) {
 6968:         my $authtext;
 6969:         if ($auth eq 'lti') {
 6970:             $authtext = &mt('None');
 6971:         } else {
 6972:             $authtext = $authnames{$shortauth{$auth}};
 6973:         }
 6974:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="lti_lcauth_'.$num.
 6975:                    '" value="'.$auth.'"'.$checked{'lcauth'}{$auth}.$onclicklcauth.' />'.
 6976:                    $authtext.'</label></span> &nbsp;';
 6977:     }
 6978:     $output .= '</td></tr>'.
 6979:                '<tr id="lti_lcauth_parmrow_'.$num.'" style="'.$lcauthparmstyle.'">'.
 6980:                '<td class="LC_right_item" colspan="2"><span class="LC_nobreak">'.
 6981:                '<span id="lti_lcauth_parmtext_'.$num.'">'.$lcauthparmtext.'</span>'.
 6982:                '<input type="text" name="lti_lcauthparm_'.$num.'" value="" /></span></td></tr>'.
 6983:                '</table></fieldset>'.
 6984:                '<fieldset class="ltioption_usr_'.$num.'" style="display:'.$optionsty.'"><legend>'.
 6985:                &mt('LON-CAPA menu items (Course Coordinator can override)').'</legend>'.
 6986:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'topmenu'}.':&nbsp;'.
 6987:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="0"'.
 6988:                $checked{'topmenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6989:                '<label><input type="radio" name="lti_topmenu_'.$num.'" value="1"'.
 6990:                $checked{'topmenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>'.
 6991:                '<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6992:                '<div class="LC_floatleft"><span class="LC_nobreak">'.$lt{'inlinemenu'}.':&nbsp;'.
 6993:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="0"'.
 6994:                $checked{'inlinemenu'}{'N'}.$onclickmenu.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 6995:                '<label><input type="radio" name="lti_inlinemenu_'.$num.'" value="1"'.
 6996:                $checked{'inlinemenu'}{'Y'}.$onclickmenu.' />'.&mt('Yes').'</label></span></div>';
 6997:      $output .='<div style="padding:0;clear:both;margin:0;border:0"></div>'.
 6998:                '<div class="LC_floatleft" style="display:'.$menusty.';" id="lti_menufield_'.$num.'">'.
 6999:                '<span class="LC_nobreak">'.&mt('Menu items').':&nbsp;';
 7000:     foreach my $type ('fullname','coursetitle','role','logout','grades') {
 7001:         $output .= '<label><input type="checkbox" name="lti_menuitem_'.$num.'" value="'.$type.'"'.
 7002:                    $checked{'menuitem'}{$type}.' />'.$menutitles{$type}.'</label>'.
 7003:                    ('&nbsp;'x2);
 7004:     }
 7005:     $output .= '</span></div></fieldset>'.
 7006:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping courses').'</legend>'.
 7007:                '<div class="LC_floatleft"><span class="LC_nobreak">'.
 7008:                &mt('Unique course identifier').':&nbsp;';
 7009:     foreach my $option ('course_offering_sourcedid','context_id','other') {
 7010:         $output .= '<label><input type="radio" name="lti_mapcrs_'.$num.'" value="'.$option.'"'.
 7011:                    $checked{'mapcrs'}{$option}.$onclickcrs.' />'.$option.'</label>'.
 7012:                    ($option eq 'other' ? '' : ('&nbsp;'x2) );
 7013:     }
 7014:     $output .= '</span></div><div class="LC_floatleft" style="display:'.$crsfieldsty.';" id="lti_crsfield_'.$num.'">'.
 7015:                '<input type="text" name="lti_mapcrsfield_'.$num.'" value="'.$cidfield.'" />'.
 7016:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>'.
 7017:                '<span class="LC_nobreak">'.&mt('LON-CAPA course type(s)').':&nbsp;';
 7018:     foreach my $type (@coursetypes) {
 7019:         $output .= '<label><input type="checkbox" name="lti_mapcrstype_'.$num.'" value="'.$type.'"'.
 7020:                    $checked{'mapcrstype'}{$type}.' />'.$coursetypetitles{$type}.'</label>'.
 7021:                    ('&nbsp;'x2);
 7022:     }
 7023:     $output .= '</span><br /><br />'.
 7024:                '<span class="LC_nobreak">'.&mt('Store mapping of course identifier to LON-CAPA CourseID').':&nbsp;'.
 7025:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="0"'.
 7026:                $checked{'storecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7027:                '<label><input type="radio" name="lti_storecrs_'.$num.'" value="1"'.
 7028:                $checked{'storecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7029:                '</fieldset>'.
 7030:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Mapping course roles').'</legend><table><tr>';
 7031:     foreach my $ltirole (@lticourseroles) {
 7032:         my ($selected,$selectnone);
 7033:         if ($rolemaps{$ltirole} eq '') {
 7034:             $selectnone = ' selected="selected"';
 7035:         }
 7036:         $output .= '<td style="text-align: center">'.$ltirole.'<br />'.
 7037:                    '<select name="lti_maprole_'.$ltirole.'_'.$num.'">'.
 7038:                    '<option value=""'.$selectnone.'>'.&mt('Select').'</option>';
 7039:         foreach my $role (@courseroles) {
 7040:             unless ($selectnone) {
 7041:                 if ($rolemaps{$ltirole} eq $role) {
 7042:                     $selected = ' selected="selected"';
 7043:                 } else {
 7044:                     $selected = '';
 7045:                 }
 7046:             }
 7047:             $output .= '<option value="'.$role.'"'.$selected.'>'.
 7048:                        &Apache::lonnet::plaintext($role,'Course').
 7049:                        '</option>';
 7050:         }
 7051:         $output .= '</select></td>';
 7052:     }
 7053:     $output .= '</tr></table></fieldset>'.
 7054:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Creating courses').'</legend>'.
 7055:                '<span class="LC_nobreak">'.&mt('Course created (if absent) on Instructor access').':&nbsp;'.
 7056:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="0"'.
 7057:                $checked{'makecrs'}{'N'}.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7058:                '<label><input type="radio" name="lti_makecrs_'.$num.'" value="1"'.
 7059:                $checked{'makecrs'}{'Y'}.' />'.&mt('Yes').'</label></span>'.
 7060:                '</fieldset>'.
 7061:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Roles which may self-enroll').'</legend>';
 7062:     foreach my $lticrsrole (@lticourseroles) {
 7063:         $output .= '<span class="LC_nobreak"><label><input type="checkbox" name="lti_selfenroll_'.$num.'" value="'.$lticrsrole.'"'.
 7064:                    $checked{'selfenroll'}{$lticrsrole}.' />'.$lticrsrole.'</label>&nbsp;</span> ';
 7065:     }
 7066:     $output .= '</fieldset>'.
 7067:                '<fieldset class="ltioption_crs_'.$num.'" style="display:'.$crssty.'"><legend>'.&mt('Course options').'</legend>'.
 7068:                '<div class="LC_floatleft"><span class="LC_nobreak">'.&mt('Assign users to sections').':&nbsp;'.
 7069:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="0"'.
 7070:                $checked{'crssec'}{'N'}.$onclicksec.' />'.&mt('No').'</label>'.('&nbsp;'x2).
 7071:                '<label><input type="radio" name="lti_crssec_'.$num.'" value="1"'.
 7072:                $checked{'crssec'}{'Y'}.$onclicksec.' />'.&mt('Yes').'</label></span></div>'.
 7073:                '<div class="LC_floatleft" style="display:'.$crssecfieldsty.';" id="lti_crssecfield_'.$num.'">'.
 7074:                '<span class="LC_nobreak">'.&mt('From').':<label>'.
 7075:                '<input type="radio" name="lti_crssecsrc_'.$num.'" value="course_section_sourcedid"'.
 7076:                $checked{'crssecsrc'}{'sourcedid'}.$onclicksecsrc.' />'.
 7077:                &mt('Standard field').'</label>'.('&nbsp;'x2).
 7078:                '<label><input type="radio" name="lti_crssecsrc_'.$num.'" value="other"'.
 7079:                $checked{'crssecsrc'}{'other'}.$onclicksecsrc.' />'.&mt('Other').
 7080:                '</label></span></div><div class="LC_floatleft" style="display:'.$secsrcfieldsty.';" id="lti_secsrcfield_'.$num.'">'.
 7081:                '<input type="text" name="lti_customsection_'.$num.'" value="'.$crssecsrc.'" />'.
 7082:                '</div><div style="padding:0;clear:both;margin:0;border:0"></div>';
 7083:     my ($pb1p1chk,$pb1p0chk,$onclickpb);
 7084:     foreach my $extra ('roster','passback') {
 7085:         my $checkedon = '';
 7086:         my $checkedoff = ' checked="checked"';
 7087:         if ($extra eq 'passback') {
 7088:             $pb1p1chk = ' checked="checked"';
 7089:             $pb1p0chk = '';
 7090:             $onclickpb = ' onclick="toggleLTI(this.form,'."'passback','$num'".');"'; 
 7091:         } else {
 7092:             $onclickpb = ''; 
 7093:         }
 7094:         if (ref($current) eq 'HASH') {
 7095:             if (($current->{$extra})) {
 7096:                 $checkedon = $checkedoff;
 7097:                 $checkedoff = '';
 7098:                 if ($extra eq 'passback') {
 7099:                     $passbacksty = 'inline-block';
 7100:                 }
 7101:                 if ($current->{'passbackformat'} eq '1.0') {
 7102:                     $pb1p0chk =  ' checked="checked"';
 7103:                     $pb1p1chk = '';
 7104:                 }
 7105:             }
 7106:         }
 7107:         $output .= $lt{$extra}.'&nbsp;'.
 7108:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="0"'.$checkedoff.$onclickpb.' />'.
 7109:                    &mt('No').'</label>'.('&nbsp;'x2).
 7110:                    '<label><input type="radio" name="lti_'.$extra.'_'.$num.'" value="1"'.$checkedon.$onclickpb.' />'.
 7111:                    &mt('Yes').'</label><br />';
 7112:     }
 7113:     $output .= '<div class="LC_floatleft" style="display:'.$passbacksty.';" id="lti_passback_'.$num.'">'.
 7114:                '<span class="LC_nobreak">'.&mt('Grade format').
 7115:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.1"'.$pb1p1chk.' />'.
 7116:                &mt('Outcomes Service (1.1)').'</label>'.('&nbsp;'x2).
 7117:                '<label><input type="radio" name="lti_passbackformat_'.$num.'" value="1.0"'.$pb1p0chk.'/>'.
 7118:                &mt('Outcomes Extension (1.0)').'</label></span></div>'.
 7119:                '<div style="padding:0;clear:both;margin:0;border:0"></div></fieldset>';
 7120:     $output .= '</span></div></fieldset>';
 7121: #        '<fieldset><legend>'.&mt('Assigning author roles').'</legend>';
 7122: #
 7123: #    $output .= '</fieldset>'.
 7124: #        '<fieldset><legend>'.&mt('Assigning domain roles').'</legend>';
 7125:     return $output;
 7126: }
 7127: 
 7128: sub ltimenu_titles {
 7129:     return &Apache::lonlocal::texthash(
 7130:                                         fullname    => 'Full name',
 7131:                                         coursetitle => 'Course title',
 7132:                                         role        => 'Role',
 7133:                                         logout      => 'Logout',
 7134:                                         grades      => 'Grades',
 7135:     );
 7136: }
 7137: 
 7138: sub check_switchserver {
 7139:     my ($home) = @_;
 7140:     my $switchserver;
 7141:     if ($home ne '') {
 7142:         my $allowed;
 7143:         my @ids=&Apache::lonnet::current_machine_ids();
 7144:         foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 7145:         if (!$allowed) {
 7146:             $switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role='.
 7147:                           &HTML::Entities::encode($env{'request.role'},'\'<>"&').
 7148:                           '&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
 7149:         }
 7150:     }
 7151:     return $switchserver;
 7152: }
 7153: 
 7154: sub print_coursedefaults {
 7155:     my ($position,$dom,$settings,$rowtotal) = @_;
 7156:     my ($css_class,$datatable,%checkedon,%checkedoff,%defaultchecked,@toggles);
 7157:     my $itemcount = 1;
 7158:     my %choices =  &Apache::lonlocal::texthash (
 7159:         canuse_pdfforms      => 'Course/Community users can create/upload PDF forms',
 7160:         uploadquota          => 'Default quota for files uploaded directly to course/community using Course Editor (MB)',
 7161:         anonsurvey_threshold => 'Responder count needed before showing submissions for anonymous surveys',
 7162:         coursecredits        => 'Credits can be specified for courses',
 7163:         uselcmath            => 'Math preview uses LON-CAPA previewer (javascript) in place of DragMath (Java)',
 7164:         usejsme              => 'Molecule editor uses JSME (HTML5) in place of JME (Java)',
 7165:         inline_chem          => 'Use inline previewer for chemical reaction response in place of pop-up',
 7166:         texengine            => 'Default method to display mathematics',
 7167:         postsubmit           => 'Disable submit button/keypress following student submission',
 7168:         canclone             => "People who may clone a course (besides course's owner and coordinators)",
 7169:         mysqltables          => 'Lifetime (s) of "Temporary" MySQL tables (student performance data) on homeserver',
 7170:         ltiauth              => 'Student username in LTI launch of deep-linked URL can be accepted without re-authentication',
 7171:     );
 7172:     my %staticdefaults = (
 7173:                            anonsurvey_threshold => 10,
 7174:                            uploadquota          => 500,
 7175:                            postsubmit           => 60,
 7176:                            mysqltables          => 172800,
 7177:                          );
 7178:     if ($position eq 'top') {
 7179:         %defaultchecked = (
 7180:                             'canuse_pdfforms' => 'off',
 7181:                             'uselcmath'       => 'on',
 7182:                             'usejsme'         => 'on',
 7183:                             'inline_chem'     => 'on',
 7184:                             'canclone'        => 'none',
 7185:                           );
 7186:         @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem');
 7187:         my $deftex = $Apache::lonnet::deftex;
 7188:         if (ref($settings) eq 'HASH') {
 7189:             if ($settings->{'texengine'}) {
 7190:                 if ($settings->{'texengine'} =~ /^(MathJax|mimetex|tth)$/) {
 7191:                     $deftex = $settings->{'texengine'};
 7192:                 }
 7193:             }
 7194:         }
 7195:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7196:         my $mathdisp = '<tr'.$css_class.'><td style="vertical-align: top">'.
 7197:                        '<span class="LC_nobreak">'.$choices{'texengine'}.
 7198:                        '</span></td><td class="LC_right_item">'.
 7199:                        '<select name="texengine">'."\n";
 7200:         my %texoptions = (
 7201:                             MathJax  => 'MathJax',
 7202:                             mimetex  => &mt('Convert to Images'),
 7203:                             tth      => &mt('TeX to HTML'),
 7204:                          );
 7205:         foreach my $renderer ('MathJax','mimetex','tth') {
 7206:             my $selected = '';
 7207:             if ($renderer eq $deftex) {
 7208:                 $selected = ' selected="selected"';
 7209:             }
 7210:             $mathdisp .= '<option value="'.$renderer.'"'.$selected.'>'.$texoptions{$renderer}.'</option>'."\n";
 7211:         }
 7212:         $mathdisp .= '</select></td></tr>'."\n";
 7213:         $itemcount ++;
 7214:         ($datatable,$itemcount) = &radiobutton_prefs($settings,\@toggles,\%defaultchecked,
 7215:                                                      \%choices,$itemcount);
 7216:         $datatable = $mathdisp.$datatable;
 7217:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7218:         $datatable .=
 7219:             '<tr'.$css_class.'><td style="vertical-align: top">'.
 7220:             '<span class="LC_nobreak">'.$choices{'canclone'}.
 7221:             '</span></td><td class="LC_left_item">';
 7222:         my $currcanclone = 'none';
 7223:         my $onclick;
 7224:         my @cloneoptions = ('none','domain');
 7225:         my %clonetitles = &Apache::lonlocal::texthash (
 7226:                              none     => 'No additional course requesters',
 7227:                              domain   => "Any course requester in course's domain",
 7228:                              instcode => 'Course requests for official courses ...',
 7229:                           );
 7230:         my (%codedefaults,@code_order,@posscodes);
 7231:         if (&Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
 7232:                                                     \@code_order) eq 'ok') {
 7233:             if (@code_order > 0) {
 7234:                 push(@cloneoptions,'instcode');
 7235:                 $onclick = ' onclick="toggleDisplay(this.form,'."'cloneinstcode'".');"';
 7236:             }
 7237:         }
 7238:         if (ref($settings) eq 'HASH') {
 7239:             if ($settings->{'canclone'}) {
 7240:                 if (ref($settings->{'canclone'}) eq 'HASH') {
 7241:                     if (ref($settings->{'canclone'}{'instcode'}) eq 'ARRAY') {
 7242:                         if (@code_order > 0) {
 7243:                             $currcanclone = 'instcode';
 7244:                             @posscodes = @{$settings->{'canclone'}{'instcode'}};
 7245:                         }
 7246:                     }
 7247:                 } elsif ($settings->{'canclone'} eq 'domain') {
 7248:                     $currcanclone = $settings->{'canclone'};
 7249:                 }
 7250:             }
 7251:         }
 7252:         foreach my $option (@cloneoptions) {
 7253:             my ($checked,$additional);
 7254:             if ($currcanclone eq $option) {
 7255:                 $checked = ' checked="checked"';
 7256:             }
 7257:             if ($option eq 'instcode') {
 7258:                 if (@code_order) {
 7259:                     my $show = 'none';
 7260:                     if ($checked) {
 7261:                         $show = 'block';
 7262:                     }
 7263:                     $additional = '<div id="cloneinstcode" style="display:'.$show.';" />'.
 7264:                                   &mt('Institutional codes for new and cloned course have identical:').
 7265:                                   '<br />';
 7266:                     foreach my $item (@code_order) {
 7267:                         my $codechk;
 7268:                         if ($checked) {
 7269:                             if (grep(/^\Q$item\E$/,@posscodes)) {
 7270:                                 $codechk = ' checked="checked"';
 7271:                             }
 7272:                         }
 7273:                         $additional .= '<label>'.
 7274:                                        '<input type="checkbox" name="clonecode" value="'.$item.'"'.$codechk.' />'.
 7275:                                        $item.'</label>';
 7276:                     }
 7277:                     $additional .= ('&nbsp;'x2).'('.&mt('check as many as needed').')</div>';
 7278:                 }
 7279:             }
 7280:             $datatable .=
 7281:                 '<span class="LC_nobreak"><label><input type="radio" name="canclone"'.$checked.
 7282:                 ' value="'.$option.'"'.$onclick.' />'.$clonetitles{$option}.
 7283:                 '</label>&nbsp;'.$additional.'</span><br />';
 7284:         }
 7285:         $datatable .= '</td>'.
 7286:                       '</tr>';
 7287:         $itemcount ++;
 7288:     } else {
 7289:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7290:         my ($currdefresponder,%defcredits,%curruploadquota,%deftimeout,%currmysql);
 7291:         my $currusecredits = 0;
 7292:         my $postsubmitclient = 1;
 7293:         my $ltiauth = 0;
 7294:         my @types = ('official','unofficial','community','textbook','placement');
 7295:         if (ref($settings) eq 'HASH') {
 7296:             if ($settings->{'ltiauth'}) {
 7297:                 $ltiauth = 1;
 7298:             }
 7299:             $currdefresponder = $settings->{'anonsurvey_threshold'};
 7300:             if (ref($settings->{'uploadquota'}) eq 'HASH') {
 7301:                 foreach my $type (keys(%{$settings->{'uploadquota'}})) {
 7302:                     $curruploadquota{$type} = $settings->{'uploadquota'}{$type};
 7303:                 }
 7304:             }
 7305:             if (ref($settings->{'coursecredits'}) eq 'HASH') {
 7306:                 foreach my $type (@types) {
 7307:                     next if ($type eq 'community');
 7308:                     $defcredits{$type} = $settings->{'coursecredits'}->{$type};
 7309:                     if ($defcredits{$type} ne '') {
 7310:                         $currusecredits = 1;
 7311:                     }
 7312:                 }
 7313:             }
 7314:             if (ref($settings->{'postsubmit'}) eq 'HASH') {
 7315:                 if ($settings->{'postsubmit'}->{'client'} eq 'off') {
 7316:                     $postsubmitclient = 0;
 7317:                     foreach my $type (@types) {
 7318:                         $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7319:                     }
 7320:                 } else {
 7321:                     foreach my $type (@types) {
 7322:                         if (ref($settings->{'postsubmit'}->{'timeout'}) eq 'HASH') {
 7323:                             if ($settings->{'postsubmit'}->{'timeout'}->{$type} =~ /^\d+$/) {
 7324:                                 $deftimeout{$type} = $settings->{'postsubmit'}->{'timeout'}->{$type};
 7325:                             } else {
 7326:                                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7327:                             }
 7328:                         } else {
 7329:                             $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7330:                         }
 7331:                     }
 7332:                 }
 7333:             } else {
 7334:                 foreach my $type (@types) {
 7335:                     $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7336:                 }
 7337:             }
 7338:             if (ref($settings->{'mysqltables'}) eq 'HASH') {
 7339:                 foreach my $type (keys(%{$settings->{'mysqltables'}})) {
 7340:                     $currmysql{$type} = $settings->{'mysqltables'}{$type};
 7341:                 }
 7342:             } else {
 7343:                 foreach my $type (@types) {
 7344:                     $currmysql{$type} = $staticdefaults{'mysqltables'};
 7345:                 }
 7346:             }
 7347:         } else {
 7348:             foreach my $type (@types) {
 7349:                 $deftimeout{$type} = $staticdefaults{'postsubmit'};
 7350:             }
 7351:         }
 7352:         if (!$currdefresponder) {
 7353:             $currdefresponder = $staticdefaults{'anonsurvey_threshold'};
 7354:         } elsif ($currdefresponder < 1) {
 7355:             $currdefresponder = 1;
 7356:         }
 7357:         foreach my $type (@types) {
 7358:             if ($curruploadquota{$type} eq '') {
 7359:                 $curruploadquota{$type} = $staticdefaults{'uploadquota'};
 7360:             }
 7361:         }
 7362:         $datatable .=
 7363:                 '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7364:                 $choices{'anonsurvey_threshold'}.
 7365:                 '</span></td>'.
 7366:                 '<td class="LC_right_item"><span class="LC_nobreak">'.
 7367:                 '<input type="text" name="anonsurvey_threshold"'.
 7368:                 ' value="'.$currdefresponder.'" size="5" /></span>'.
 7369:                 '</td></tr>'."\n";
 7370:         $itemcount ++;
 7371:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7372:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7373:                       $choices{'uploadquota'}.
 7374:                       '</span></td>'.
 7375:                       '<td style="text-align: right" class="LC_right_item">'.
 7376:                       '<table><tr>';
 7377:         foreach my $type (@types) {
 7378:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7379:                            '<input type="text" name="uploadquota_'.$type.'"'.
 7380:                            ' value="'.$curruploadquota{$type}.'" size="5" /></td>';
 7381:         }
 7382:         $datatable .= '</tr></table></td></tr>'."\n";
 7383:         $itemcount ++;
 7384:         my $onclick = "toggleDisplay(this.form,'credits');";
 7385:         my $display = 'none';
 7386:         if ($currusecredits) {
 7387:             $display = 'block';
 7388:         }
 7389:         my $additional = '<div id="credits" style="display: '.$display.'">'.
 7390:                          '<i>'.&mt('Default credits').'</i><br /><table><tr>';
 7391:         foreach my $type (@types) {
 7392:             next if ($type eq 'community');
 7393:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7394:                            '<input type="text" name="'.$type.'_credits"'.
 7395:                            ' value="'.$defcredits{$type}.'" size="3" /></td>';
 7396:         }
 7397:         $additional .= '</tr></table></div>'."\n";
 7398:         %defaultchecked = ('coursecredits' => 'off');
 7399:         @toggles = ('coursecredits');
 7400:         my $current = {
 7401:                         'coursecredits' => $currusecredits,
 7402:                       };
 7403:         (my $table,$itemcount) =
 7404:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7405:                                \%choices,$itemcount,$onclick,$additional,'left');
 7406:         $datatable .= $table;
 7407:         $onclick = "toggleDisplay(this.form,'studentsubmission');";
 7408:         my $display = 'none';
 7409:         if ($postsubmitclient) {
 7410:             $display = 'block';
 7411:         }
 7412:         $additional = '<div id="studentsubmission" style="display: '.$display.'">'.
 7413:                       &mt('Number of seconds submit is disabled').'<br />'.
 7414:                       '<i>'.&mt('Enter 0 to remain disabled until page reload.').'</i><br />'.
 7415:                       '<table><tr>';
 7416:         foreach my $type (@types) {
 7417:             $additional .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7418:                            '<input type="text" name="'.$type.'_timeout" value="'.
 7419:                            $deftimeout{$type}.'" size="5" /></td>';
 7420:         }
 7421:         $additional .= '</tr></table></div>'."\n";
 7422:         %defaultchecked = ('postsubmit' => 'on');
 7423:         @toggles = ('postsubmit');
 7424:         $current = {
 7425:                        'postsubmit' => $postsubmitclient,
 7426:                    };
 7427:         ($table,$itemcount) =
 7428:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7429:                                \%choices,$itemcount,$onclick,$additional,'left');
 7430:         $datatable .= $table;
 7431:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7432:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7433:                       $choices{'mysqltables'}.
 7434:                       '</span></td>'.
 7435:                       '<td style="text-align: right" class="LC_right_item">'.
 7436:                       '<table><tr>';
 7437:         foreach my $type (@types) {
 7438:             $datatable .= '<td style="text-align: center">'.&mt($type).'<br />'.
 7439:                            '<input type="text" name="mysqltables_'.$type.'"'.
 7440:                            ' value="'.$currmysql{$type}.'" size="8" /></td>';
 7441:         }
 7442:         $datatable .= '</tr></table></td></tr>'."\n";
 7443:         $itemcount ++;
 7444:         %defaultchecked = ('ltiauth' => 'off');
 7445:         @toggles = ('ltiauth');
 7446:         $current = {
 7447:                        'ltiauth' => $ltiauth,
 7448:                    };
 7449:         ($table,$itemcount) =
 7450:             &radiobutton_prefs($current,\@toggles,\%defaultchecked,
 7451:                                \%choices,$itemcount,undef,undef,'left');
 7452:         $datatable .= $table;
 7453:         $itemcount ++;
 7454:     }
 7455:     $$rowtotal += $itemcount;
 7456:     return $datatable;
 7457: }
 7458: 
 7459: sub print_selfenrollment {
 7460:     my ($position,$dom,$settings,$rowtotal) = @_;
 7461:     my ($css_class,$datatable);
 7462:     my $itemcount = 1;
 7463:     my @types = ('official','unofficial','community','textbook','placement');
 7464:     if (($position eq 'top') || ($position eq 'middle')) {
 7465:         my ($rowsref,$titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
 7466:         my %descs = &Apache::lonuserutils::selfenroll_default_descs();
 7467:         my @rows;
 7468:         my $key;
 7469:         if ($position eq 'top') {
 7470:             $key = 'admin'; 
 7471:             if (ref($rowsref) eq 'ARRAY') {
 7472:                 @rows = @{$rowsref};
 7473:             }
 7474:         } elsif ($position eq 'middle') {
 7475:             $key = 'default';
 7476:             @rows = ('types','registered','approval','limit');
 7477:         }
 7478:         foreach my $row (@rows) {
 7479:             if (defined($titlesref->{$row})) {
 7480:                 $itemcount ++;
 7481:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7482:                 $datatable .= '<tr'.$css_class.'>'.
 7483:                               '<td>'.$titlesref->{$row}.'</td>'.
 7484:                               '<td class="LC_left_item">'.
 7485:                               '<table><tr>';
 7486:                 my (%current,%currentcap);
 7487:                 if (ref($settings) eq 'HASH') {
 7488:                     if (ref($settings->{$key}) eq 'HASH') {
 7489:                         foreach my $type (@types) {
 7490:                             if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7491:                                 $current{$type} = $settings->{$key}->{$type}->{$row};
 7492:                             }
 7493:                             if (($row eq 'limit') && ($key eq 'default')) {
 7494:                                 if (ref($settings->{$key}->{$type}) eq 'HASH') {
 7495:                                     $currentcap{$type} = $settings->{$key}->{$type}->{'cap'};
 7496:                                 }
 7497:                             }
 7498:                         }
 7499:                     }
 7500:                 }
 7501:                 my %roles = (
 7502:                              '0' => &Apache::lonnet::plaintext('dc'),
 7503:                             ); 
 7504:             
 7505:                 foreach my $type (@types) {
 7506:                     unless (($row eq 'registered') && ($key eq 'default')) {
 7507:                         $datatable .= '<th>'.&mt($type).'</th>';
 7508:                     }
 7509:                 }
 7510:                 unless (($row eq 'registered') && ($key eq 'default')) {
 7511:                     $datatable .= '</tr><tr>';
 7512:                 }
 7513:                 foreach my $type (@types) {
 7514:                     if ($type eq 'community') {
 7515:                         $roles{'1'} = &mt('Community personnel');
 7516:                     } else {
 7517:                         $roles{'1'} = &mt('Course personnel');
 7518:                     }
 7519:                     $datatable .= '<td style="vertical-align: top">';
 7520:                     if ($position eq 'top') {
 7521:                         my %checked;
 7522:                         if ($current{$type} eq '0') {
 7523:                             $checked{'0'} = ' checked="checked"';
 7524:                         } else {
 7525:                             $checked{'1'} = ' checked="checked"';
 7526:                         }
 7527:                         foreach my $role ('1','0') {
 7528:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7529:                                           '<input type="radio" name="selfenrolladmin_'.$row.'_'.$type.'" '.
 7530:                                           'value="'.$role.'"'.$checked{$role}.' />'.
 7531:                                           $roles{$role}.'</label></span> ';
 7532:                         }
 7533:                     } else {
 7534:                         if ($row eq 'types') {
 7535:                             my %checked;
 7536:                             if ($current{$type} =~ /^(all|dom)$/) {
 7537:                                 $checked{$1} = ' checked="checked"';
 7538:                             } else {
 7539:                                 $checked{''} = ' checked="checked"';
 7540:                             }
 7541:                             foreach my $val ('','dom','all') {
 7542:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7543:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7544:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7545:                             }
 7546:                         } elsif ($row eq 'registered') {
 7547:                             my %checked;
 7548:                             if ($current{$type} eq '1') {
 7549:                                 $checked{'1'} = ' checked="checked"';
 7550:                             } else {
 7551:                                 $checked{'0'} = ' checked="checked"';
 7552:                             }
 7553:                             foreach my $val ('0','1') {
 7554:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7555:                                               '<input type ="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7556:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7557:                             }
 7558:                         } elsif ($row eq 'approval') {
 7559:                             my %checked;
 7560:                             if ($current{$type} =~ /^([12])$/) {
 7561:                                 $checked{$1} = ' checked="checked"';
 7562:                             } else {
 7563:                                 $checked{'0'} = ' checked="checked"';
 7564:                             }
 7565:                             for my $val (0..2) {
 7566:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7567:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7568:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7569:                             }
 7570:                         } elsif ($row eq 'limit') {
 7571:                             my %checked;
 7572:                             if ($current{$type} =~ /^(allstudents|selfenrolled)$/) {
 7573:                                 $checked{$1} = ' checked="checked"';
 7574:                             } else {
 7575:                                 $checked{'none'} = ' checked="checked"';
 7576:                             }
 7577:                             my $cap;
 7578:                             if ($currentcap{$type} =~ /^\d+$/) {
 7579:                                 $cap = $currentcap{$type};
 7580:                             }
 7581:                             foreach my $val ('none','allstudents','selfenrolled') {
 7582:                                 $datatable .= '<span class="LC_nobreak"><label>'.
 7583:                                               '<input type="radio" name="selfenrolldefault_'.$row.'_'.$type.'" '.
 7584:                                               'value="'.$val.'"'.$checked{$val}.' />'.$descs{$row}{$val}.'</label></span> ';
 7585:                             }
 7586:                             $datatable .= '<br />'.
 7587:                                           '<span class="LC_nobreak">'.&mt('Maximum allowed: ').
 7588:                                           '<input type="text" name="selfenrolldefault_cap_'.$type.'" size = "5" value="'.$cap.'" />'.
 7589:                                           '</span>'; 
 7590:                         }
 7591:                     }
 7592:                     $datatable .= '</td>';
 7593:                 }
 7594:                 $datatable .= '</tr>';
 7595:             }
 7596:             $datatable .= '</table></td></tr>';
 7597:         }
 7598:     } elsif ($position eq 'bottom') {
 7599:         $datatable .= &print_validation_rows('selfenroll',$dom,$settings,\$itemcount);
 7600:     }
 7601:     $$rowtotal += $itemcount;
 7602:     return $datatable;
 7603: }
 7604: 
 7605: sub print_validation_rows {
 7606:     my ($caller,$dom,$settings,$rowtotal) = @_;
 7607:     my ($itemsref,$namesref,$fieldsref);
 7608:     if ($caller eq 'selfenroll') { 
 7609:         ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
 7610:     } elsif ($caller eq 'requestcourses') {
 7611:         ($itemsref,$namesref,$fieldsref) = &Apache::loncoursequeueadmin::requestcourses_validation_types();
 7612:     }
 7613:     my %currvalidation;
 7614:     if (ref($settings) eq 'HASH') {
 7615:         if (ref($settings->{'validation'}) eq 'HASH') {
 7616:             %currvalidation = %{$settings->{'validation'}};
 7617:         }
 7618:     }
 7619:     my $datatable;
 7620:     my $itemcount = 0;
 7621:     foreach my $item (@{$itemsref}) {
 7622:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7623:         $datatable .= '<tr'.$css_class.'><td><span class="LC_nobreak">'.
 7624:                       $namesref->{$item}.
 7625:                       '</span></td>'.
 7626:                       '<td class="LC_left_item">';
 7627:         if (($item eq 'url') || ($item eq 'button')) {
 7628:             $datatable .= '<span class="LC_nobreak">'.
 7629:                           '<input type="text" name="'.$caller.'_validation_'.$item.'"'.
 7630:                           ' value="'.$currvalidation{$item}.'" size="50" /></span>';
 7631:         } elsif ($item eq 'fields') {
 7632:             my @currfields;
 7633:             if (ref($currvalidation{$item}) eq 'ARRAY') {
 7634:                 @currfields = @{$currvalidation{$item}};
 7635:             }
 7636:             foreach my $field (@{$fieldsref}) {
 7637:                 my $check = '';
 7638:                 if (grep(/^\Q$field\E$/,@currfields)) {
 7639:                     $check = ' checked="checked"';
 7640:                 }
 7641:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7642:                               '<input type="checkbox" name="'.$caller.'_validation_fields"'.
 7643:                               ' value="'.$field.'"'.$check.' />'.$field.
 7644:                               '</label></span> ';
 7645:             }
 7646:         } elsif ($item eq 'markup') {
 7647:             $datatable .= '<textarea name="'.$caller.'_validation_markup" cols="50" rows="5">'.
 7648:                            $currvalidation{$item}.
 7649:                               '</textarea>';
 7650:         }
 7651:         $datatable .= '</td></tr>'."\n";
 7652:         if (ref($rowtotal)) {
 7653:             $itemcount ++;
 7654:         }
 7655:     }
 7656:     if ($caller eq 'requestcourses') {
 7657:         my %currhash;
 7658:         if (ref($settings) eq 'HASH') {
 7659:             if (ref($settings->{'validation'}) eq 'HASH') {
 7660:                 if ($settings->{'validation'}{'dc'} ne '') {
 7661:                     $currhash{$settings->{'validation'}{'dc'}} = 1;
 7662:                 }
 7663:             }
 7664:         }
 7665:         my $numinrow = 2;
 7666:         my ($numdc,$dctable,$rows) = &active_dc_picker($dom,$numinrow,'radio',
 7667:                                                        'validationdc',%currhash);
 7668:         my $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 7669:         $datatable .= '<tr'.$css_class.'><td>';
 7670:         if ($numdc > 1) {
 7671:             $datatable .= &mt('Course creation processed as: (choose Dom. Coord.)');
 7672:         } else {
 7673:             $datatable .=  &mt('Course creation processed as: ');
 7674:         }
 7675:         $datatable .= '</td><td class="LC_left_item">'.$dctable.'</td></tr>';
 7676:         $itemcount ++;
 7677:     }
 7678:     if (ref($rowtotal)) {
 7679:         $$rowtotal += $itemcount;
 7680:     }
 7681:     return $datatable;
 7682: }
 7683: 
 7684: sub print_privacy {
 7685:     my ($position,$dom,$settings,$rowtotal) = @_;
 7686:     my ($datatable,$css_class,$numinrow,@items,%names,$othertitle,$usertypes,$types);
 7687:     my $itemcount = 0;
 7688:     unless ($position eq 'top') {
 7689:         @items = ('domain','author','course','community');
 7690:         %names = &Apache::lonlocal::texthash (
 7691:                      domain => 'Assigned domain role(s)',
 7692:                      author => 'Assigned co-author role(s)',
 7693:                      course => 'Assigned course role(s)',
 7694:                      community => 'Assigned community role',
 7695:                  );
 7696:         $numinrow = 4;
 7697:         ($othertitle,$usertypes,$types) =
 7698:             &Apache::loncommon::sorted_inst_types($dom);
 7699:     }
 7700:     if (($position eq 'top') || ($position eq 'middle')) {
 7701:         my (%by_ip,%by_location,@intdoms,@instdoms);
 7702:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 7703:         if ($position eq 'top') {
 7704:             my %curr;
 7705:             my @options = ('none','user','domain','auto');
 7706:             my %titles = &Apache::lonlocal::texthash (
 7707:                 none   => 'Not allowed',
 7708:                 user   => 'User authorizes',
 7709:                 domain => 'DC authorizes',
 7710:                 auto   => 'Unrestricted',
 7711:                 instdom => 'Other domain shares institution/provider',
 7712:                 extdom => 'Other domain has different institution/provider',
 7713:             );
 7714:             my %names = &Apache::lonlocal::texthash (
 7715:                 domain => 'Domain role',
 7716:                 author => 'Co-author role',
 7717:                 course => 'Course role',
 7718:                 community => 'Community role',
 7719:             );
 7720:             my $primary_id = &Apache::lonnet::domain($dom,'primary');
 7721:             my $intdom = &Apache::lonnet::internet_dom($primary_id);
 7722:             foreach my $domtype ('instdom','extdom') {
 7723:                 my (%checked,$skip);
 7724:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7725:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$domtype}.'</td>'.
 7726:                               '<td class="LC_left_item">';
 7727:                 if ($domtype eq 'instdom') {
 7728:                     unless (@instdoms > 1) {
 7729:                         $datatable .= &mt('Nothing to set, as no domains besides [_1] are hosted by [_2]',$dom,$intdom);
 7730:                         $skip = 1;
 7731:                     }
 7732:                 } elsif ($domtype eq 'extdom') {
 7733:                     if (keys(%by_location) == 0) {
 7734:                         $datatable .= &mt('Nothing to set, as no other hosts besides [_1]',$intdom);
 7735:                         $skip = 1;
 7736:                     }
 7737:                 }
 7738:                 unless ($skip) {
 7739:                     foreach my $roletype ('domain','author','course','community') {
 7740:                         $checked{'auto'} = ' checked="checked"';
 7741:                         if (ref($settings) eq 'HASH') {
 7742:                             if (ref($settings->{approval}) eq 'HASH') {
 7743:                                 if (ref($settings->{approval}->{$domtype}) eq 'HASH') {
 7744:                                     if ($settings->{approval}->{$domtype}->{$roletype}=~ /^(none|user|domain)$/) {
 7745:                                         $checked{$1} = ' checked="checked"';
 7746:                                         $checked{'auto'} = '';
 7747:                                     }
 7748:                                 }
 7749:                             }
 7750:                         }
 7751:                         $datatable .= '<fieldset><legend>'.$names{$roletype}.'</legend>';
 7752:                         foreach my $option (@options) {
 7753:                             $datatable .= '<span class="LC_nobreak"><label>'.
 7754:                                           '<input type="radio" name="privacy_approval_'.$domtype.'_'.$roletype.'" '.
 7755:                                           'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 7756:                                           '</label></span>&nbsp; ';
 7757:                         }
 7758:                         $datatable .= '</fieldset>';
 7759:                     }
 7760:                 }
 7761:                 $datatable .= '</td></tr>';
 7762:                 $itemcount ++;
 7763:             }
 7764:         } elsif ($position eq 'middle') {
 7765:             if ((@instdoms > 1) || (keys(%by_location) > 0)) {
 7766:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7767:                     foreach my $item (@{$types}) {
 7768:                         $datatable .= &modifiable_userdata_row('privacy','othdom_'.$item,$settings,
 7769:                                                                $numinrow,$itemcount,'','','','','',
 7770:                                                                '',$usertypes->{$item});
 7771:                         $itemcount ++;
 7772:                     }
 7773:                 }
 7774:                 $datatable .= &modifiable_userdata_row('privacy','othdom_default',$settings,
 7775:                                                        $numinrow,$itemcount,'','','','','',
 7776:                                                        '',$othertitle);
 7777:                 $itemcount ++;
 7778:             } else {
 7779:                 my (@insttypes,%insttitles);
 7780:                 if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7781:                     @insttypes = @{$types};
 7782:                     %insttitles = %{$usertypes};
 7783:                 }
 7784:                 foreach my $item (@insttypes,'default') {
 7785:                     my $title;
 7786:                     if ($item eq 'default') {
 7787:                         $title = $othertitle;
 7788:                     } else {
 7789:                         $title = $insttitles{$item};
 7790:                     }
 7791:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7792:                     $datatable .= '<tr'.$css_class.'>'.
 7793:                                   '<td class="LC_left_item">'.$title.'</td>'.
 7794:                                   '<td class="LC_left_item">'.
 7795:                                   &mt('Nothing to set here, as there are no other domains').
 7796:                                   '</td></tr>';
 7797:                     $itemcount ++;
 7798:                 }
 7799:             }
 7800:         }
 7801:     } else {
 7802:         my $prefix;
 7803:         if ($position eq 'lower') {
 7804:             $prefix = 'priv';
 7805:         } else {
 7806:             $prefix = 'unpriv';
 7807:         }
 7808:         foreach my $item (@items) {
 7809:             $datatable .= &modifiable_userdata_row('privacy',$prefix.'_'.$item,$settings,
 7810:                                                    $numinrow,$itemcount,'','','','','',
 7811:                                                    '',$names{$item});
 7812:             $itemcount ++;
 7813:         }
 7814:     }
 7815:     if (ref($rowtotal)) {
 7816:         $$rowtotal += $itemcount;
 7817:     }
 7818:     return $datatable;
 7819: }
 7820: 
 7821: sub print_passwords {
 7822:     my ($position,$dom,$confname,$settings,$rowtotal) = @_;
 7823:     my ($datatable,$css_class);
 7824:     my $itemcount = 0;
 7825:     my %titles = &Apache::lonlocal::texthash (
 7826:         captcha        => '"Forgot Password" CAPTCHA validation',
 7827:         link           => 'Reset link expiration (hours)',
 7828:         case           => 'Case-sensitive usernames/e-mail',
 7829:         prelink        => 'Information required (form 1)',
 7830:         postlink       => 'Information required (form 2)',
 7831:         emailsrc       => 'LON-CAPA e-mail address type(s)',
 7832:         customtext     => 'Domain specific text (HTML)',
 7833:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
 7834:         intauth_check  => 'Check bcrypt cost if authenticated',
 7835:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
 7836:         permanent      => 'Permanent e-mail address',
 7837:         critical       => 'Critical notification address',
 7838:         notify         => 'Notification address',
 7839:         min            => 'Minimum password length',
 7840:         max            => 'Maximum password length',
 7841:         chars          => 'Required characters',
 7842:         expire         => 'Password expiration (days)',
 7843:         numsaved       => 'Number of previous passwords to save and disallow reuse',
 7844:     );
 7845:     if ($position eq 'top') {
 7846:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 7847:         my $shownlinklife = 2;
 7848:         my $prelink = 'both';
 7849:         my (%casesens,%postlink,%emailsrc,$nostdtext,$customurl);
 7850:         if (ref($settings) eq 'HASH') {
 7851:             if ($settings->{resetlink} =~ /^\d+(|\.\d*)$/) {
 7852:                 $shownlinklife = $settings->{resetlink};
 7853:             }
 7854:             if (ref($settings->{resetcase}) eq 'ARRAY') {
 7855:                 map { $casesens{$_} = 1; } (@{$settings->{resetcase}});
 7856:             }
 7857:             if ($settings->{resetprelink} =~ /^(both|either)$/) {
 7858:                 $prelink = $settings->{resetprelink};
 7859:             }
 7860:             if (ref($settings->{resetpostlink}) eq 'HASH') {
 7861:                 %postlink = %{$settings->{resetpostlink}};
 7862:             }
 7863:             if (ref($settings->{resetemail}) eq 'ARRAY') {
 7864:                 map { $emailsrc{$_} = 1; } (@{$settings->{resetemail}});
 7865:             }
 7866:             if ($settings->{resetremove}) {
 7867:                 $nostdtext = 1;
 7868:             }
 7869:             if ($settings->{resetcustom}) {
 7870:                 $customurl = $settings->{resetcustom};
 7871:             }
 7872:         } else {
 7873:             if (ref($types) eq 'ARRAY') {
 7874:                 foreach my $item (@{$types}) {
 7875:                     $casesens{$item} = 1;
 7876:                     $postlink{$item} = ['username','email'];
 7877:                 }
 7878:             }
 7879:             $casesens{'default'} = 1;
 7880:             $postlink{'default'} = ['username','email'];
 7881:             $prelink = 'both';
 7882:             %emailsrc = (
 7883:                           permanent => 1,
 7884:                           critical  => 1,
 7885:                           notify    => 1,
 7886:             );
 7887:         }
 7888:         $datatable = &captcha_choice('passwords',$settings,$$rowtotal);
 7889:         $itemcount ++;
 7890:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7891:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'link'}.'</td>'.
 7892:                       '<td class="LC_left_item">'.
 7893:                       '<input type="textbox" value="'.$shownlinklife.'" '.
 7894:                       'name="passwords_link" size="3" /></td></tr>';
 7895:         $itemcount ++;
 7896:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7897:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'case'}.'</td>'.
 7898:                       '<td class="LC_left_item">';
 7899:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7900:             foreach my $item (@{$types}) {
 7901:                 my $checkedcase;
 7902:                 if ($casesens{$item}) {
 7903:                     $checkedcase = ' checked="checked"';
 7904:                 }
 7905:                 $datatable .= '<span class="LC_nobreak"><label>'.
 7906:                               '<input type="checkbox" name="passwords_case_sensitive" value="'.
 7907:                               $item.'"'.$checkedcase.' />'.$usertypes->{$item}.'</label>'.
 7908:                               '</span>&nbsp;&nbsp; ';
 7909:             }
 7910:         }
 7911:         my $checkedcase;
 7912:         if ($casesens{'default'}) {
 7913:             $checkedcase = ' checked="checked"';
 7914:         }
 7915:         $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 7916:                       'name="passwords_case_sensitive" value="default"'.$checkedcase.' />'.
 7917:                       $othertitle.'</label></span></td>';
 7918:         $itemcount ++;
 7919:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7920:         my %checkedpre = (
 7921:                              both => ' checked="checked"',
 7922:                              either => '',
 7923:                          );
 7924:         if ($prelink eq 'either') {
 7925:             $checkedpre{either} = ' checked="checked"';
 7926:             $checkedpre{both} = '';
 7927:         }
 7928:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'prelink'}.'</td>'.
 7929:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 7930:                       '<label><input type="radio" name="passwords_prelink" value="both"'.$checkedpre{'both'}.' />'.
 7931:                       &mt('Both username and e-mail address').'</label></span>&nbsp;&nbsp; '.
 7932:                       '<span class="LC_nobreak"><label>'.
 7933:                       '<input type="radio" name="passwords_prelink" value="either"'.$checkedpre{'either'}.' />'.
 7934:                       &mt('Either username or e-mail address').'</label></span></td></tr>';
 7935:         $itemcount ++;
 7936:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7937:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'postlink'}.'</td>'.
 7938:                       '<td class="LC_left_item">';
 7939:         my %postlinked;
 7940:         if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 7941:             foreach my $item (@{$types}) {
 7942:                 undef(%postlinked);
 7943:                 $datatable .= '<fieldset style="display: inline-block;">'.
 7944:                               '<legend>'.$usertypes->{$item}.'</legend>';
 7945:                 if (ref($postlink{$item}) eq 'ARRAY') {
 7946:                     map { $postlinked{$_} = 1; } (@{$postlink{$item}});
 7947:                 }
 7948:                 foreach my $field ('email','username') {
 7949:                     my $checked;
 7950:                     if ($postlinked{$field}) {
 7951:                         $checked = ' checked="checked"';
 7952:                     }
 7953:                     $datatable .= '<span class="LC_nobreak"><label>'.
 7954:                                   '<input type="checkbox" name="passwords_postlink_'.$item.'" value="'.
 7955:                                   $field.'"'.$checked.' />'.$field.'</label>'.
 7956:                                   '<span>&nbsp;&nbsp; ';
 7957:                 }
 7958:                 $datatable .= '</fieldset>';
 7959:             }
 7960:         }
 7961:         if (ref($postlink{'default'}) eq 'ARRAY') {
 7962:             map { $postlinked{$_} = 1; } (@{$postlink{'default'}});
 7963:         }
 7964:         $datatable .= '<fieldset style="display: inline-block;">'.
 7965:                       '<legend>'.$othertitle.'</legend>';
 7966:         foreach my $field ('email','username') {
 7967:             my $checked;
 7968:             if ($postlinked{$field}) {
 7969:                 $checked = ' checked="checked"';
 7970:             }
 7971:             $datatable .= '<span class="LC_nobreak"><label>'.
 7972:                           '<input type="checkbox" name="passwords_postlink_default" value="'.
 7973:                           $field.'"'.$checked.' />'.$field.'</label>'.
 7974:                           '<span>&nbsp;&nbsp; ';
 7975:         }
 7976:         $datatable .= '</fieldset></td></tr>';
 7977:         $itemcount ++;
 7978:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7979:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'emailsrc'}.'</td>'.
 7980:                       '<td class="LC_left_item">';
 7981:         foreach my $type ('permanent','critical','notify') {
 7982:             my $checkedemail;
 7983:             if ($emailsrc{$type}) {
 7984:                 $checkedemail = ' checked="checked"';
 7985:             }
 7986:             $datatable .= '<span class="LC_nobreak"><label>'.
 7987:                           '<input type="checkbox" name="passwords_emailsrc" value="'.
 7988:                           $type.'"'.$checkedemail.' />'.$titles{$type}.'</label>'.
 7989:                           '<span>&nbsp;&nbsp; ';
 7990:         }
 7991:         $datatable .= '</td></tr>';
 7992:         $itemcount ++;
 7993:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 7994:         my $switchserver = &check_switchserver($dom,$confname);
 7995:         my ($showstd,$noshowstd);
 7996:         if ($nostdtext) {
 7997:             $noshowstd = ' checked="checked"';
 7998:         } else {
 7999:             $showstd = ' checked="checked"';
 8000:         }
 8001:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'customtext'}.'</td>'.
 8002:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8003:                       &mt('Retain standard text:').
 8004:                       '<label><input type="radio" name="passwords_stdtext" value="1"'.$showstd.' />'.
 8005:                       &mt('Yes').'</label>'.'&nbsp;'.
 8006:                       '<label><input type="radio" name="passwords_stdtext" value="0"'.$noshowstd.' />'.
 8007:                       &mt('No').'</label></span><br />'.
 8008:                       '<span class="LC_fontsize_small">'.
 8009:                       &mt('(If you use the same account ...  reset a password from this page.)').'</span><br /><br />'.
 8010:                       &mt('Include custom text:');
 8011:         if ($customurl) {
 8012:             my $link =  &Apache::loncommon::modal_link($customurl,&mt('custom text'),600,500,
 8013:                                                        undef,undef,undef,undef,'background-color:#ffffff');
 8014:             $datatable .= '<span class="LC_nobreak">&nbsp;'.$link.
 8015:                           '<label><input type="checkbox" name="passwords_custom_del"'.
 8016:                           ' value="1" />'.&mt('Delete?').'</label></span>'.
 8017:                           ' <span class="LC_nobreak">&nbsp;'.&mt('Replace:').'</span>';
 8018:         }
 8019:         if ($switchserver) {
 8020:             $datatable .= '<span class="LC_nobreak">&nbsp;'.&mt('Upload to library server: [_1]',$switchserver).'</span>';
 8021:         } else {
 8022:             $datatable .='<span class="LC_nobreak">&nbsp;'.
 8023:                          '<input type="file" name="passwords_customfile" /></span>';
 8024:         }
 8025:         $datatable .= '</td></tr>';
 8026:     } elsif ($position eq 'middle') {
 8027:         my %domconf = &Apache::lonnet::get_dom('configuration',['defaults'],$dom);
 8028:         my @items = ('intauth_cost','intauth_check','intauth_switch');
 8029:         my %defaults;
 8030:         if (ref($domconf{'defaults'}) eq 'HASH') {
 8031:             %defaults = %{$domconf{'defaults'}};
 8032:             if ($defaults{'intauth_cost'} !~ /^\d+$/) {
 8033:                 $defaults{'intauth_cost'} = 10;
 8034:             }
 8035:             if ($defaults{'intauth_check'} !~ /^(0|1|2)$/) {
 8036:                 $defaults{'intauth_check'} = 0;
 8037:             }
 8038:             if ($defaults{'intauth_switch'} !~ /^(0|1|2)$/) {
 8039:                 $defaults{'intauth_switch'} = 0;
 8040:             }
 8041:         } else {
 8042:             %defaults = (
 8043:                           'intauth_cost'   => 10,
 8044:                           'intauth_check'  => 0,
 8045:                           'intauth_switch' => 0,
 8046:                         );
 8047:         }
 8048:         foreach my $item (@items) {
 8049:             if ($itemcount%2) {
 8050:                 $css_class = '';
 8051:             } else {
 8052:                 $css_class = ' class="LC_odd_row" ';
 8053:             }
 8054:             $datatable .= '<tr'.$css_class.'>'.
 8055:                           '<td><span class="LC_nobreak">'.$titles{$item}.
 8056:                           '</span></td><td class="LC_left_item" colspan="3">';
 8057:             if ($item eq 'intauth_switch') {
 8058:                 my @options = (0,1,2);
 8059:                 my %optiondesc = &Apache::lonlocal::texthash (
 8060:                                    0 => 'No',
 8061:                                    1 => 'Yes',
 8062:                                    2 => 'Yes, and copy existing passwd file to passwd.bak file',
 8063:                                  );
 8064:                 $datatable .= '<table width="100%">';
 8065:                 foreach my $option (@options) {
 8066:                     my $checked = ' ';
 8067:                     if ($defaults{$item} eq $option) {
 8068:                         $checked = ' checked="checked"';
 8069:                     }
 8070:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8071:                                   '<label><input type="radio" name="'.$item.
 8072:                                   '" value="'.$option.'"'.$checked.' />'.
 8073:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8074:                 }
 8075:                 $datatable .= '</table>';
 8076:             } elsif ($item eq 'intauth_check') {
 8077:                 my @options = (0,1,2);
 8078:                 my %optiondesc = &Apache::lonlocal::texthash (
 8079:                                    0 => 'No',
 8080:                                    1 => 'Yes, allow login then update passwd file using default cost (if higher)',
 8081:                                    2 => 'Yes, disallow login if stored cost is less than domain default',
 8082:                                  );
 8083:                 $datatable .= '<table width="100%">';
 8084:                 foreach my $option (@options) {
 8085:                     my $checked = ' ';
 8086:                     my $onclick;
 8087:                     if ($defaults{$item} eq $option) {
 8088:                         $checked = ' checked="checked"';
 8089:                     }
 8090:                     if ($option == 2) {
 8091:                         $onclick = ' onclick="javascript:warnIntAuth(this);"';
 8092:                     }
 8093:                     $datatable .= '<tr><td class="LC_left_item"><span class="LC_nobreak">'.
 8094:                                   '<label><input type="radio" name="'.$item.
 8095:                                   '" value="'.$option.'"'.$checked.$onclick.' />'.
 8096:                                   $optiondesc{$option}.'</label></span></td></tr>';
 8097:                 }
 8098:                 $datatable .= '</table>';
 8099:             } else {
 8100:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
 8101:                               $defaults{$item}.'" size="3" onblur="javascript:warnIntAuth(this);" />';
 8102:             }
 8103:             $datatable .= '</td></tr>';
 8104:             $itemcount ++;
 8105:         }
 8106:     } elsif ($position eq 'lower') {
 8107:         $datatable .= &password_rules('passwords',\$itemcount,$settings);
 8108:     } else {
 8109:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 8110:         my %ownerchg = (
 8111:                           by  => {},
 8112:                           for => {},
 8113:                        );
 8114:         my %ownertitles = &Apache::lonlocal::texthash (
 8115:                             by  => 'Course owner status(es) allowed',
 8116:                             for => 'Student status(es) allowed',
 8117:                           );
 8118:         if (ref($settings) eq 'HASH') {
 8119:             if (ref($settings->{crsownerchg}) eq 'HASH') {
 8120:                 if (ref($settings->{crsownerchg}{'by'}) eq 'ARRAY') {
 8121:                     map { $ownerchg{by}{$_} = 1; } (@{$settings->{crsownerchg}{'by'}});
 8122:                 }
 8123:                 if (ref($settings->{crsownerchg}{'for'}) eq 'ARRAY') {
 8124:                     map { $ownerchg{for}{$_} = 1; } (@{$settings->{crsownerchg}{'for'}});
 8125:                 }
 8126:             }
 8127:         }
 8128:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8129:         $datatable .= '<tr '.$css_class.'>'.
 8130:                       '<td>'.
 8131:                       &mt('Requirements').'<ul>'.
 8132:                       '<li>'.&mt("Course 'type' is not a Community or Placement Test").'</li>'.
 8133:                       '<li>'.&mt('User is Course Coordinator and also course owner').'</li>'.
 8134:                       '<li>'.&mt("Student's only active roles are student role(s) in course(s) owned by this user").'</li>'.
 8135:                       '<li>'.&mt('User, course, and student share same domain').'</li>'.
 8136:                       '</ul>'.
 8137:                       '</td>'.
 8138:                       '<td class="LC_left_item">';
 8139:         foreach my $item ('by','for') {
 8140:             $datatable .= '<fieldset style="display: inline-block;">'.
 8141:                           '<legend>'.$ownertitles{$item}.'</legend>';
 8142:             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
 8143:                 foreach my $type (@{$types}) {
 8144:                     my $checked;
 8145:                     if ($ownerchg{$item}{$type}) {
 8146:                         $checked = ' checked="checked"';
 8147:                     }
 8148:                     $datatable .= '<span class="LC_nobreak"><label>'.
 8149:                                   '<input type="checkbox" name="passwords_crsowner_'.$item.'" value="'.
 8150:                                   $type.'"'.$checked.' />'.$usertypes->{$type}.'</label>'.
 8151:                                   '</span>&nbsp;&nbsp; ';
 8152:                 }
 8153:             }
 8154:             my $checked;
 8155:             if ($ownerchg{$item}{'default'}) {
 8156:                 $checked = ' checked="checked"';
 8157:             }
 8158:             $datatable .= '<span class="LC_nobreak"><label><input type="checkbox" '.
 8159:                           'name="passwords_crsowner_'.$item.'" value="default"'.$checked.' />'.
 8160:                           $othertitle.'</label></span></fieldset>';
 8161:         }
 8162:         $datatable .= '</td></tr>';
 8163:     }
 8164:     return $datatable;
 8165: }
 8166: 
 8167: sub password_rules {
 8168:     my ($prefix,$itemcountref,$settings) = @_;
 8169:     my ($min,$max,%chars,$expire,$numsaved,$numinrow);
 8170:     my %titles;
 8171:     if ($prefix eq 'passwords') {
 8172:         %titles = &Apache::lonlocal::texthash (
 8173:             min            => 'Minimum password length',
 8174:             max            => 'Maximum password length',
 8175:             chars          => 'Required characters',
 8176:         );
 8177:     } elsif ($prefix eq 'secrets') {
 8178:         %titles = &Apache::lonlocal::texthash (
 8179:             min            => 'Minimum secret length',
 8180:             max            => 'Maximum secret length',
 8181:             chars          => 'Required characters',
 8182:         );
 8183:     }
 8184:     $min = $Apache::lonnet::passwdmin;
 8185:     my $datatable;
 8186:     my $itemcount;
 8187:     if (ref($itemcountref)) {
 8188:         $itemcount = $$itemcountref;
 8189:     }
 8190:     if (ref($settings) eq 'HASH') {
 8191:         if ($settings->{min}) {
 8192:             $min = $settings->{min};
 8193:         }
 8194:         if ($settings->{max}) {
 8195:             $max = $settings->{max};
 8196:         }
 8197:         if (ref($settings->{chars}) eq 'ARRAY') {
 8198:             map { $chars{$_} = 1; } (@{$settings->{chars}});
 8199:         }
 8200:         if ($prefix eq 'passwords') { 
 8201:             if ($settings->{expire}) {
 8202:                 $expire = $settings->{expire};
 8203:             }
 8204:             if ($settings->{numsaved}) {
 8205:                 $numsaved = $settings->{numsaved};
 8206:             }
 8207:         }
 8208:     }
 8209:     my %rulenames = &Apache::lonlocal::texthash(
 8210:                                                  uc => 'At least one upper case letter',
 8211:                                                  lc => 'At least one lower case letter',
 8212:                                                  num => 'At least one number',
 8213:                                                  spec => 'At least one non-alphanumeric',
 8214:                                                );
 8215:     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8216:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'min'}.'</td>'.
 8217:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8218:                   '<input type="text" name="'.$prefix.'_min" value="'.$min.'" size="3" '.
 8219:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8220:                   '<span class="LC_fontsize_small"> '.&mt('(Enter an integer: 7 or larger)').'</span>'.
 8221:                   '</span></td></tr>';
 8222:     $itemcount ++;
 8223:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8224:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'max'}.'</td>'.
 8225:                   '<td class="LC_left_item"><span class="LC_nobreak">'.
 8226:                   '<input type="text" name="'.$prefix.'_max" value="'.$max.'" size="3" '.
 8227:                   'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8228:                   '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no maximum)').'</span>'.
 8229:                   '</span></td></tr>';
 8230:     $itemcount ++;
 8231:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8232:     $datatable .= '<tr'.$css_class.'><td>'.$titles{'chars'}.'<br />'.
 8233:                   '<span class="LC_nobreak LC_fontsize_small">'.&mt('(Leave unchecked if not required)').
 8234:                   '</span></td>';
 8235:     my $numinrow = 2;
 8236:     my @possrules = ('uc','lc','num','spec');
 8237:     $datatable .= '<td class="LC_left_item"><table>';
 8238:     for (my $i=0; $i<@possrules; $i++) {
 8239:         my ($rem,$checked);
 8240:         if ($chars{$possrules[$i]}) {
 8241:             $checked = ' checked="checked"';
 8242:         }
 8243:         $rem = $i%($numinrow);
 8244:         if ($rem == 0) {
 8245:             if ($i > 0) {
 8246:                 $datatable .= '</tr>';
 8247:             }
 8248:             $datatable .= '<tr>';
 8249:         }
 8250:         $datatable .= '<td><span class="LC_nobreak"><label>'.
 8251:                       '<input type="checkbox" name="'.$prefix.'_chars" value="'.$possrules[$i].'"'.$checked.' />'.
 8252:                       $rulenames{$possrules[$i]}.'</label></span></td>';
 8253:     }
 8254:     my $rem = @possrules%($numinrow);
 8255:     my $colsleft = $numinrow - $rem;
 8256:     if ($colsleft > 1 ) {
 8257:         $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8258:                       '&nbsp;</td>';
 8259:     } elsif ($colsleft == 1) {
 8260:         $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8261:     }
 8262:     $datatable .='</table></td></tr>';
 8263:     $itemcount ++;
 8264:     if ($prefix eq 'passwords') {
 8265:         $titles{'expire'} = &mt('Password expiration (days)');
 8266:         $titles{'numsaved'} = &mt('Number of previous passwords to save and disallow reuse');
 8267:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8268:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'expire'}.'</td>'.
 8269:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8270:                       '<input type="text" name="'.$prefix.'_expire" value="'.$expire.'" size="4" '.
 8271:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8272:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank for no expiration)').'</span>'.
 8273:                       '</span></td></tr>';
 8274:         $itemcount ++;
 8275:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8276:         $datatable .= '<tr'.$css_class.'><td>'.$titles{'numsaved'}.'</td>'.
 8277:                       '<td class="LC_left_item"><span class="LC_nobreak">'.
 8278:                       '<input type="text" name="'.$prefix.'_numsaved" value="'.$numsaved.'" size="3" '.
 8279:                       'onblur="javascript:warnInt'.$prefix.'(this);" />'.
 8280:                       '<span class="LC_fontsize_small"> '.&mt('(Leave blank to not save previous passwords)').'</span>'.
 8281:                       '</span></td></tr>';
 8282:         $itemcount ++;
 8283:     }
 8284:     if (ref($itemcountref)) {
 8285:         $$itemcountref += $itemcount;
 8286:     }
 8287:     return $datatable;
 8288: }
 8289: 
 8290: sub print_wafproxy {
 8291:     my ($position,$dom,$settings,$rowtotal) = @_;
 8292:     my $css_class;
 8293:     my $itemcount = 0;
 8294:     my $datatable;
 8295:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8296:     my (%othercontrol,%otherdoms,%aliases,%saml,%values,$setdom,$showdom);
 8297:     my %lt = &wafproxy_titles();
 8298:     foreach my $server (sort(keys(%servers))) {
 8299:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
 8300:         next if ($serverhome eq '');
 8301:         my $serverdom;
 8302:         if ($serverhome ne $server) {
 8303:             $serverdom = &Apache::lonnet::host_domain($serverhome);
 8304:             if (($serverdom ne '') && (&Apache::lonnet::domain($serverdom) ne '')) {
 8305:                 $othercontrol{$server} = $serverdom;
 8306:             }
 8307:         } else {
 8308:             $serverdom = &Apache::lonnet::host_domain($server);
 8309:             next if (($serverdom eq '') || (&Apache::lonnet::domain($serverdom) eq ''));
 8310:             if ($serverdom ne $dom) {
 8311:                 $othercontrol{$server} = $serverdom;
 8312:             } else {
 8313:                 $setdom = 1;
 8314:                 if (ref($settings) eq 'HASH') {
 8315:                     if (ref($settings->{'alias'}) eq 'HASH') {
 8316:                         $aliases{$dom} = $settings->{'alias'};
 8317:                         if ($aliases{$dom} ne '') {
 8318:                             $showdom = 1;
 8319:                         }
 8320:                     }
 8321:                     if (ref($settings->{'saml'}) eq 'HASH') {
 8322:                         $saml{$dom} = $settings->{'saml'};
 8323:                     }
 8324:                 }
 8325:             }
 8326:         }
 8327:     }
 8328:     if ($setdom) {
 8329:         %{$values{$dom}} = ();
 8330:         if (ref($settings) eq 'HASH') {
 8331:             foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8332:                 $values{$dom}{$item} = $settings->{$item};
 8333:             }
 8334:         }
 8335:     }
 8336:     if (keys(%othercontrol)) {
 8337:         %otherdoms = reverse(%othercontrol);
 8338:         foreach my $domain (keys(%otherdoms)) {
 8339:             %{$values{$domain}} = ();
 8340:             my %config = &Apache::lonnet::get_dom('configuration',['wafproxy'],$domain);
 8341:             if (ref($config{'wafproxy'}) eq 'HASH') {
 8342:                 $aliases{$domain} = $config{'wafproxy'}{'alias'};
 8343:                 if (exists($config{'wafproxy'}{'saml'})) { 
 8344:                     $saml{$domain} = $config{'wafproxy'}{'saml'};
 8345:                 }
 8346:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext') {
 8347:                     $values{$domain}{$item} = $config{'wafproxy'}{$item};
 8348:                 }
 8349:             }
 8350:         }
 8351:     }
 8352:     if ($position eq 'top') {
 8353:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8354:         my %aliasinfo;
 8355:         foreach my $server (sort(keys(%servers))) {
 8356:             $itemcount ++;
 8357:             my $dom_in_effect;
 8358:             my $aliasrows = '<tr>'.
 8359:                             '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8360:                             &mt('Hostname').':&nbsp;'.
 8361:                             '<i>'.&Apache::lonnet::hostname($server).'</i></td><td>&nbsp;</td>';
 8362:             if ($othercontrol{$server}) {
 8363:                 $dom_in_effect = $othercontrol{$server};
 8364:                 my ($current,$forsaml);
 8365:                 if (ref($aliases{$dom_in_effect}) eq 'HASH') {
 8366:                     $current = $aliases{$dom_in_effect}{$server};
 8367:                 }
 8368:                 if (ref($saml{$dom_in_effect}) eq 'HASH') {
 8369:                     if ($saml{$dom_in_effect}{$server}) {
 8370:                         $forsaml = 1;
 8371:                     }
 8372:                 }
 8373:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8374:                               &mt('Alias').':&nbsp';
 8375:                 if ($current) {
 8376:                     $aliasrows .= $current;
 8377:                     if ($forsaml) {
 8378:                          $aliasrows .= '&nbsp;('.&mt('also for SSO Auth').')';
 8379:                     }
 8380:                 } else {
 8381:                     $aliasrows .= &mt('None');
 8382:                 }
 8383:                 $aliasrows .= '&nbsp;<span class="LC_small">('.
 8384:                               &mt('controlled by domain: [_1]',
 8385:                                   '<b>'.$dom_in_effect.'</b>').')</span></td>';
 8386:             } else {
 8387:                 $dom_in_effect = $dom;
 8388:                 my ($current,$samlon,$samloff);
 8389:                 $samloff = ' checked="checked"';
 8390:                 if (ref($aliases{$dom}) eq 'HASH') {
 8391:                     if ($aliases{$dom}{$server}) {
 8392:                         $current = $aliases{$dom}{$server};
 8393:                     }
 8394:                 }
 8395:                 if (ref($saml{$dom}) eq 'HASH') {
 8396:                     if ($saml{$dom}{$server}) {
 8397:                         $samlon = $samloff;
 8398:                         undef($samloff);
 8399:                     }
 8400:                 }
 8401:                 $aliasrows .= '<td class="LC_left_item" style="vertical-align: baseline;">'.
 8402:                               &mt('Alias').':&nbsp;'.
 8403:                               '<input type="text" name="wafproxy_alias_'.$server.'" '.
 8404:                               'value="'.$current.'" size="30" />'.
 8405:                               ('&nbsp;'x2).'<span class="LC_nobreak">'.
 8406:                               &mt('Alias used for SSO Auth').':&nbsp;<label>'.
 8407:                               '<input type="radio" value="0"'.$samloff.' name="wafproxy_alias_saml_'.$server.'" />'.
 8408:                               &mt('No').'</label>&nbsp;<label>'. 
 8409:                               '<input type="radio" value="1"'.$samlon.' name="wafproxy_alias_saml_'.$server.'" />'.
 8410:                               &mt('Yes').'</label></span>'.
 8411:                               '</td>'; 
 8412:             }
 8413:             $aliasrows .= '</tr>';
 8414:             $aliasinfo{$dom_in_effect} .= $aliasrows;
 8415:         }
 8416:         if ($aliasinfo{$dom}) {
 8417:             my ($onclick,$wafon,$wafoff,$showtable);
 8418:             $onclick = ' onclick="javascript:toggleWAF();"';
 8419:             $wafoff = ' checked="checked"';
 8420:             $showtable = ' style="display:none";';
 8421:             if ($showdom) {
 8422:                 $wafon = $wafoff;
 8423:                 $wafoff = '';
 8424:                 $showtable = ' style="display:inline;"';
 8425:             }
 8426:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8427:             $datatable = '<tr'.$css_class.'>'.
 8428:                          '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br />'.
 8429:                          '<span class="LC_nobreak">'.&mt('WAF in use?').'&nbsp;<label>'.
 8430:                          '<input type="radio" name="wafproxy_'.$dom.'" value="1"'.$wafon.$onclick.' />'.
 8431:                          &mt('Yes').'</label>'.('&nbsp;'x2).'<label>'.
 8432:                          '<input type="radio" name="wafproxy_'.$dom.'" value="0"'.$wafoff.$onclick.' />'.
 8433:                          &mt('No').'</label></span></td>'.
 8434:                          '<td class="LC_left_item">'.
 8435:                          '<table id="wafproxy_table"'.$showtable.'>'.$aliasinfo{$dom}.
 8436:                          '</table></td></tr>';
 8437:             $itemcount++;
 8438:         }
 8439:         if (keys(%otherdoms)) {
 8440:             foreach my $key (sort(keys(%otherdoms))) {
 8441:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8442:                 $datatable .= '<tr'.$css_class.'>'.
 8443:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$key.'</b>').'</td>'.
 8444:                               '<td class="LC_left_item"><table>'.$aliasinfo{$key}.
 8445:                               '</table></td></tr>';
 8446:                 $itemcount++;
 8447:             }
 8448:         }
 8449:     } else {
 8450:         my %ip_methods = &remoteip_methods();
 8451:         if ($setdom) {
 8452:             $itemcount ++;
 8453:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8454:             my ($nowafstyle,$wafstyle,$curr_remotip,$currwafdisplay,$vpndircheck,$vpnaliascheck,
 8455:                 $currwafvpn,$wafrangestyle,$alltossl,$ssltossl);
 8456:             $wafstyle = ' style="display:none;"';
 8457:             $nowafstyle = ' style="display:table-row;"';
 8458:             $currwafdisplay = ' style="display: none"';
 8459:             $wafrangestyle = ' style="display: none"';
 8460:             $curr_remotip = 'n';
 8461:             $ssltossl = ' checked="checked"';
 8462:             if ($showdom) {
 8463:                 $wafstyle = ' style="display:table-row;"';
 8464:                 $nowafstyle =  ' style="display:none;"';
 8465:                 if (keys(%{$values{$dom}})) {
 8466:                     if ($values{$dom}{remoteip} =~ /^[nmh]$/) {
 8467:                         $curr_remotip = $values{$dom}{remoteip};
 8468:                     }
 8469:                     if ($curr_remotip eq 'h') {
 8470:                         $currwafdisplay = ' style="display:table-row"';
 8471:                         $wafrangestyle = ' style="display:inline-block;"';
 8472:                     }
 8473:                     if ($values{$dom}{'sslopt'}) {
 8474:                         $alltossl = ' checked="checked"';
 8475:                         $ssltossl = '';
 8476:                     }
 8477:                 }
 8478:                 if (($values{$dom}{'vpnint'} ne '') || ($values{$dom}{'vpnext'} ne '')) {
 8479:                     $vpndircheck = ' checked="checked"';
 8480:                     $currwafvpn = ' style="display:table-row;"';
 8481:                     $wafrangestyle = ' style="display:inline-block;"';
 8482:                 } else {
 8483:                     $vpnaliascheck = ' checked="checked"';
 8484:                     $currwafvpn = ' style="display:none;"';
 8485:                 }
 8486:             }
 8487:             $datatable .= '<tr'.$css_class.' id="nowafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8488:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'</td>'.
 8489:                           '<td class="LC_right_item">'.&mt('WAF not in use, nothing to set').'</td>'.
 8490:                           '</tr>'.
 8491:                           '<tr'.$css_class.' id="wafproxyrow_'.$dom.'"'.$wafstyle.'>'.
 8492:                           '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$dom.'</b>').'<br /><br />'.
 8493:                           '<div id="wafproxyranges_'.$dom.'">'.&mt('Format for comma separated IP ranges').':<br />'.
 8494:                           &mt('A.B.C.D/N or A.B.C.D-E.F.G.H').'<br />'.
 8495:                           &mt('Range(s) stored in CIDR notation').'</div></td>'.
 8496:                           '<td class="LC_left_item"><table>'.
 8497:                           '<tr>'.
 8498:                           '<td valign="top">'.$lt{'remoteip'}.':&nbsp;'.
 8499:                           '<select name="wafproxy_remoteip" id="wafproxy_remoteip" onchange="javascript:updateWAF();">';
 8500:             foreach my $option ('m','h','n') {
 8501:                 my $sel;
 8502:                 if ($option eq $curr_remotip) {
 8503:                    $sel = ' selected="selected"';
 8504:                 }
 8505:                 $datatable .= '<option value="'.$option.'"'.$sel.'>'.
 8506:                               $ip_methods{$option}.'</option>';
 8507:             }
 8508:             $datatable .= '</select></td></tr>'."\n".
 8509:                           '<tr id="wafproxy_header"'.$currwafdisplay.'><td>'.
 8510:                           $lt{'ipheader'}.':&nbsp;'.
 8511:                           '<input type="text" value="'.$values{$dom}{'ipheader'}.'" '.
 8512:                           'name="wafproxy_ipheader" />'.
 8513:                           '</td></tr>'."\n".
 8514:                           '<tr id="wafproxy_trust"'.$currwafdisplay.'><td>'.
 8515:                           $lt{'trusted'}.':<br />'.
 8516:                           '<textarea name="wafproxy_trusted" rows="3" cols="80">'.
 8517:                           $values{$dom}{'trusted'}.'</textarea>'.
 8518:                           '</td></tr>'."\n".
 8519:                           '<tr><td><hr /></td></tr>'."\n".
 8520:                           '<tr>'.
 8521:                           '<td valign="top">'.$lt{'vpnaccess'}.':<br /><span class="LC_nobreak">'.
 8522:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpndircheck.' value="1" onclick="javascript:checkWAF();" />'.
 8523:                           $lt{'vpndirect'}.'</label>'.('&nbsp;'x2).
 8524:                           '<label><input type="radio" name="wafproxy_vpnaccess"'.$vpnaliascheck.' value="0" onclick="javascript:checkWAF();" />'.
 8525:                           $lt{'vpnaliased'}.'</label></span></td></tr>';
 8526:             foreach my $item ('vpnint','vpnext') {
 8527:                 $datatable .= '<tr id="wafproxy_show_'.$item.'"'.$currwafvpn.'>'.
 8528:                               '<td valign="top">'.$lt{$item}.':<br />'.
 8529:                               '<textarea name="wafproxy_'.$item.'" rows="3" cols="80">'.
 8530:                               $values{$dom}{$item}.'</textarea>'.
 8531:                               '</td></tr>'."\n";
 8532:             }
 8533:             $datatable .= '<tr><td><hr /></td></tr>'."\n".
 8534:                           '<tr>'.
 8535:                           '<td valign="top">'.$lt{'sslopt'}.':<br /><span class="LC_nobreak">'.
 8536:                           '<label><input type="radio" name="wafproxy_sslopt"'.$alltossl.' value="1" />'.
 8537:                           $lt{'alltossl'}.'</label>'.('&nbsp;'x2).
 8538:                           '<label><input type="radio" name="wafproxy_sslopt"'.$ssltossl.' value="0" />'.
 8539:                           $lt{'ssltossl'}.'</label></span></td></tr>'."\n".
 8540:                           '</table></td></tr>';
 8541:         }
 8542:         if (keys(%otherdoms)) {
 8543:             foreach my $domain (sort(keys(%otherdoms))) {
 8544:                 $itemcount ++;
 8545:                 $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8546:                 $datatable .= '<tr'.$css_class.'>'.
 8547:                               '<td class="LC_left_item">'.&mt('Domain: [_1]','<b>'.$domain.'</b>').'</td>'.
 8548:                               '<td class="LC_left_item"><table>';
 8549:                 foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
 8550:                     my $showval = &mt('None');
 8551:                     if ($item eq 'ssl') {
 8552:                         $showval = $lt{'ssltossl'};
 8553:                     }
 8554:                     if ($values{$domain}{$item}) {
 8555:                         $showval = $values{$domain}{$item};
 8556:                         if ($item eq 'ssl') {
 8557:                             $showval = $lt{'alltossl'};
 8558:                         } elsif ($item eq 'remoteip') {
 8559:                             $showval = $ip_methods{$values{$domain}{$item}};
 8560:                         }
 8561:                     }
 8562:                     $datatable .= '<tr>'.
 8563:                                   '<td>'.$lt{$item}.':&nbsp;'.$showval.'</td></tr>';
 8564:                 }
 8565:                 $datatable .= '</table></td></tr>';
 8566:             }
 8567:         }
 8568:     }
 8569:     $$rowtotal += $itemcount;
 8570:     return $datatable;
 8571: }
 8572: 
 8573: sub wafproxy_titles {
 8574:     return &Apache::lonlocal::texthash(
 8575:                remoteip   => "Method for determining user's IP",
 8576:                ipheader   => 'Request header containing remote IP',
 8577:                trusted    => 'Trusted IP range(s)',
 8578:                vpnaccess  => 'Access from institutional VPN',
 8579:                vpndirect  => 'via regular hostname (no WAF)',
 8580:                vpnaliased => 'via aliased hostname (WAF)',
 8581:                vpnint     => 'Internal IP Range(s) for VPN sessions',
 8582:                vpnext     => 'IP Range(s) for backend WAF connections',
 8583:                sslopt     => 'Forwarding http/https',
 8584:                alltossl   => 'WAF forwards both http and https requests to https',
 8585:                ssltossl   => 'WAF forwards http requests to http and https to https',
 8586:            );
 8587: }
 8588: 
 8589: sub remoteip_methods {
 8590:     return &Apache::lonlocal::texthash(
 8591:               m => 'Use Apache mod_remoteip',
 8592:               h => 'Use headers parsed by LON-CAPA',
 8593:               n => 'Not in use',
 8594:            );
 8595: }
 8596: 
 8597: sub print_usersessions {
 8598:     my ($position,$dom,$settings,$rowtotal) = @_;
 8599:     my ($css_class,$datatable,$itemcount,%checked,%choices);
 8600:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8601:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8602: 
 8603:     my @alldoms = &Apache::lonnet::all_domains();
 8604:     my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8605:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8606:     my %altids = &id_for_thisdom(%servers);
 8607:     if ($position eq 'top') {
 8608:         if (keys(%serverhomes) > 1) {
 8609:             my %spareid = &current_offloads_to($dom,$settings,\%servers);
 8610:             my ($curroffloadnow,$curroffloadoth);
 8611:             if (ref($settings) eq 'HASH') {
 8612:                 if (ref($settings->{'offloadnow'}) eq 'HASH') {
 8613:                     $curroffloadnow = $settings->{'offloadnow'};
 8614:                 }
 8615:                 if (ref($settings->{'offloadoth'}) eq 'HASH') {
 8616:                     $curroffloadoth = $settings->{'offloadoth'};
 8617:                 }
 8618:             }
 8619:             my $other_insts = scalar(keys(%by_location));
 8620:             $datatable .= &spares_row($dom,\%servers,\%spareid,\%serverhomes,\%altids,
 8621:                                       $other_insts,$curroffloadnow,$curroffloadoth,$rowtotal);
 8622:         } else {
 8623:             $datatable .= '<tr'.$css_class.'><td colspan="2">'.
 8624:                           &mt('Nothing to set here, as the cluster to which this domain belongs only contains one server.').
 8625:                           '</td></tr>';
 8626:         }
 8627:     } else {
 8628:         my %titles = &usersession_titles();
 8629:         my ($prefix,@types);
 8630:         if ($position eq 'bottom') {
 8631:             $prefix = 'remote';
 8632:             @types = ('version','excludedomain','includedomain');
 8633:         } else {
 8634:             $prefix = 'hosted';
 8635:             @types = ('excludedomain','includedomain');
 8636:         }
 8637:         ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8638:     }
 8639:     $$rowtotal += $itemcount;
 8640:     return $datatable;
 8641: }
 8642: 
 8643: sub rules_by_location {
 8644:     my ($settings,$prefix,$by_location,$by_ip,$types,$titles) = @_; 
 8645:     my ($datatable,$itemcount,$css_class);
 8646:     if (keys(%{$by_location}) == 0) {
 8647:         $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8648:         $datatable = '<tr'.$css_class.'><td colspan="2">'.
 8649:                      &mt('Nothing to set here, as the cluster to which this domain belongs only contains one institution.').
 8650:                      '</td></tr>';
 8651:         $itemcount = 1;
 8652:     } else {
 8653:         $itemcount = 0;
 8654:         my $numinrow = 5;
 8655:         my (%current,%checkedon,%checkedoff);
 8656:         my @locations = sort(keys(%{$by_location}));
 8657:         foreach my $type (@{$types}) {
 8658:             $checkedon{$type} = '';
 8659:             $checkedoff{$type} = ' checked="checked"';
 8660:         }
 8661:         if (ref($settings) eq 'HASH') {
 8662:             if (ref($settings->{$prefix}) eq 'HASH') {
 8663:                 foreach my $key (keys(%{$settings->{$prefix}})) {
 8664:                     $current{$key} = $settings->{$prefix}{$key};
 8665:                     if ($key eq 'version') {
 8666:                         if ($current{$key} ne '') {
 8667:                             $checkedon{$key} = ' checked="checked"';
 8668:                             $checkedoff{$key} = '';
 8669:                         }
 8670:                     } elsif (ref($current{$key}) eq 'ARRAY') {
 8671:                         $checkedon{$key} = ' checked="checked"';
 8672:                         $checkedoff{$key} = '';
 8673:                     }
 8674:                 }
 8675:             }
 8676:         }
 8677:         foreach my $type (@{$types}) {
 8678:             next if ($type ne 'version' && !@locations);
 8679:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 8680:             $datatable .= '<tr'.$css_class.'>
 8681:                            <td><span class="LC_nobreak">'.$titles->{$type}.'</span><br />
 8682:                            <span class="LC_nobreak">&nbsp;
 8683:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedoff{$type}.' value="0" />'.&mt('Not in use').'</label>&nbsp;
 8684:                            <label><input type="radio" name="'.$prefix.'_'.$type.'_inuse" '.$checkedon{$type}.' value="1" />'.&mt('In use').'</label></span></td><td>';
 8685:             if ($type eq 'version') {
 8686:                 my @lcversions = &Apache::lonnet::all_loncaparevs();
 8687:                 my $selector = '<select name="'.$prefix.'_version">';
 8688:                 foreach my $version (@lcversions) {
 8689:                     my $selected = '';
 8690:                     if ($current{'version'} eq $version) {
 8691:                         $selected = ' selected="selected"';
 8692:                     }
 8693:                     $selector .= ' <option value="'.$version.'"'.
 8694:                                  $selected.'>'.$version.'</option>';
 8695:                 }
 8696:                 $selector .= '</select> ';
 8697:                 $datatable .= &mt('remote server must be version: [_1] or later',$selector);
 8698:             } else {
 8699:                 $datatable.= '<div><input type="button" value="'.&mt('check all').'" '.
 8700:                              'onclick="javascript:checkAll(document.display.'.$prefix.'_'.$type.')"'.
 8701:                              ' />'.('&nbsp;'x2).
 8702:                              '<input type="button" value="'.&mt('uncheck all').'" '.
 8703:                              'onclick="javascript:uncheckAll(document.display.'.$prefix.'_'.$type.')" />'.
 8704:                              "\n".
 8705:                              '</div><div><table>';
 8706:                 my $rem;
 8707:                 for (my $i=0; $i<@locations; $i++) {
 8708:                     my ($showloc,$value,$checkedtype);
 8709:                     if (ref($by_location->{$locations[$i]}) eq 'ARRAY') {
 8710:                         my $ip = $by_location->{$locations[$i]}->[0];
 8711:                         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8712:                             $value = join(':',@{$by_ip->{$ip}});
 8713:                             $showloc = join(', ',@{$by_ip->{$ip}});
 8714:                             if (ref($current{$type}) eq 'ARRAY') {
 8715:                                 foreach my $loc (@{$by_ip->{$ip}}) {
 8716:                                     if (grep(/^\Q$loc\E$/,@{$current{$type}})) {
 8717:                                         $checkedtype = ' checked="checked"';
 8718:                                         last;
 8719:                                     }
 8720:                                 }
 8721:                             }
 8722:                         }
 8723:                     }
 8724:                     $rem = $i%($numinrow);
 8725:                     if ($rem == 0) {
 8726:                         if ($i > 0) {
 8727:                             $datatable .= '</tr>';
 8728:                         }
 8729:                         $datatable .= '<tr>';
 8730:                     }
 8731:                     $datatable .= '<td class="LC_left_item">'.
 8732:                                   '<span class="LC_nobreak"><label>'.
 8733:                                   '<input type="checkbox" name="'.$prefix.'_'.$type.
 8734:                                   '" value="'.$value.'"'.$checkedtype.' />'.$showloc.
 8735:                                   '</label></span></td>';
 8736:                 }
 8737:                 $rem = @locations%($numinrow);
 8738:                 my $colsleft = $numinrow - $rem;
 8739:                 if ($colsleft > 1 ) {
 8740:                     $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 8741:                                   '&nbsp;</td>';
 8742:                 } elsif ($colsleft == 1) {
 8743:                     $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 8744:                 }
 8745:                 $datatable .= '</tr></table>';
 8746:             }
 8747:             $datatable .= '</td></tr>';
 8748:             $itemcount ++;
 8749:         }
 8750:     }
 8751:     return ($datatable,$itemcount);
 8752: }
 8753: 
 8754: sub print_ssl {
 8755:     my ($position,$dom,$settings,$rowtotal) = @_;
 8756:     my ($css_class,$datatable);
 8757:     my $itemcount = 1;
 8758:     if ($position eq 'top') {
 8759:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
 8760:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
 8761:         my $same_institution;
 8762:         if ($intdom ne '') {
 8763:             my $internet_names = &Apache::lonnet::get_internet_names($Apache::lonnet::perlvar{'lonHostID'});
 8764:             if (ref($internet_names) eq 'ARRAY') {
 8765:                 if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
 8766:                     $same_institution = 1;
 8767:                 }
 8768:             }
 8769:         }
 8770:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8771:         $datatable = '<tr'.$css_class.'><td colspan="2">';
 8772:         if ($same_institution) {
 8773:             my %domservers = &Apache::lonnet::get_servers($dom);
 8774:             $datatable .= &LONCAPA::SSL::print_certstatus(\%domservers,'web','domprefs');
 8775:         } else {
 8776:             $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.");
 8777:         }
 8778:         $datatable .= '</td></tr>';
 8779:         $itemcount ++;
 8780:     } else {
 8781:         my %titles = &ssl_titles();
 8782:         my (%by_ip,%by_location,@intdoms,@instdoms);
 8783:         &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8784:         my @alldoms = &Apache::lonnet::all_domains();
 8785:         my %serverhomes = %Apache::lonnet::serverhomeIDs;
 8786:         my @domservers = &Apache::lonnet::get_servers($dom);
 8787:         my %servers = &Apache::lonnet::internet_dom_servers($dom);
 8788:         my %altids = &id_for_thisdom(%servers);
 8789:         if (($position eq 'connto') || ($position eq 'connfrom')) {
 8790:             my $legacy;
 8791:             unless (ref($settings) eq 'HASH') {
 8792:                 my $name;
 8793:                 if ($position eq 'connto') {
 8794:                     $name = 'loncAllowInsecure';
 8795:                 } else {
 8796:                     $name = 'londAllowInsecure';
 8797:                 }
 8798:                 my $primarylibserv = &Apache::lonnet::domain($dom,'primary');
 8799:                 my @ids=&Apache::lonnet::current_machine_ids();
 8800:                 if (($primarylibserv ne '') && (!grep(/^\Q$primarylibserv\E$/,@ids))) {
 8801:                     my %what = (
 8802:                                    $name => 1,
 8803:                                );
 8804:                     my ($result,$returnhash) =
 8805:                         &Apache::lonnet::get_remote_globals($primarylibserv,\%what);
 8806:                     if ($result eq 'ok') {
 8807:                         if (ref($returnhash) eq 'HASH') {
 8808:                             $legacy = $returnhash->{$name};
 8809:                         }
 8810:                     }
 8811:                 } else {
 8812:                     $legacy = $Apache::lonnet::perlvar{$name};
 8813:                 }
 8814:             }
 8815:             foreach my $type ('dom','intdom','other') {
 8816:                 my %checked;
 8817:                 $css_class = $itemcount%2?' class="LC_odd_row"':'';
 8818:                 $datatable .= '<tr'.$css_class.'><td>'.$titles{$type}.'</td>'.
 8819:                               '<td class="LC_right_item">';
 8820:                 my $skip; 
 8821:                 if ($type eq 'dom') {
 8822:                     unless (keys(%servers) > 1) {
 8823:                         $datatable .= &mt('Nothing to set here, as there are no other servers/VMs');    
 8824:                         $skip = 1;
 8825:                     }
 8826:                 }
 8827:                 if ($type eq 'intdom') {
 8828:                     unless (@instdoms > 1) {
 8829:                         $datatable .= &mt('Nothing to set here, as there are no other domains for this institution');
 8830:                         $skip = 1;
 8831:                     } 
 8832:                 } elsif ($type eq 'other') {
 8833:                     if (keys(%by_location) == 0) {
 8834:                         $datatable .= &mt('Nothing to set here, as there are no other institutions');
 8835:                         $skip = 1;
 8836:                     }
 8837:                 }
 8838:                 unless ($skip) {
 8839:                     $checked{'yes'} = ' checked="checked"'; 
 8840:                     if (ref($settings) eq 'HASH') {
 8841:                         if (ref($settings->{$position}) eq 'HASH') {
 8842:                             if ($settings->{$position}->{$type} =~ /^(no|req)$/) {
 8843:                                 $checked{$1} = $checked{'yes'};
 8844:                                 delete($checked{'yes'}); 
 8845:                             }
 8846:                         }
 8847:                     } else {
 8848:                         if ($legacy == 0) {
 8849:                             $checked{'req'} = $checked{'yes'};
 8850:                             delete($checked{'yes'});    
 8851:                         }
 8852:                     }
 8853:                     foreach my $option ('no','yes','req') {
 8854:                         $datatable .= '<span class="LC_nobreak"><label>'.
 8855:                                       '<input type="radio" name="'.$position.'_'.$type.'" '.
 8856:                                       'value="'.$option.'"'.$checked{$option}.' />'.$titles{$option}.
 8857:                                       '</label></span>'.('&nbsp;'x2);
 8858:                     }
 8859:                 }
 8860:                 $datatable .= '</td></tr>';
 8861:                 $itemcount ++; 
 8862:             }
 8863:         } else {
 8864:             my $prefix = 'replication';
 8865:             my @types = ('certreq','nocertreq');
 8866:             if (keys(%by_location) == 0) {
 8867:                 $datatable .= '<tr'.$css_class.'><td>'.
 8868:                               &mt('Nothing to set here, as there are no other institutions').
 8869:                               '</td></tr>';
 8870:                 $itemcount ++;
 8871:             } else {
 8872:                 ($datatable,$itemcount) = 
 8873:                     &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8874:             }
 8875:         }
 8876:     }
 8877:     $$rowtotal += $itemcount;
 8878:     return $datatable;
 8879: }
 8880: 
 8881: sub ssl_titles {
 8882:     return &Apache::lonlocal::texthash (
 8883:                dom           => 'LON-CAPA servers/VMs from same domain',
 8884:                intdom        => 'LON-CAPA servers/VMs from same "internet" domain',
 8885:                other         => 'External LON-CAPA servers/VMs',
 8886:                connto        => 'Connections to other servers',
 8887:                connfrom      => 'Connections from other servers',
 8888:                replication   => 'Replicating content to other institutions',
 8889:                certreq       => 'Client certificate required, but specific domains exempt',
 8890:                nocertreq     => 'No client certificate required, except for specific domains',
 8891:                no            => 'SSL not used',
 8892:                yes           => 'SSL Optional (used if available)',
 8893:                req           => 'SSL Required',
 8894:     );
 8895: }
 8896: 
 8897: sub print_trust {
 8898:     my ($prefix,$dom,$settings,$rowtotal) = @_;
 8899:     my ($css_class,$datatable,%checked,%choices);
 8900:     my (%by_ip,%by_location,@intdoms,@instdoms);
 8901:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
 8902:     my $itemcount = 1;
 8903:     my %titles = &trust_titles();
 8904:     my @types = ('exc','inc');
 8905:     if ($prefix eq 'top') {
 8906:         $prefix = 'content';
 8907:     } elsif ($prefix eq 'bottom') {
 8908:         $prefix = 'msg';
 8909:     }
 8910:     ($datatable,$itemcount) = &rules_by_location($settings,$prefix,\%by_location,\%by_ip,\@types,\%titles);
 8911:     $$rowtotal += $itemcount;
 8912:     return $datatable;
 8913: }
 8914: 
 8915: sub trust_titles {
 8916:     return &Apache::lonlocal::texthash(
 8917:                content  => "Access to this domain's content by others",
 8918:                shared   => "Access to other domain's content by this domain",
 8919:                enroll   => "Enrollment in this domain's courses by others", 
 8920:                othcoau  => "Co-author roles in this domain for others",
 8921:                coaurem  => "Co-author roles for this domain's users elsewhere", 
 8922:                domroles => "Domain roles in this domain assignable to others",
 8923:                catalog  => "Course Catalog for this domain displayed elsewhere",
 8924:                reqcrs   => "Requests for creation of courses in this domain by others",
 8925:                msg      => "Users in other domains can send messages to this domain",
 8926:                exc      => "Allow all, but exclude specific domains",
 8927:                inc      => "Deny all, but include specific domains",
 8928:            );
 8929: } 
 8930: 
 8931: sub build_location_hashes {
 8932:     my ($intdoms,$by_ip,$by_location,$instdoms) = @_;
 8933:     return unless((ref($intdoms) eq 'ARRAY') && (ref($by_ip) eq 'HASH') &&
 8934:                   (ref($by_location) eq 'HASH') && (ref($instdoms) eq 'ARRAY'));
 8935:     my %iphost = &Apache::lonnet::get_iphost();
 8936:     my $primary_id = &Apache::lonnet::domain($env{'request.role.domain'},'primary');
 8937:     my $primary_ip = &Apache::lonnet::get_host_ip($primary_id);
 8938:     if (ref($iphost{$primary_ip}) eq 'ARRAY') {
 8939:         foreach my $id (@{$iphost{$primary_ip}}) {
 8940:             my $intdom = &Apache::lonnet::internet_dom($id);
 8941:             unless(grep(/^\Q$intdom\E$/,@{$intdoms})) {
 8942:                 push(@{$intdoms},$intdom);
 8943:             }
 8944:         }
 8945:     }
 8946:     foreach my $ip (keys(%iphost)) {
 8947:         if (ref($iphost{$ip}) eq 'ARRAY') {
 8948:             foreach my $id (@{$iphost{$ip}}) {
 8949:                 my $location = &Apache::lonnet::internet_dom($id);
 8950:                 if ($location) {
 8951:                     if (grep(/^\Q$location\E$/,@{$intdoms})) {
 8952:                         my $dom = &Apache::lonnet::host_domain($id);
 8953:                         unless (grep(/^\Q$dom\E/,@{$instdoms})) {
 8954:                             push(@{$instdoms},$dom);
 8955:                         }
 8956:                         next;
 8957:                     }
 8958:                     if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8959:                         unless(grep(/^\Q$location\E$/,@{$by_ip->{$ip}})) {
 8960:                             push(@{$by_ip->{$ip}},$location);
 8961:                         }
 8962:                     } else {
 8963:                         $by_ip->{$ip} = [$location];
 8964:                     }
 8965:                 }
 8966:             }
 8967:         }
 8968:     }
 8969:     foreach my $ip (sort(keys(%{$by_ip}))) {
 8970:         if (ref($by_ip->{$ip}) eq 'ARRAY') {
 8971:             @{$by_ip->{$ip}} = sort(@{$by_ip->{$ip}});
 8972:             my $first = $by_ip->{$ip}->[0];
 8973:             if (ref($by_location->{$first}) eq 'ARRAY') {
 8974:                 unless (grep(/^\Q$ip\E$/,@{$by_location->{$first}})) {
 8975:                     push(@{$by_location->{$first}},$ip);
 8976:                 }
 8977:             } else {
 8978:                 $by_location->{$first} = [$ip];
 8979:             }
 8980:         }
 8981:     }
 8982:     return;
 8983: }
 8984: 
 8985: sub current_offloads_to {
 8986:     my ($dom,$settings,$servers) = @_;
 8987:     my (%spareid,%otherdomconfigs);
 8988:     if (ref($servers) eq 'HASH') {
 8989:         foreach my $lonhost (sort(keys(%{$servers}))) {
 8990:             my $gotspares;
 8991:             if (ref($settings) eq 'HASH') {
 8992:                 if (ref($settings->{'spares'}) eq 'HASH') {
 8993:                     if (ref($settings->{'spares'}{$lonhost}) eq 'HASH') {
 8994:                         $spareid{$lonhost}{'primary'} = $settings->{'spares'}{$lonhost}{'primary'};
 8995:                         $spareid{$lonhost}{'default'} = $settings->{'spares'}{$lonhost}{'default'};
 8996:                         $gotspares = 1;
 8997:                     }
 8998:                 }
 8999:             }
 9000:             unless ($gotspares) {
 9001:                 my $gotspares;
 9002:                 my $serverhomeID =
 9003:                     &Apache::lonnet::get_server_homeID($servers->{$lonhost});
 9004:                 my $serverhomedom =
 9005:                     &Apache::lonnet::host_domain($serverhomeID);
 9006:                 if ($serverhomedom ne $dom) {
 9007:                     if (ref($otherdomconfigs{$serverhomedom} eq 'HASH')) {
 9008:                         if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9009:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9010:                                 $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9011:                                 $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9012:                                 $gotspares = 1;
 9013:                             }
 9014:                         }
 9015:                     } else {
 9016:                         $otherdomconfigs{$serverhomedom} =
 9017:                             &Apache::lonnet::get_dom('configuration',['usersessions'],$serverhomedom);
 9018:                         if (ref($otherdomconfigs{$serverhomedom}) eq 'HASH') {
 9019:                             if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}) eq 'HASH') {
 9020:                                 if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}) eq 'HASH') {
 9021:                                     if (ref($otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{$lonhost}) eq 'HASH') {
 9022:                                         $spareid{$lonhost}{'primary'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'primary'};
 9023:                                         $spareid{$lonhost}{'default'} = $otherdomconfigs{$serverhomedom}{'usersessions'}{'spares'}{'default'};
 9024:                                         $gotspares = 1;
 9025:                                     }
 9026:                                 }
 9027:                             }
 9028:                         }
 9029:                     }
 9030:                 }
 9031:             }
 9032:             unless ($gotspares) {
 9033:                 if ($lonhost eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9034:                     $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9035:                     $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9036:                } else {
 9037:                     my $server_hostname = &Apache::lonnet::hostname($lonhost);
 9038:                     my $server_homeID = &Apache::lonnet::get_server_homeID($server_hostname);
 9039:                     if ($server_homeID eq $Apache::lonnet::perlvar{'lonHostID'}) {
 9040:                         $spareid{$lonhost}{'primary'} = $Apache::lonnet::spareid{'primary'};
 9041:                         $spareid{$lonhost}{'default'} = $Apache::lonnet::spareid{'default'};
 9042:                     } else {
 9043:                         my %what = (
 9044:                              spareid => 1,
 9045:                         );
 9046:                         my ($result,$returnhash) = 
 9047:                             &Apache::lonnet::get_remote_globals($lonhost,\%what);
 9048:                         if ($result eq 'ok') { 
 9049:                             if (ref($returnhash) eq 'HASH') {
 9050:                                 if (ref($returnhash->{'spareid'}) eq 'HASH') {
 9051:                                     $spareid{$lonhost}{'primary'} = $returnhash->{'spareid'}->{'primary'};
 9052:                                     $spareid{$lonhost}{'default'} = $returnhash->{'spareid'}->{'default'};
 9053:                                 }
 9054:                             }
 9055:                         }
 9056:                     }
 9057:                 }
 9058:             }
 9059:         }
 9060:     }
 9061:     return %spareid;
 9062: }
 9063: 
 9064: sub spares_row {
 9065:     my ($dom,$servers,$spareid,$serverhomes,$altids,$other_insts,
 9066:         $curroffloadnow,$curroffloadoth,$rowtotal) = @_;
 9067:     my $css_class;
 9068:     my $numinrow = 4;
 9069:     my $itemcount = 1;
 9070:     my $datatable;
 9071:     my %typetitles = &sparestype_titles();
 9072:     if ((ref($servers) eq 'HASH') && (ref($spareid) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9073:         foreach my $server (sort(keys(%{$servers}))) {
 9074:             my $serverhome = &Apache::lonnet::get_server_homeID($servers->{$server});
 9075:             my ($othercontrol,$serverdom);
 9076:             if ($serverhome ne $server) {
 9077:                 $serverdom = &Apache::lonnet::host_domain($serverhome);
 9078:                 $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9079:             } else {
 9080:                 $serverdom = &Apache::lonnet::host_domain($server);
 9081:                 if ($serverdom ne $dom) {
 9082:                     $othercontrol = &mt('Session offloading controlled by domain: [_1]','<b>'.$serverdom.'</b>');
 9083:                 }
 9084:             }
 9085:             next unless (ref($spareid->{$server}) eq 'HASH');
 9086:             my ($checkednow,$checkedoth);
 9087:             if (ref($curroffloadnow) eq 'HASH') {
 9088:                 if ($curroffloadnow->{$server}) {
 9089:                     $checkednow = ' checked="checked"';
 9090:                 }
 9091:             }
 9092:             if (ref($curroffloadoth) eq 'HASH') {
 9093:                 if ($curroffloadoth->{$server}) {
 9094:                     $checkedoth = ' checked="checked"';
 9095:                 }
 9096:             }
 9097:             $css_class = $itemcount%2 ? ' class="LC_odd_row"' : '';
 9098:             $datatable .= '<tr'.$css_class.'>
 9099:                            <td rowspan="2">
 9100:                             <span class="LC_nobreak">'.
 9101:                           &mt('[_1] when busy, offloads to:'
 9102:                               ,'<b>'.$server.'</b>').'</span><br />'.
 9103:                           '<span class="LC_nobreak">'."\n".
 9104:                           '<label><input type="checkbox" name="offloadnow" value="'.$server.'"'.$checkednow.' />'.
 9105:                           '&nbsp;'.&mt('Switch any active user on next access').'</label></span>'.
 9106:                           "\n";
 9107:             if ($other_insts) {
 9108:                 $datatable .= '<br />'.
 9109:                               '<span class="LC_nobreak">'."\n".
 9110:                           '<label><input type="checkbox" name="offloadoth" value="'.$server.'"'.$checkedoth.' />'.
 9111:                           '&nbsp;'.&mt('Switch other institutions on next access').'</label></span>'.
 9112:                           "\n";
 9113:             }
 9114:             my (%current,%canselect);
 9115:             my @choices = 
 9116:                 &possible_newspares($server,$spareid->{$server},$serverhomes,$altids);
 9117:             foreach my $type ('primary','default') {
 9118:                 if (ref($spareid->{$server}) eq 'HASH') {
 9119:                     if (ref($spareid->{$server}{$type}) eq 'ARRAY') {
 9120:                         my @spares = @{$spareid->{$server}{$type}};
 9121:                         if (@spares > 0) {
 9122:                             if ($othercontrol) {
 9123:                                 $current{$type} = join(', ',@spares);
 9124:                             } else {
 9125:                                 $current{$type} .= '<table>';
 9126:                                 my $numspares = scalar(@spares);
 9127:                                 for (my $i=0;  $i<@spares; $i++) {
 9128:                                     my $rem = $i%($numinrow);
 9129:                                     if ($rem == 0) {
 9130:                                         if ($i > 0) {
 9131:                                             $current{$type} .= '</tr>';
 9132:                                         }
 9133:                                         $current{$type} .= '<tr>';
 9134:                                     }
 9135:                                     $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;'.
 9136:                                                        $spareid->{$server}{$type}[$i].
 9137:                                                        '</label></td>'."\n";
 9138:                                 }
 9139:                                 my $rem = @spares%($numinrow);
 9140:                                 my $colsleft = $numinrow - $rem;
 9141:                                 if ($colsleft > 1 ) {
 9142:                                     $current{$type} .= '<td colspan="'.$colsleft.
 9143:                                                        '" class="LC_left_item">'.
 9144:                                                        '&nbsp;</td>';
 9145:                                 } elsif ($colsleft == 1) {
 9146:                                     $current{$type} .= '<td class="LC_left_item">&nbsp;</td>'."\n";
 9147:                                 }
 9148:                                 $current{$type} .= '</tr></table>';
 9149:                             }
 9150:                         }
 9151:                     }
 9152:                     if ($current{$type} eq '') {
 9153:                         $current{$type} = &mt('None specified');
 9154:                     }
 9155:                     if ($othercontrol) {
 9156:                         if ($type eq 'primary') {
 9157:                             $canselect{$type} = $othercontrol;
 9158:                         }
 9159:                     } else {
 9160:                         $canselect{$type} = 
 9161:                             &mt('Add new [_1]'.$type.'[_2]:','<i>','</i>').'&nbsp;'.
 9162:                             '<select name="newspare_'.$type.'_'.$server.'" '.
 9163:                             'id="newspare_'.$type.'_'.$server.'" onchange="checkNewSpares('."'$server','$type'".');">'."\n".
 9164:                             '<option value="" selected ="selected">'.&mt('Select').'</option>'."\n";
 9165:                         if (@choices > 0) {
 9166:                             foreach my $lonhost (@choices) {
 9167:                                 $canselect{$type} .= '<option value="'.$lonhost.'">'.$lonhost.'</option>'."\n";
 9168:                             }
 9169:                         }
 9170:                         $canselect{$type} .= '</select>'."\n";
 9171:                     }
 9172:                 } else {
 9173:                     $current{$type} = &mt('Could not be determined');
 9174:                     if ($type eq 'primary') {
 9175:                         $canselect{$type} =  $othercontrol;
 9176:                     }
 9177:                 }
 9178:                 if ($type eq 'default') {
 9179:                     $datatable .= '<tr'.$css_class.'>';
 9180:                 }
 9181:                 $datatable .= '<td><i>'.$typetitles{$type}.'</i></td>'."\n".
 9182:                               '<td>'.$current{$type}.'</td>'."\n".
 9183:                               '<td>'.$canselect{$type}.'</td></tr>'."\n";
 9184:             }
 9185:             $itemcount ++;
 9186:         }
 9187:     }
 9188:     $$rowtotal += $itemcount;
 9189:     return $datatable;
 9190: }
 9191: 
 9192: sub possible_newspares {
 9193:     my ($server,$currspares,$serverhomes,$altids) = @_;
 9194:     my $serverhostname = &Apache::lonnet::hostname($server);
 9195:     my %excluded;
 9196:     if ($serverhostname ne '') {
 9197:         %excluded = (
 9198:                        $serverhostname => 1,
 9199:                     );
 9200:     }
 9201:     if (ref($currspares) eq 'HASH') {
 9202:         foreach my $type (keys(%{$currspares})) {
 9203:             if (ref($currspares->{$type}) eq 'ARRAY') {
 9204:                 if (@{$currspares->{$type}} > 0) {
 9205:                     foreach my $curr (@{$currspares->{$type}}) {
 9206:                         my $hostname = &Apache::lonnet::hostname($curr);
 9207:                         $excluded{$hostname} = 1;
 9208:                     }
 9209:                 }
 9210:             }
 9211:         }
 9212:     }
 9213:     my @choices;
 9214:     if ((ref($serverhomes) eq 'HASH') && (ref($altids) eq 'HASH')) {
 9215:         if (keys(%{$serverhomes}) > 1) {
 9216:             foreach my $name (sort(keys(%{$serverhomes}))) {
 9217:                 unless ($excluded{$name}) {
 9218:                     if (exists($altids->{$serverhomes->{$name}})) {
 9219:                         push(@choices,$altids->{$serverhomes->{$name}});
 9220:                     } else {
 9221:                         push(@choices,$serverhomes->{$name});
 9222:                     }
 9223:                 }
 9224:             }
 9225:         }
 9226:     }
 9227:     return sort(@choices);
 9228: }
 9229: 
 9230: sub print_loadbalancing {
 9231:     my ($dom,$settings,$rowtotal) = @_;
 9232:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
 9233:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
 9234:     my $numinrow = 1;
 9235:     my $datatable;
 9236:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
 9237:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
 9238:     if (ref($settings) eq 'HASH') {
 9239:         %existing = %{$settings};
 9240:     }
 9241:     if ((keys(%servers) > 1) || (keys(%existing) > 0)) {
 9242:         &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
 9243:                                   \%currtargets,\%currrules,\%currcookies);
 9244:     } else {
 9245:         return;
 9246:     }
 9247:     my ($othertitle,$usertypes,$types) =
 9248:         &Apache::loncommon::sorted_inst_types($dom);
 9249:     my $rownum = 8;
 9250:     if (ref($types) eq 'ARRAY') {
 9251:         $rownum += scalar(@{$types});
 9252:     }
 9253:     my @css_class = ('LC_odd_row','LC_even_row');
 9254:     my $balnum = 0;
 9255:     my $islast;
 9256:     my (@toshow,$disabledtext);
 9257:     if (keys(%currbalancer) > 0) {
 9258:         @toshow = sort(keys(%currbalancer));
 9259:         if (scalar(@toshow) < scalar(keys(%servers)) + 1) {
 9260:             push(@toshow,'');
 9261:         }
 9262:     } else {
 9263:         @toshow = ('');
 9264:         $disabledtext = &mt('No existing load balancer');
 9265:     }
 9266:     foreach my $lonhost (@toshow) {
 9267:         if ($balnum == scalar(@toshow)-1) {
 9268:             $islast = 1;
 9269:         } else {
 9270:             $islast = 0;
 9271:         }
 9272:         my $cssidx = $balnum%2;
 9273:         my $targets_div_style = 'display: none';
 9274:         my $disabled_div_style = 'display: block';
 9275:         my $homedom_div_style = 'display: none';
 9276:         $datatable .= '<tr class="'.$css_class[$cssidx].'">'.
 9277:                       '<td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9278:                       '<p>';
 9279:         if ($lonhost eq '') {
 9280:             $datatable .= '<span class="LC_nobreak">';
 9281:             if (keys(%currbalancer) > 0) {
 9282:                 $datatable .= &mt('Add balancer:');
 9283:             } else {
 9284:                 $datatable .= &mt('Enable balancer:');
 9285:             }
 9286:             $datatable .= '&nbsp;'.
 9287:                           '<select name="loadbalancing_lonhost_'.$balnum.'"'.
 9288:                           ' id="loadbalancing_lonhost_'.$balnum.'"'.
 9289:                           ' onchange="toggleTargets('."'$balnum'".');">'."\n".
 9290:                           '<option value="" selected="selected">'.&mt('None').
 9291:                           '</option>'."\n";
 9292:             foreach my $server (sort(keys(%servers))) {
 9293:                 next if ($currbalancer{$server});
 9294:                 $datatable .= '<option value="'.$server.'">'.$server.'</option>'."\n";
 9295:             }
 9296:             $datatable .=
 9297:                 '</select>'."\n".
 9298:                 '<input type="hidden" name="loadbalancing_prevlonhost_'.$balnum.'" id="loadbalancing_prevlonhost_'.$balnum.'" value="" />&nbsp;</span>'."\n";
 9299:         } else {
 9300:             $datatable .= '<i>'.$lonhost.'</i><br /><span class="LC_nobreak">'.
 9301:                           '<label><input type="checkbox" name="loadbalancing_delete" value="'.$balnum.'" id="loadbalancing_delete_'.$balnum.'" onclick="javascript:balancerDeleteChange('."'$balnum'".');" />&nbsp;'.
 9302:                            &mt('Stop balancing').'</label>'.
 9303:                            '<input type="hidden" name="loadbalancing_lonhost_'.$balnum.'" value="'.$lonhost.'" id="loadbalancing_lonhost_'.$balnum.'" /></span>';
 9304:             $targets_div_style = 'display: block';
 9305:             $disabled_div_style = 'display: none';
 9306:             if ($dom eq &Apache::lonnet::host_domain($lonhost)) {
 9307:                 $homedom_div_style = 'display: block';
 9308:             }
 9309:         }
 9310:         $datatable .= '</p></td><td rowspan="'.$rownum.'" style="vertical-align: top">'.
 9311:                   '<div id="loadbalancing_disabled_'.$balnum.'" style="'.
 9312:                   $disabled_div_style.'">'.$disabledtext.'</div>'."\n".
 9313:                   '<div id="loadbalancing_targets_'.$balnum.'" style="'.$targets_div_style.'">'.&mt('Offloads to:').'<br />';
 9314:         my ($numspares,@spares) = &count_servers($lonhost,%servers);
 9315:         my @sparestypes = ('primary','default');
 9316:         my %typetitles = &sparestype_titles();
 9317:         my %hostherechecked = (
 9318:                                   no => ' checked="checked"',
 9319:                               );
 9320:         my %balcookiechecked = (
 9321:                                   no => ' checked="checked"', 
 9322:                                );
 9323:         foreach my $sparetype (@sparestypes) {
 9324:             my $targettable;
 9325:             for (my $i=0; $i<$numspares; $i++) {
 9326:                 my $checked;
 9327:                 if (ref($currtargets{$lonhost}) eq 'HASH') {
 9328:                     if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9329:                         if (grep(/^\Q$spares[$i]\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9330:                             $checked = ' checked="checked"';
 9331:                         }
 9332:                     }
 9333:                 }
 9334:                 my ($chkboxval,$disabled);
 9335:                 if (($lonhost ne '') && (exists($servers{$lonhost}))) {
 9336:                     $chkboxval = $spares[$i];
 9337:                 }
 9338:                 if (exists($currbalancer{$spares[$i]})) {
 9339:                     $disabled = ' disabled="disabled"';
 9340:                 }
 9341:                 $targettable .=
 9342:                     '<td><span class="LC_nobreak"><label>'.
 9343:                     '<input type="checkbox" name="loadbalancing_target_'.$balnum.'_'.$sparetype.'"'.
 9344:                     $checked.$disabled.' value="'.$chkboxval.'" id="loadbalancing_target_'.$balnum.'_'.$sparetype.'_'.$i.'" onclick="checkOffloads('."this,'$balnum','$sparetype'".');" /><span id="loadbalancing_targettxt_'.$balnum.'_'.$sparetype.'_'.$i.'">&nbsp;'.$chkboxval.
 9345:                     '</span></label></span></td>';
 9346:                 my $rem = $i%($numinrow);
 9347:                 if ($rem == 0) {
 9348:                     if (($i > 0) && ($i < $numspares-1)) {
 9349:                         $targettable .= '</tr>';
 9350:                     }
 9351:                     if ($i < $numspares-1) {
 9352:                         $targettable .= '<tr>';
 9353:                     }
 9354:                 }
 9355:             }
 9356:             if ($targettable ne '') {
 9357:                 my $rem = $numspares%($numinrow);
 9358:                 my $colsleft = $numinrow - $rem;
 9359:                 if ($colsleft > 1 ) {
 9360:                     $targettable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9361:                                     '&nbsp;</td>';
 9362:                 } elsif ($colsleft == 1) {
 9363:                     $targettable .= '<td class="LC_left_item">&nbsp;</td>';
 9364:                 }
 9365:                 $datatable .=  '<i>'.$typetitles{$sparetype}.'</i><br />'.
 9366:                                '<table><tr>'.$targettable.'</tr></table><br />';
 9367:             }
 9368:             $hostherechecked{$sparetype} = '';
 9369:             if (ref($currtargets{$lonhost}) eq 'HASH') {
 9370:                 if (ref($currtargets{$lonhost}{$sparetype}) eq 'ARRAY') {
 9371:                     if (grep(/^\Q$lonhost\E$/,@{$currtargets{$lonhost}{$sparetype}})) {
 9372:                         $hostherechecked{$sparetype} = ' checked="checked"';
 9373:                         $hostherechecked{'no'} = '';
 9374:                     }
 9375:                 }
 9376:             }
 9377:         }
 9378:         if ($currcookies{$lonhost}) {
 9379:             %balcookiechecked = (
 9380:                                     yes => ' checked="checked"',
 9381:                                 );
 9382:         }
 9383:         $datatable .= &mt('Hosting on balancer itself').'<br />'.
 9384:                       '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" value="no"'.
 9385:                       $hostherechecked{'no'}.' />'.&mt('No').'</label><br />';
 9386:         foreach my $sparetype (@sparestypes) {
 9387:             $datatable .= '<label><input type="radio" name="loadbalancing_target_'.$balnum.'_hosthere" '.
 9388:                           'value="'.$sparetype.'"'.$hostherechecked{$sparetype}.' /><i>'.$typetitles{$sparetype}.
 9389:                           '</i></label><br />';
 9390:         }
 9391:         $datatable .= &mt('Use balancer cookie').'<br />'.
 9392:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="1"'.
 9393:                       $balcookiechecked{'yes'}.' />'.&mt('Yes').'</label><br />'.
 9394:                       '<label><input type="radio" name="loadbalancing_cookie_'.$balnum.'" value="0"'.
 9395:                       $balcookiechecked{'no'}.' />'.&mt('No').'</label><br />'.
 9396:                       '</div></td></tr>'.
 9397:                       &loadbalancing_rules($dom,$intdom,$currrules{$lonhost},
 9398:                                            $othertitle,$usertypes,$types,\%servers,
 9399:                                            \%currbalancer,$lonhost,
 9400:                                            $targets_div_style,$homedom_div_style,
 9401:                                            $css_class[$cssidx],$balnum,$islast);
 9402:         $$rowtotal += $rownum;
 9403:         $balnum ++;
 9404:     }
 9405:     $datatable .= '<input type="hidden" name="loadbalancing_total" id="loadbalancing_total" value="'.$balnum.'" />';
 9406:     return $datatable;
 9407: }
 9408: 
 9409: sub get_loadbalancers_config {
 9410:     my ($servers,$existing,$currbalancer,$currtargets,$currrules,$currcookies) = @_;
 9411:     return unless ((ref($servers) eq 'HASH') &&
 9412:                    (ref($existing) eq 'HASH') && (ref($currbalancer) eq 'HASH') &&
 9413:                    (ref($currtargets) eq 'HASH') && (ref($currrules) eq 'HASH') &&
 9414:                    (ref($currcookies) eq 'HASH'));
 9415:     if (keys(%{$existing}) > 0) {
 9416:         my $oldlonhost;
 9417:         foreach my $key (sort(keys(%{$existing}))) {
 9418:             if ($key eq 'lonhost') {
 9419:                 $oldlonhost = $existing->{'lonhost'};
 9420:                 $currbalancer->{$oldlonhost} = 1;
 9421:             } elsif ($key eq 'targets') {
 9422:                 if ($oldlonhost) {
 9423:                     $currtargets->{$oldlonhost} = $existing->{'targets'};
 9424:                 }
 9425:             } elsif ($key eq 'rules') {
 9426:                 if ($oldlonhost) {
 9427:                     $currrules->{$oldlonhost} = $existing->{'rules'};
 9428:                 }
 9429:             } elsif (ref($existing->{$key}) eq 'HASH') {
 9430:                 $currbalancer->{$key} = 1;
 9431:                 $currtargets->{$key} = $existing->{$key}{'targets'};
 9432:                 $currrules->{$key} = $existing->{$key}{'rules'};
 9433:                 if ($existing->{$key}{'cookie'}) {
 9434:                     $currcookies->{$key} = 1;
 9435:                 }
 9436:             }
 9437:         }
 9438:     } else {
 9439:         my ($balancerref,$targetsref) =
 9440:                 &Apache::lonnet::get_lonbalancer_config($servers);
 9441:         if ((ref($balancerref) eq 'HASH') && (ref($targetsref) eq 'HASH')) {
 9442:             foreach my $server (sort(keys(%{$balancerref}))) {
 9443:                 $currbalancer->{$server} = 1;
 9444:                 $currtargets->{$server} = $targetsref->{$server};
 9445:             }
 9446:         }
 9447:     }
 9448:     return;
 9449: }
 9450: 
 9451: sub loadbalancing_rules {
 9452:     my ($dom,$intdom,$currrules,$othertitle,$usertypes,$types,$servers,
 9453:         $currbalancer,$lonhost,$targets_div_style,$homedom_div_style,
 9454:         $css_class,$balnum,$islast) = @_;
 9455:     my $output;
 9456:     my $num = 0;
 9457:     my ($alltypes,$othertypes,$titles) =
 9458:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
 9459:     if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH'))  {
 9460:         foreach my $type (@{$alltypes}) {
 9461:             $num ++;
 9462:             my $current;
 9463:             if (ref($currrules) eq 'HASH') {
 9464:                 $current = $currrules->{$type};
 9465:             }
 9466:             if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9467:                 if ($dom ne &Apache::lonnet::host_domain($lonhost)) {
 9468:                     $current = '';
 9469:                 }
 9470:             }
 9471:             $output .= &loadbalance_rule_row($type,$titles->{$type},$current,
 9472:                                              $servers,$currbalancer,$lonhost,$dom,
 9473:                                              $targets_div_style,$homedom_div_style,
 9474:                                              $css_class,$balnum,$num,$islast);
 9475:         }
 9476:     }
 9477:     return $output;
 9478: }
 9479: 
 9480: sub loadbalancing_titles {
 9481:     my ($dom,$intdom,$usertypes,$types) = @_;
 9482:     my %othertypes = (
 9483:            '_LC_adv'         => &mt('Advanced users from [_1]',$dom),
 9484:            '_LC_author'      => &mt('Users from [_1] with author role',$dom),
 9485:            '_LC_internetdom' => &mt('Users not from [_1], but from [_2]',$dom,$intdom),
 9486:            '_LC_external'    => &mt('Users not from [_1]',$intdom),
 9487:            '_LC_ipchangesso' => &mt('SSO users from [_1], with IP mismatch',$dom),
 9488:            '_LC_ipchange'    => &mt('Non-SSO users with IP mismatch'),
 9489:                      );
 9490:     my @alltypes = ('_LC_adv','_LC_author','_LC_internetdom','_LC_external','_LC_ipchangesso','_LC_ipchange');
 9491:     my @available;
 9492:     if (ref($types) eq 'ARRAY') {
 9493:         @available = @{$types};
 9494:     }
 9495:     unless (grep(/^default$/,@available)) {
 9496:         push(@available,'default');
 9497:     }
 9498:     unshift(@alltypes,@available);
 9499:     my %titles;
 9500:     foreach my $type (@alltypes) {
 9501:         if ($type =~ /^_LC_/) {
 9502:             $titles{$type} = $othertypes{$type};
 9503:         } elsif ($type eq 'default') {
 9504:             $titles{$type} = &mt('All users from [_1]',$dom);
 9505:             if (ref($types) eq 'ARRAY') {
 9506:                 if (@{$types} > 0) {
 9507:                     $titles{$type} = &mt('Other users from [_1]',$dom);
 9508:                 }
 9509:             }
 9510:         } elsif (ref($usertypes) eq 'HASH') {
 9511:             $titles{$type} = $usertypes->{$type};
 9512:         }
 9513:     }
 9514:     return (\@alltypes,\%othertypes,\%titles);
 9515: }
 9516: 
 9517: sub loadbalance_rule_row {
 9518:     my ($type,$title,$current,$servers,$currbalancer,$lonhost,$dom,
 9519:         $targets_div_style,$homedom_div_style,$css_class,$balnum,$num,$islast) = @_;
 9520:     my @rulenames;
 9521:     my %ruletitles = &offloadtype_text();
 9522:     if (($type eq '_LC_ipchangesso') || ($type eq '_LC_ipchange')) {
 9523:         @rulenames = ('balancer','offloadedto','specific');
 9524:     } else {
 9525:         @rulenames = ('default','homeserver');
 9526:         if ($type eq '_LC_external') {
 9527:             push(@rulenames,'externalbalancer');
 9528:         } else {
 9529:             push(@rulenames,'specific');
 9530:         }
 9531:         push(@rulenames,'none');
 9532:     }
 9533:     my $style = $targets_div_style;
 9534:     if (($type eq '_LC_external') || ($type eq '_LC_internetdom')) {
 9535:         $style = $homedom_div_style;
 9536:     }
 9537:     my $space;
 9538:     if ($islast && $num == 1) {
 9539:         $space = '<div style="display:inline-block;">&nbsp;</div>';
 9540:     }
 9541:     my $output =
 9542:         '<tr class="'.$css_class.'" id="balanceruletr_'.$balnum.'_'.$num.'"><td style="vertical-align: top">'.$space.
 9543:         '<div id="balanceruletitle_'.$balnum.'_'.$type.'" style="'.$style.'">'.$title.'</div></td>'."\n".
 9544:         '<td valaign="top">'.$space.
 9545:         '<div id="balancerule_'.$balnum.'_'.$type.'" style="'.$style.'">'."\n";
 9546:     for (my $i=0; $i<@rulenames; $i++) {
 9547:         my $rule = $rulenames[$i];
 9548:         my ($checked,$extra);
 9549:         if ($rulenames[$i] eq 'default') {
 9550:             $rule = '';
 9551:         }
 9552:         if ($rulenames[$i] eq 'specific') {
 9553:             if (ref($servers) eq 'HASH') {
 9554:                 my $default;
 9555:                 if (($current ne '') && (exists($servers->{$current}))) {
 9556:                     $checked = ' checked="checked"';
 9557:                 }
 9558:                 unless ($checked) {
 9559:                     $default = ' selected="selected"';
 9560:                 }
 9561:                 $extra =
 9562:                     ':&nbsp;<select name="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9563:                     '" id="loadbalancing_singleserver_'.$balnum.'_'.$type.
 9564:                     '" onchange="singleServerToggle('."'$balnum','$type'".')">'."\n".
 9565:                     '<option value=""'.$default.'></option>'."\n";
 9566:                 foreach my $server (sort(keys(%{$servers}))) {
 9567:                     if (ref($currbalancer) eq 'HASH') {
 9568:                         next if (exists($currbalancer->{$server}));
 9569:                     }
 9570:                     my $selected;
 9571:                     if ($server eq $current) {
 9572:                         $selected = ' selected="selected"';
 9573:                     }
 9574:                     $extra .= '<option value="'.$server.'"'.$selected.'>'.$server.'</option>';
 9575:                 }
 9576:                 $extra .= '</select>';
 9577:             }
 9578:         } elsif ($rule eq $current) {
 9579:             $checked = ' checked="checked"';
 9580:         }
 9581:         $output .= '<span class="LC_nobreak"><label>'.
 9582:                    '<input type="radio" name="loadbalancing_rules_'.$balnum.'_'.$type.
 9583:                    '" id="loadbalancing_rules_'.$balnum.'_'.$type.'_'.$i.'" value="'.
 9584:                    $rule.'" onclick="balanceruleChange('."this.form,'$balnum','$type'".
 9585:                    ')"'.$checked.' />&nbsp;';
 9586:         if (($rulenames[$i] eq 'specific') && ($type =~ /^_LC_ipchange/)) {
 9587:             $output .= $ruletitles{'particular'};
 9588:         } else {
 9589:             $output .= $ruletitles{$rulenames[$i]};
 9590:         }
 9591:         $output .= '</label>'.$extra.'</span><br />'."\n";
 9592:     }
 9593:     $output .= '</div></td></tr>'."\n";
 9594:     return $output;
 9595: }
 9596: 
 9597: sub offloadtype_text {
 9598:     my %ruletitles = &Apache::lonlocal::texthash (
 9599:            'default'          => 'Offloads to default destinations',
 9600:            'homeserver'       => "Offloads to user's home server",
 9601:            'externalbalancer' => "Offloads to Load Balancer in user's domain",
 9602:            'specific'         => 'Offloads to specific server',
 9603:            'none'             => 'No offload',
 9604:            'balancer'         => 'Session hosted on Load Balancer, after re-authentication',
 9605:            'offloadedto'      => 'Session hosted on offload server, after re-authentication',
 9606:            'particular'       => 'Session hosted (after re-auth) on server:',
 9607:     );
 9608:     return %ruletitles;
 9609: }
 9610: 
 9611: sub sparestype_titles {
 9612:     my %typestitles = &Apache::lonlocal::texthash (
 9613:                           'primary' => 'primary',
 9614:                           'default' => 'default',
 9615:                       );
 9616:     return %typestitles;
 9617: }
 9618: 
 9619: sub contact_titles {
 9620:     my %titles = &Apache::lonlocal::texthash (
 9621:                    'supportemail'    => 'Support E-mail address',
 9622:                    'adminemail'      => 'Default Server Admin E-mail address',
 9623:                    'errormail'       => 'Error reports to be e-mailed to',
 9624:                    'packagesmail'    => 'Package update alerts to be e-mailed to',
 9625:                    'helpdeskmail'    => "Helpdesk requests from all users in this domain",
 9626:                    'otherdomsmail'   => 'Helpdesk requests from users in other (unconfigured) domains',
 9627:                    'lonstatusmail'   => 'E-mail from nightly status check (warnings/errors)',
 9628:                    'requestsmail'    => 'E-mail from course requests requiring approval',
 9629:                    'updatesmail'     => 'E-mail from nightly check of LON-CAPA module integrity/updates',
 9630:                    'idconflictsmail' => 'E-mail from bi-nightly check for multiple users sharing same student/employee ID',
 9631:                    'hostipmail'      => 'E-mail from nightly check of hostname/IP network changes',
 9632:                    'errorthreshold'  => 'Error count threshold for status e-mail to admin(s)',
 9633:                    'errorsysmail'    => 'Error count threshold for e-mail to developer group',
 9634:                    'errorweights'    => 'Weights used to compute error count',
 9635:                    'errorexcluded'   => 'Servers with unsent updates excluded from count',
 9636:                  );
 9637:     my %short_titles = &Apache::lonlocal::texthash (
 9638:                            adminemail   => 'Admin E-mail address',
 9639:                            supportemail => 'Support E-mail',
 9640:                        );   
 9641:     return (\%titles,\%short_titles);
 9642: }
 9643: 
 9644: sub helpform_fields {
 9645:     my %titles =  &Apache::lonlocal::texthash (
 9646:                        'username'   => 'Name',
 9647:                        'user'       => 'Username/domain',
 9648:                        'phone'      => 'Phone',
 9649:                        'cc'         => 'Cc e-mail',
 9650:                        'course'     => 'Course Details',
 9651:                        'section'    => 'Sections',
 9652:                        'screenshot' => 'File upload',
 9653:     );
 9654:     my @fields = ('username','phone','user','course','section','cc','screenshot');
 9655:     my %possoptions = (
 9656:                         username     => ['yes','no','req'],
 9657:                         phone        => ['yes','no','req'],
 9658:                         user         => ['yes','no'],
 9659:                         cc           => ['yes','no'],
 9660:                         course       => ['yes','no'],
 9661:                         section      => ['yes','no'],
 9662:                         screenshot   => ['yes','no'],
 9663:                       );
 9664:     my %fieldoptions = &Apache::lonlocal::texthash (
 9665:                          'yes'  => 'Optional',
 9666:                          'req'  => 'Required',
 9667:                          'no'   => "Not shown",
 9668:     );
 9669:     return (\@fields,\%titles,\%fieldoptions,\%possoptions);
 9670: }
 9671: 
 9672: sub tool_titles {
 9673:     my %titles = &Apache::lonlocal::texthash (
 9674:                      aboutme    => 'Personal web page',
 9675:                      blog       => 'Blog',
 9676:                      webdav     => 'WebDAV',
 9677:                      portfolio  => 'Portfolio',
 9678:                      official   => 'Official courses (with institutional codes)',
 9679:                      unofficial => 'Unofficial courses',
 9680:                      community  => 'Communities',
 9681:                      textbook   => 'Textbook courses',
 9682:                      placement  => 'Placement tests',
 9683:                  );
 9684:     return %titles;
 9685: }
 9686: 
 9687: sub courserequest_titles {
 9688:     my %titles = &Apache::lonlocal::texthash (
 9689:                                    official   => 'Official',
 9690:                                    unofficial => 'Unofficial',
 9691:                                    community  => 'Communities',
 9692:                                    textbook   => 'Textbook',
 9693:                                    placement  => 'Placement tests',
 9694:                                    lti        => 'LTI Provider',
 9695:                                    norequest  => 'Not allowed',
 9696:                                    approval   => 'Approval by DC',
 9697:                                    validate   => 'With validation',
 9698:                                    autolimit  => 'Numerical limit',
 9699:                                    unlimited  => '(blank for unlimited)',
 9700:                  );
 9701:     return %titles;
 9702: }
 9703: 
 9704: sub authorrequest_titles {
 9705:     my %titles = &Apache::lonlocal::texthash (
 9706:                                    norequest  => 'Not allowed',
 9707:                                    approval   => 'Approval by Dom. Coord.',
 9708:                                    automatic  => 'Automatic approval',
 9709:                  );
 9710:     return %titles;
 9711: }
 9712: 
 9713: sub courserequest_conditions {
 9714:     my %conditions = &Apache::lonlocal::texthash (
 9715:        approval    => '(Processing of request subject to approval by Domain Coordinator).',
 9716:        validate   => '(Processing of request subject to institutional validation).',
 9717:                  );
 9718:     return %conditions;
 9719: }
 9720: 
 9721: 
 9722: sub print_usercreation {
 9723:     my ($position,$dom,$settings,$rowtotal) = @_;
 9724:     my $numinrow = 4;
 9725:     my $datatable;
 9726:     if ($position eq 'top') {
 9727:         $$rowtotal ++;
 9728:         my $rowcount = 0;
 9729:         my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($dom,'username');
 9730:         if (ref($rules) eq 'HASH') {
 9731:             if (keys(%{$rules}) > 0) {
 9732:                 $datatable .= &user_formats_row('username',$settings,$rules,
 9733:                                                 $ruleorder,$numinrow,$rowcount);
 9734:                 $$rowtotal ++;
 9735:                 $rowcount ++;
 9736:             }
 9737:         }
 9738:         my ($idrules,$idruleorder) = &Apache::lonnet::inst_userrules($dom,'id');
 9739:         if (ref($idrules) eq 'HASH') {
 9740:             if (keys(%{$idrules}) > 0) {
 9741:                 $datatable .= &user_formats_row('id',$settings,$idrules,
 9742:                                                 $idruleorder,$numinrow,$rowcount);
 9743:                 $$rowtotal ++;
 9744:                 $rowcount ++;
 9745:             }
 9746:         }
 9747:         if ($rowcount == 0) {
 9748:             $datatable .= '<tr><td colspan="2">'.&mt('No format rules have been defined for usernames or IDs in this domain.').'</td></tr>';  
 9749:             $$rowtotal ++;
 9750:             $rowcount ++;
 9751:         }
 9752:     } elsif ($position eq 'middle') {
 9753:         my @creators = ('author','course','requestcrs');
 9754:         my ($rules,$ruleorder) =
 9755:             &Apache::lonnet::inst_userrules($dom,'username');
 9756:         my %lt = &usercreation_types();
 9757:         my %checked;
 9758:         if (ref($settings) eq 'HASH') {
 9759:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 9760:                 foreach my $item (@creators) {
 9761:                     $checked{$item} = $settings->{'cancreate'}{$item};
 9762:                 }
 9763:             } elsif (ref($settings->{'cancreate'}) eq 'ARRAY') {
 9764:                 foreach my $item (@creators) {
 9765:                     if (grep(/^\Q$item\E$/,@{$settings->{'cancreate'}})) {
 9766:                         $checked{$item} = 'none';
 9767:                     }
 9768:                 }
 9769:             }
 9770:         }
 9771:         my $rownum = 0;
 9772:         foreach my $item (@creators) {
 9773:             $rownum ++;
 9774:             if ($checked{$item} eq '') {
 9775:                 $checked{$item} = 'any';
 9776:             }
 9777:             my $css_class;
 9778:             if ($rownum%2) {
 9779:                 $css_class = '';
 9780:             } else {
 9781:                 $css_class = ' class="LC_odd_row" ';
 9782:             }
 9783:             $datatable .= '<tr'.$css_class.'>'.
 9784:                          '<td><span class="LC_nobreak">'.$lt{$item}.
 9785:                          '</span></td><td style="text-align: right">';
 9786:             my @options = ('any');
 9787:             if (ref($rules) eq 'HASH') {
 9788:                 if (keys(%{$rules}) > 0) {
 9789:                     push(@options,('official','unofficial'));
 9790:                 }
 9791:             }
 9792:             push(@options,'none');
 9793:             foreach my $option (@options) {
 9794:                 my $type = 'radio';
 9795:                 my $check = ' ';
 9796:                 if ($checked{$item} eq $option) {
 9797:                     $check = ' checked="checked" ';
 9798:                 } 
 9799:                 $datatable .= '<span class="LC_nobreak"><label>'.
 9800:                               '<input type="'.$type.'" name="can_createuser_'.
 9801:                               $item.'" value="'.$option.'"'.$check.'/>&nbsp;'.
 9802:                               $lt{$option}.'</label>&nbsp;&nbsp;</span>';
 9803:             }
 9804:             $datatable .= '</td></tr>';
 9805:         }
 9806:     } else {
 9807:         my @contexts = ('author','course','domain');
 9808:         my @authtypes = ('int','krb4','krb5','loc','lti');
 9809:         my %checked;
 9810:         if (ref($settings) eq 'HASH') {
 9811:             if (ref($settings->{'authtypes'}) eq 'HASH') {
 9812:                 foreach my $item (@contexts) {
 9813:                     if (ref($settings->{'authtypes'}{$item}) eq 'HASH') {
 9814:                         foreach my $auth (@authtypes) {
 9815:                             if ($settings->{'authtypes'}{$item}{$auth}) {
 9816:                                 $checked{$item}{$auth} = ' checked="checked" ';
 9817:                             }
 9818:                         }
 9819:                     }
 9820:                 }
 9821:             }
 9822:         } else {
 9823:             foreach my $item (@contexts) {
 9824:                 foreach my $auth (@authtypes) {
 9825:                     $checked{$item}{$auth} = ' checked="checked" ';
 9826:                 }
 9827:             }
 9828:         }
 9829:         my %title = &context_names();
 9830:         my %authname = &authtype_names();
 9831:         my $rownum = 0;
 9832:         my $css_class; 
 9833:         foreach my $item (@contexts) {
 9834:             if ($rownum%2) {
 9835:                 $css_class = '';
 9836:             } else {
 9837:                 $css_class = ' class="LC_odd_row" ';
 9838:             }
 9839:             $datatable .=   '<tr'.$css_class.'>'.
 9840:                             '<td>'.$title{$item}.
 9841:                             '</td><td class="LC_left_item">'.
 9842:                             '<span class="LC_nobreak">';
 9843:             foreach my $auth (@authtypes) {
 9844:                 $datatable .= '<label>'. 
 9845:                               '<input type="checkbox" name="'.$item.'_auth" '.
 9846:                               $checked{$item}{$auth}.' value="'.$auth.'" />'.
 9847:                               $authname{$auth}.'</label>&nbsp;';
 9848:             }
 9849:             $datatable .= '</span></td></tr>';
 9850:             $rownum ++;
 9851:         }
 9852:         $$rowtotal += $rownum;
 9853:     }
 9854:     return $datatable;
 9855: }
 9856: 
 9857: sub print_selfcreation {
 9858:     my ($position,$dom,$settings,$rowtotal) = @_;
 9859:     my (@selfcreate,$createsettings,$processing,$emailoptions,$emailverified,
 9860:         $emaildomain,$datatable);
 9861:     if (ref($settings) eq 'HASH') {
 9862:         if (ref($settings->{'cancreate'}) eq 'HASH') {
 9863:             $createsettings = $settings->{'cancreate'};
 9864:             if (ref($createsettings) eq 'HASH') {
 9865:                 if (ref($createsettings->{'selfcreate'}) eq 'ARRAY') {
 9866:                     @selfcreate = @{$createsettings->{'selfcreate'}};
 9867:                 } elsif ($createsettings->{'selfcreate'} ne '') {
 9868:                     if ($settings->{'cancreate'}{'selfcreate'} eq 'any') {
 9869:                         @selfcreate = ('email','login','sso');
 9870:                     } elsif ($createsettings->{'selfcreate'} ne 'none') {
 9871:                         @selfcreate = ($createsettings->{'selfcreate'});
 9872:                     }
 9873:                 }
 9874:                 if (ref($createsettings->{'selfcreateprocessing'}) eq 'HASH') {
 9875:                     $processing = $createsettings->{'selfcreateprocessing'};
 9876:                 }
 9877:                 if (ref($createsettings->{'emailoptions'}) eq 'HASH') {
 9878:                     $emailoptions = $createsettings->{'emailoptions'};
 9879:                 }
 9880:                 if (ref($createsettings->{'emailverified'}) eq 'HASH') {
 9881:                     $emailverified = $createsettings->{'emailverified'};
 9882:                 }
 9883:                 if (ref($createsettings->{'emaildomain'}) eq 'HASH') {
 9884:                     $emaildomain = $createsettings->{'emaildomain'};
 9885:                 }
 9886:             }
 9887:         }
 9888:     }
 9889:     my %radiohash;
 9890:     my $numinrow = 4;
 9891:     map { $radiohash{'cancreate_'.$_} = 1; } @selfcreate;
 9892:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
 9893:     if ($position eq 'top') {
 9894:         my %choices = &Apache::lonlocal::texthash (
 9895:                                                       cancreate_login      => 'Institutional Login',
 9896:                                                       cancreate_sso        => 'Institutional Single Sign On',
 9897:                                                   );
 9898:         my @toggles = sort(keys(%choices));
 9899:         my %defaultchecked = (
 9900:                                'cancreate_login' => 'off',
 9901:                                'cancreate_sso'   => 'off',
 9902:                              );
 9903:         my ($onclick,$itemcount);
 9904:         ($datatable,$itemcount) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9905:                                                      \%choices,$itemcount,$onclick);
 9906:         $$rowtotal += $itemcount;
 9907:         
 9908:         if (ref($usertypes) eq 'HASH') {
 9909:             if (keys(%{$usertypes}) > 0) {
 9910:                 $datatable .= &insttypes_row($createsettings,$types,$usertypes,
 9911:                                              $dom,$numinrow,$othertitle,
 9912:                                              'statustocreate',$rowtotal);
 9913:                 $$rowtotal ++;
 9914:             }
 9915:         }
 9916:         my @fields = ('lastname','firstname','middlename','permanentemail','id','inststatus');
 9917:         my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
 9918:         $fieldtitles{'inststatus'} = &mt('Institutional status');
 9919:         my $rem;
 9920:         my $numperrow = 2;
 9921:         my $css_class = $$rowtotal%2?' class="LC_odd_row"':'';
 9922:         $datatable .= '<tr'.$css_class.'>'.
 9923:                      '<td class="LC_left_item">'.&mt('Mapping of Shibboleth environment variable names to user data fields (SSO auth)').'</td>'.
 9924:                      '<td class="LC_left_item">'."\n".
 9925:                      '<table>'."\n";
 9926:         for (my $i=0; $i<@fields; $i++) {
 9927:             $rem = $i%($numperrow);
 9928:             if ($rem == 0) {
 9929:                 if ($i > 0) {
 9930:                     $datatable .= '</tr>';
 9931:                 }
 9932:                 $datatable .= '<tr>';
 9933:             }
 9934:             my $currval;
 9935:             if (ref($createsettings) eq 'HASH') {
 9936:                 if (ref($createsettings->{'shibenv'}) eq 'HASH') {
 9937:                     $currval = $createsettings->{'shibenv'}{$fields[$i]};
 9938:                 }
 9939:             }
 9940:             $datatable .= '<td class="LC_left_item">'.
 9941:                           '<span class="LC_nobreak">'.
 9942:                           '<input type="text" name="shibenv_'.$fields[$i].'" '.
 9943:                           'value="'.$currval.'" size="10" />&nbsp;'.
 9944:                           $fieldtitles{$fields[$i]}.'</span></td>';
 9945:         }
 9946:         my $colsleft = $numperrow - $rem;
 9947:         if ($colsleft > 1 ) {
 9948:             $datatable .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
 9949:                          '&nbsp;</td>';
 9950:         } elsif ($colsleft == 1) {
 9951:             $datatable .= '<td class="LC_left_item">&nbsp;</td>';
 9952:         }
 9953:         $datatable .= '</tr></table></td></tr>';
 9954:         $$rowtotal ++;
 9955:     } elsif ($position eq 'middle') {
 9956:         my %domconf = &Apache::lonnet::get_dom('configuration',['usermodification'],$dom);
 9957:         my @posstypes;
 9958:         if (ref($types) eq 'ARRAY') {
 9959:             @posstypes = @{$types};
 9960:         }
 9961:         unless (grep(/^default$/,@posstypes)) {
 9962:             push(@posstypes,'default');
 9963:         }
 9964:         my %usertypeshash;
 9965:         if (ref($usertypes) eq 'HASH') {
 9966:             %usertypeshash = %{$usertypes};
 9967:         }
 9968:         $usertypeshash{'default'} = $othertitle;
 9969:         foreach my $status (@posstypes) {
 9970:             $datatable .= &modifiable_userdata_row('selfcreate',$status,$domconf{'usermodification'},
 9971:                                                    $numinrow,$$rowtotal,\%usertypeshash);
 9972:             $$rowtotal ++;
 9973:         }
 9974:     } else {
 9975:         my %choices = &Apache::lonlocal::texthash (
 9976:                           'cancreate_email' => 'Non-institutional username (via e-mail verification)',
 9977:                                                   );
 9978:         my @toggles = sort(keys(%choices));
 9979:         my %defaultchecked = (
 9980:                                'cancreate_email' => 'off',
 9981:                              );
 9982:         my $customclass = 'LC_selfcreate_email';
 9983:         my $classprefix = 'LC_canmodify_emailusername_';
 9984:         my $optionsprefix = 'LC_options_emailusername_';
 9985:         my $display = 'none';
 9986:         my $rowstyle = 'display:none';
 9987:         if (grep(/^\Qemail\E$/,@selfcreate)) {
 9988:             $display = 'block';
 9989:             $rowstyle = 'display:table-row';
 9990:         }
 9991:         my $onclick = "toggleRows(this.form,'cancreate_email','selfassign','$customclass','$classprefix','$optionsprefix');";
 9992:         ($datatable,$$rowtotal) = &radiobutton_prefs(\%radiohash,\@toggles,\%defaultchecked,
 9993:                                                      \%choices,$$rowtotal,$onclick);
 9994:         $datatable .= &print_requestmail($dom,'selfcreation',$createsettings,$rowtotal,$customclass,
 9995:                                          $rowstyle);
 9996:         $$rowtotal ++;
 9997:         $datatable .= &captcha_choice('cancreate',$createsettings,$$rowtotal,$customclass,
 9998:                                       $rowstyle);
 9999:         $$rowtotal ++;
10000:         my (@ordered,@posstypes,%usertypeshash);
10001:         my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
10002:         my ($emailrules,$emailruleorder) =
10003:             &Apache::lonnet::inst_userrules($dom,'email');
10004:         my $primary_id = &Apache::lonnet::domain($dom,'primary');
10005:         my $intdom = &Apache::lonnet::internet_dom($primary_id);
10006:         if (ref($types) eq 'ARRAY') {
10007:             @posstypes = @{$types};
10008:         }
10009:         if (@posstypes) {
10010:             unless (grep(/^default$/,@posstypes)) {
10011:                 push(@posstypes,'default');
10012:             }
10013:             if (ref($usertypes) eq 'HASH') {
10014:                 %usertypeshash = %{$usertypes};
10015:             }
10016:             my $currassign;
10017:             if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
10018:                 $currassign = {
10019:                                   selfassign => $domdefaults{'inststatusguest'},
10020:                               };
10021:                 @ordered = @{$domdefaults{'inststatusguest'}};
10022:             } else {
10023:                 $currassign = { selfassign => [] };
10024:             }
10025:             my $onclicktypes = "toggleDataRow(this.form,'selfassign','$customclass','$optionsprefix',);".
10026:                                "toggleDataRow(this.form,'selfassign','$customclass','$classprefix',1);";
10027:             $datatable .= &insttypes_row($currassign,$types,$usertypes,$dom,
10028:                                          $numinrow,$othertitle,'selfassign',
10029:                                          $rowtotal,$onclicktypes,$customclass,
10030:                                          $rowstyle);
10031:             $$rowtotal ++;
10032:             $usertypeshash{'default'} = $othertitle;
10033:             foreach my $status (@posstypes) {
10034:                 my $css_class;
10035:                 if ($$rowtotal%2) {
10036:                     $css_class = 'LC_odd_row ';
10037:                 }
10038:                 $css_class .= $customclass;
10039:                 my $rowid = $optionsprefix.$status;
10040:                 my $hidden = 1;
10041:                 my $currstyle = 'display:none';
10042:                 if (grep(/^\Q$status\E$/,@ordered)) {
10043:                     $currstyle = $rowstyle;
10044:                     $hidden = 0; 
10045:                 }
10046:                 $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10047:                                              $emailrules,$emailruleorder,$settings,$status,$rowid,
10048:                                              $usertypeshash{$status},$css_class,$currstyle,$intdom);
10049:                 unless ($hidden) {
10050:                     $$rowtotal ++;
10051:                 }
10052:             }
10053:         } else {
10054:             my $css_class;
10055:             if ($$rowtotal%2) {
10056:                 $css_class = 'LC_odd_row ';
10057:             }
10058:             $css_class .= $customclass;
10059:             $usertypeshash{'default'} = $othertitle;
10060:             $datatable .= &noninst_users($processing,$emailverified,$emailoptions,$emaildomain,
10061:                                          $emailrules,$emailruleorder,$settings,'default','',
10062:                                          $othertitle,$css_class,$rowstyle,$intdom);
10063:             $$rowtotal ++;
10064:         }
10065:         my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
10066:         $numinrow = 1;
10067:         if (@posstypes) {
10068:             foreach my $status (@posstypes) {
10069:                 my $rowid = $classprefix.$status;
10070:                 my $datarowstyle = 'display:none';
10071:                 if (grep(/^\Q$status\E$/,@ordered)) { 
10072:                     $datarowstyle = $rowstyle; 
10073:                 }
10074:                 $datatable .= &modifiable_userdata_row('cancreate','emailusername_'.$status,$settings,
10075:                                                        $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10076:                                                        $infotitles,$rowid,$customclass,$datarowstyle);
10077:                 unless ($datarowstyle eq 'display:none') {
10078:                     $$rowtotal ++;
10079:                 }
10080:             }
10081:         } else {
10082:             $datatable .= &modifiable_userdata_row('cancreate','emailusername_default',$settings,
10083:                                                    $numinrow,$$rowtotal,\%usertypeshash,$infofields,
10084:                                                    $infotitles,'',$customclass,$rowstyle);
10085:         }
10086:     }
10087:     return $datatable;
10088: }
10089: 
10090: sub selfcreate_javascript {
10091:     return <<"ENDSCRIPT";
10092: 
10093: <script type="text/javascript">
10094: // <![CDATA[
10095: 
10096: function toggleRows(form,radio,checkbox,target,prefix,altprefix) {
10097:     var x = document.getElementsByClassName(target);
10098:     var insttypes = 0;
10099:     var insttypeRegExp = new RegExp(prefix);
10100:     if ((x.length != undefined) && (x.length > 0)) {
10101:         if (form.elements[radio].length != undefined) {
10102:             for (var i=0; i<form.elements[radio].length; i++) {
10103:                 if (form.elements[radio][i].checked) {
10104:                     if (form.elements[radio][i].value == 1) {
10105:                         for (var j=0; j<x.length; j++) {
10106:                             if (x[j].id == 'undefined') {
10107:                                 x[j].style.display = 'table-row';
10108:                             } else if (insttypeRegExp.test(x[j].id)) {
10109:                                 insttypes ++;
10110:                             } else {
10111:                                 x[j].style.display = 'table-row';
10112:                             }
10113:                         }
10114:                     } else {
10115:                         for (var j=0; j<x.length; j++) {
10116:                             x[j].style.display = 'none';
10117:                         }
10118:                     }
10119:                     break;
10120:                 }
10121:             }
10122:             if (insttypes > 0) {
10123:                 toggleDataRow(form,checkbox,target,altprefix);
10124:                 toggleDataRow(form,checkbox,target,prefix,1);
10125:             }
10126:         }
10127:     }
10128:     return;
10129: }
10130: 
10131: function toggleDataRow(form,checkbox,target,prefix,docount) {
10132:     if (form.elements[checkbox].length != undefined) {
10133:         var count = 0;
10134:         if (docount) {
10135:             for (var i=0; i<form.elements[checkbox].length; i++) {
10136:                 if (form.elements[checkbox][i].checked) {
10137:                     count ++;
10138:                 }
10139:             }
10140:         }
10141:         for (var i=0; i<form.elements[checkbox].length; i++) {
10142:             var type = form.elements[checkbox][i].value;
10143:             if (document.getElementById(prefix+type)) {
10144:                 if (form.elements[checkbox][i].checked) {
10145:                     document.getElementById(prefix+type).style.display = 'table-row';
10146:                     if (count % 2 == 1) {
10147:                         document.getElementById(prefix+type).className = target+' LC_odd_row';
10148:                     } else {
10149:                         document.getElementById(prefix+type).className = target;
10150:                     }
10151:                     count ++;
10152:                 } else {
10153:                     document.getElementById(prefix+type).style.display = 'none';
10154:                 }
10155:             }
10156:         }
10157:     }
10158:     return;
10159: }
10160: 
10161: function toggleEmailOptions(form,radio,prefix,altprefix,status) {
10162:     var caller = radio+'_'+status;
10163:     if (form.elements[caller].length != undefined) {
10164:         for (var i=0; i<form.elements[caller].length; i++) {
10165:             if (form.elements[caller][i].checked) {
10166:                 if (document.getElementById(altprefix+'_inst_'+status)) {
10167:                     var curr = form.elements[caller][i].value;
10168:                     if (prefix) {
10169:                         document.getElementById(prefix+'_'+status).style.display = 'none';
10170:                     }
10171:                     document.getElementById(altprefix+'_inst_'+status).style.display = 'none';
10172:                     document.getElementById(altprefix+'_noninst_'+status).style.display = 'none';
10173:                     if (curr == 'custom') {
10174:                         if (prefix) { 
10175:                             document.getElementById(prefix+'_'+status).style.display = 'inline';
10176:                         }
10177:                     } else if (curr == 'inst') {
10178:                         document.getElementById(altprefix+'_inst_'+status).style.display = 'inline';
10179:                     } else if (curr == 'noninst') {
10180:                         document.getElementById(altprefix+'_noninst_'+status).style.display = 'inline';
10181:                     }
10182:                     break;
10183:                 }
10184:             }
10185:         }
10186:     }
10187: }
10188: 
10189: // ]]>
10190: </script>
10191: 
10192: ENDSCRIPT
10193: }
10194: 
10195: sub noninst_users {
10196:     my ($processing,$emailverified,$emailoptions,$emaildomain,$emailrules,
10197:         $emailruleorder,$settings,$type,$rowid,$typetitle,$css_class,$rowstyle,$intdom) = @_; 
10198:     my $class = 'LC_left_item';
10199:     if ($css_class) {
10200:         $css_class = ' class="'.$css_class.'"'; 
10201:     }
10202:     if ($rowid) {
10203:         $rowid = ' id="'.$rowid.'"';
10204:     }
10205:     if ($rowstyle) {
10206:         $rowstyle = ' style="'.$rowstyle.'"';
10207:     }
10208:     my ($output,$description);
10209:     if ($type eq 'default') {
10210:         $description = &mt('Requests for: [_1]',$typetitle);
10211:     } else {
10212:         $description = &mt('Requests for: [_1] (status self-reported)',$typetitle);
10213:     }
10214:     $output = '<tr'.$css_class.$rowid.$rowstyle.'>'.
10215:               "<td>$description</td>\n".           
10216:               '<td class="'.$class.'" colspan="2">'.
10217:               '<table><tr>';
10218:     my %headers = &Apache::lonlocal::texthash( 
10219:               approve  => 'Processing',
10220:               email    => 'E-mail',
10221:               username => 'Username',
10222:     );
10223:     foreach my $item ('approve','email','username') {
10224:         $output .= '<th>'.$headers{$item}.'</th>';
10225:     }
10226:     $output .= '</tr><tr>';
10227:     foreach my $item ('approve','email','username') {
10228:         $output .= '<td style="vertical-align: top">';
10229:         my (%choices,@options,$hashref,$defoption,$name,$onclick,$hascustom);
10230:         if ($item eq 'approve') {
10231:             %choices = &Apache::lonlocal::texthash (
10232:                                                      automatic => 'Automatically approved',
10233:                                                      approval  => 'Queued for approval',
10234:                                                    );
10235:             @options = ('automatic','approval');
10236:             $hashref = $processing;
10237:             $defoption = 'automatic';
10238:             $name = 'cancreate_emailprocess_'.$type;
10239:         } elsif ($item eq 'email') {
10240:             %choices = &Apache::lonlocal::texthash (
10241:                                                      any     => 'Any e-mail',
10242:                                                      inst    => 'Institutional only',
10243:                                                      noninst => 'Non-institutional only',
10244:                                                      custom  => 'Custom restrictions',
10245:                                                    );
10246:             @options = ('any','inst','noninst');
10247:             my $showcustom;
10248:             if (ref($emailrules) eq 'HASH') {
10249:                 if (keys(%{$emailrules}) > 0) {
10250:                     push(@options,'custom');
10251:                     $showcustom = 'cancreate_emailrule';
10252:                     if (ref($settings) eq 'HASH') {
10253:                         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
10254:                             foreach my $rule (@{$settings->{'email_rule'}}) {
10255:                                 if (exists($emailrules->{$rule})) {
10256:                                     $hascustom ++;
10257:                                 }
10258:                             }
10259:                         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
10260:                             if (ref($settings->{'email_rule'}{$type}) eq 'ARRAY') {
10261:                                 foreach my $rule (@{$settings->{'email_rule'}{$type}}) {
10262:                                     if (exists($emailrules->{$rule})) {
10263:                                         $hascustom ++;
10264:                                     }
10265:                                 }
10266:                             }
10267:                         }
10268:                     }
10269:                 }
10270:             }
10271:             $onclick = ' onclick="toggleEmailOptions(this.form,'."'cancreate_emailoptions','$showcustom',".
10272:                                                      "'cancreate_emaildomain','$type'".');"';
10273:             $hashref = $emailoptions;
10274:             $defoption = 'any';
10275:             $name = 'cancreate_emailoptions_'.$type;
10276:         } elsif ($item eq 'username') {
10277:             %choices = &Apache::lonlocal::texthash (
10278:                                                      all    => 'Same as e-mail',
10279:                                                      first  => 'Omit @domain',
10280:                                                      free   => 'Free to choose',
10281:                                                    );
10282:             @options = ('all','first','free');
10283:             $hashref = $emailverified;
10284:             $defoption = 'all';
10285:             $name = 'cancreate_usernameoptions_'.$type;
10286:         }
10287:         foreach my $option (@options) {
10288:             my $checked;
10289:             if (ref($hashref) eq 'HASH') {
10290:                 if ($type eq '') {
10291:                     if (!exists($hashref->{'default'})) {
10292:                         if ($option eq $defoption) {
10293:                             $checked = ' checked="checked"';
10294:                         }
10295:                     } else {
10296:                         if ($hashref->{'default'} eq $option) {
10297:                             $checked = ' checked="checked"';
10298:                         }
10299:                     }
10300:                 } else {
10301:                     if (!exists($hashref->{$type})) {
10302:                         if ($option eq $defoption) {
10303:                             $checked = ' checked="checked"';
10304:                         }
10305:                     } else {
10306:                         if ($hashref->{$type} eq $option) {
10307:                             $checked = ' checked="checked"';
10308:                         }
10309:                     }
10310:                 }
10311:             } elsif (($item eq 'email') && ($hascustom)) {
10312:                 if ($option eq 'custom') {
10313:                     $checked = ' checked="checked"';
10314:                 }
10315:             } elsif ($option eq $defoption) {
10316:                 $checked = ' checked="checked"';
10317:             }
10318:             $output .= '<span class="LC_nobreak"><label>'.
10319:                        '<input type="radio" name="'.$name.'"'.
10320:                        $checked.' value="'.$option.'"'.$onclick.' />'.
10321:                        $choices{$option}.'</label></span><br />';
10322:             if ($item eq 'email') {
10323:                 if ($option eq 'custom') {
10324:                     my $id = 'cancreate_emailrule_'.$type;
10325:                     my $display = 'none';
10326:                     if ($checked) {
10327:                         $display = 'inline';
10328:                     }
10329:                     my $numinrow = 2;
10330:                     $output .= '<fieldset id="'.$id.'" style="display:'.$display.';">'.
10331:                                '<legend>'.&mt('Disallow').'</legend><table>'.
10332:                                &user_formats_row('email',$settings,$emailrules,
10333:                                                  $emailruleorder,$numinrow,'',$type);
10334:                               '</table></fieldset>';
10335:                 } elsif (($option eq 'inst') || ($option eq 'noninst')) {
10336:                     my %text = &Apache::lonlocal::texthash (
10337:                                                              inst    => 'must end:',
10338:                                                              noninst => 'cannot end:',
10339:                                                            );
10340:                     my $value;
10341:                     if (ref($emaildomain) eq 'HASH') {
10342:                         if (ref($emaildomain->{$type}) eq 'HASH') {
10343:                             $value = $emaildomain->{$type}->{$option}; 
10344:                         }
10345:                     }
10346:                     if ($value eq '') {
10347:                         $value = '@'.$intdom;
10348:                     }
10349:                     my $condition = 'cancreate_emaildomain_'.$option.'_'.$type;
10350:                     my $display = 'none';
10351:                     if ($checked) {
10352:                         $display = 'inline';
10353:                     }
10354:                     $output .= '<div id="'.$condition.'" style="display:'.$display.';">'.
10355:                                '<span class="LC_domprefs_email">'.$text{$option}.'</span> '.
10356:                                '<input type="text" name="'.$condition.'" value="'.$value.'" size="10" />'.
10357:                                '</div>';
10358:                 }
10359:             }
10360:         }
10361:         $output .= '</td>'."\n";
10362:     }
10363:     $output .= "</tr></table></td></tr>\n";
10364:     return $output;
10365: }
10366: 
10367: sub captcha_choice {
10368:     my ($context,$settings,$itemcount,$customcss,$rowstyle) = @_;
10369:     my ($keyentry,$currpub,$currpriv,%checked,$rowname,$pubtext,$privtext,
10370:         $vertext,$currver);
10371:     my %lt = &captcha_phrases();
10372:     $keyentry = 'hidden';
10373:     my $colspan=2;
10374:     if ($context eq 'cancreate') {
10375:         $rowname = &mt('CAPTCHA validation');
10376:     } elsif ($context eq 'login') {
10377:         $rowname =  &mt('"Contact helpdesk" CAPTCHA validation');
10378:     } elsif ($context eq 'passwords') {
10379:         $rowname = &mt('"Forgot Password" CAPTCHA validation');
10380:         $colspan=1;
10381:     }
10382:     if (ref($settings) eq 'HASH') {
10383:         if ($settings->{'captcha'}) {
10384:             $checked{$settings->{'captcha'}} = ' checked="checked"';
10385:         } else {
10386:             $checked{'original'} = ' checked="checked"';
10387:         }
10388:         if ($settings->{'captcha'} eq 'recaptcha') {
10389:             $pubtext = $lt{'pub'};
10390:             $privtext = $lt{'priv'};
10391:             $keyentry = 'text';
10392:             $vertext = $lt{'ver'};
10393:             $currver = $settings->{'recaptchaversion'};
10394:             if ($currver ne '2') {
10395:                 $currver = 1;
10396:             }
10397:         }
10398:         if (ref($settings->{'recaptchakeys'}) eq 'HASH') {
10399:             $currpub = $settings->{'recaptchakeys'}{'public'};
10400:             $currpriv = $settings->{'recaptchakeys'}{'private'};
10401:         }
10402:     } else {
10403:         $checked{'original'} = ' checked="checked"';
10404:     }
10405:     my $css_class;
10406:     if ($itemcount%2) {
10407:         $css_class = 'LC_odd_row';
10408:     }
10409:     if ($customcss) {
10410:         $css_class .= " $customcss";
10411:     }
10412:     $css_class =~ s/^\s+//;
10413:     if ($css_class) {
10414:         $css_class = ' class="'.$css_class.'"';
10415:     }
10416:     if ($rowstyle) {
10417:         $css_class .= ' style="'.$rowstyle.'"';
10418:     }
10419:     my $output = '<tr'.$css_class.'>'.
10420:                  '<td class="LC_left_item">'.$rowname.'</td><td class="LC_left_item" colspan="'.$colspan.'">'."\n".
10421:                  '<table><tr><td>'."\n";
10422:     foreach my $option ('original','recaptcha','notused') {
10423:         $output .= '<span class="LC_nobreak"><label><input type="radio" name="'.$context.'_captcha" value="'.
10424:                    $option.'" '.$checked{$option}.' onchange="javascript:updateCaptcha('."this,'$context'".');" />'.
10425:                    $lt{$option}.'</label></span>';
10426:         unless ($option eq 'notused') {
10427:             $output .= ('&nbsp;'x2)."\n";
10428:         }
10429:     }
10430: #
10431: # Note: If reCAPTCHA is to be used for LON-CAPA servers in a domain, a domain coordinator should visit:
10432: # https://www.google.com/recaptcha and generate a Public and Private key. For domains with multiple
10433: # servers a single key pair will be used for all servers, so the internet domain (e.g., yourcollege.edu)
10434: # specified for use with the key should be broad enough to accommodate all servers in the LON-CAPA domain.
10435: #
10436:     $output .= '</td></tr>'."\n".
10437:                '<tr><td class="LC_zero_height">'."\n".
10438:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchapubtxt">'.$pubtext.'</span>&nbsp;'."\n".
10439:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapub" name="'.$context.'_recaptchapub" value="'.
10440:                $currpub.'" size="40" /></span><br />'."\n".
10441:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchaprivtxt">'.$privtext.'</span>&nbsp;'."\n".
10442:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchapriv" name="'.$context.'_recaptchapriv" value="'.
10443:                $currpriv.'" size="40" /></span><br />'.
10444:                '<span class="LC_nobreak"><span id="'.$context.'_recaptchavertxt">'.$vertext.'</span>&nbsp;'."\n".
10445:                '<input type="'.$keyentry.'" id="'.$context.'_recaptchaversion" name="'.$context.'_recaptchaversion" value="'.
10446:                $currver.'" size="3" /></span><br />'.
10447:                '</td></tr></table>'."\n".
10448:                '</td></tr>';
10449:     return $output;
10450: }
10451: 
10452: sub user_formats_row {
10453:     my ($type,$settings,$rules,$ruleorder,$numinrow,$rowcount,$status) = @_;
10454:     my $output;
10455:     my %text = (
10456:                    'username' => 'new usernames',
10457:                    'id'       => 'IDs',
10458:                );
10459:     unless ($type eq 'email') {
10460:         my $css_class = $rowcount%2?' class="LC_odd_row"':'';
10461:         $output = '<tr '.$css_class.'>'.
10462:                   '<td><span class="LC_nobreak">'.
10463:                   &mt("Format rules to check for $text{$type}: ").
10464:                   '</td><td class="LC_left_item" colspan="2"><table>';
10465:     }
10466:     my $rem;
10467:     if (ref($ruleorder) eq 'ARRAY') {
10468:         for (my $i=0; $i<@{$ruleorder}; $i++) {
10469:             if (ref($rules->{$ruleorder->[$i]}) eq 'HASH') {
10470:                 my $rem = $i%($numinrow);
10471:                 if ($rem == 0) {
10472:                     if ($i > 0) {
10473:                         $output .= '</tr>';
10474:                     }
10475:                     $output .= '<tr>';
10476:                 }
10477:                 my $check = ' ';
10478:                 if (ref($settings) eq 'HASH') {
10479:                     if (ref($settings->{$type.'_rule'}) eq 'ARRAY') {
10480:                         if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}})) {
10481:                             $check = ' checked="checked" ';
10482:                         }
10483:                     } elsif ((ref($settings->{$type.'_rule'}) eq 'HASH') && ($status ne '')) {
10484:                         if (ref($settings->{$type.'_rule'}->{$status}) eq 'ARRAY') {
10485:                             if (grep(/^\Q$ruleorder->[$i]\E$/,@{$settings->{$type.'_rule'}->{$status}})) {
10486:                                 $check = ' checked="checked" ';
10487:                             }
10488:                         }
10489:                     }
10490:                 }
10491:                 my $name = $type.'_rule';
10492:                 if ($type eq 'email') {
10493:                     $name .= '_'.$status;
10494:                 }
10495:                 $output .= '<td class="LC_left_item">'.
10496:                            '<span class="LC_nobreak"><label>'.
10497:                            '<input type="checkbox" name="'.$name.'" '.
10498:                            'value="'.$ruleorder->[$i].'"'.$check.'/>'.
10499:                            $rules->{$ruleorder->[$i]}{'name'}.'</label></span></td>';
10500:             }
10501:         }
10502:         $rem = @{$ruleorder}%($numinrow);
10503:     }
10504:     my $colsleft;
10505:     if ($rem) {
10506:         $colsleft = $numinrow - $rem;
10507:     }
10508:     if ($colsleft > 1 ) {
10509:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
10510:                    '&nbsp;</td>';
10511:     } elsif ($colsleft == 1) {
10512:         $output .= '<td class="LC_left_item">&nbsp;</td>';
10513:     }
10514:     $output .= '</tr></table>';
10515:     unless ($type eq 'email') {
10516:         $output .= '</td></tr>';
10517:     }
10518:     return $output;
10519: }
10520: 
10521: sub usercreation_types {
10522:     my %lt = &Apache::lonlocal::texthash (
10523:                     author     => 'When adding a co-author',
10524:                     course     => 'When adding a user to a course',
10525:                     requestcrs => 'When requesting a course',
10526:                     any        => 'Any',
10527:                     official   => 'Institutional only ',
10528:                     unofficial => 'Non-institutional only',
10529:                     none       => 'None',
10530:     );
10531:     return %lt;
10532: }
10533: 
10534: sub selfcreation_types {
10535:     my %lt = &Apache::lonlocal::texthash (
10536:                     selfcreate => 'User creates own account',
10537:                     any        => 'Any',
10538:                     official   => 'Institutional only ',
10539:                     unofficial => 'Non-institutional only',
10540:                     email      => 'E-mail address',
10541:                     login      => 'Institutional Login',
10542:                     sso        => 'SSO',
10543:              );
10544: }
10545: 
10546: sub authtype_names {
10547:     my %lt = &Apache::lonlocal::texthash(
10548:                       int    => 'Internal',
10549:                       krb4   => 'Kerberos 4',
10550:                       krb5   => 'Kerberos 5',
10551:                       loc    => 'Local',
10552:                       lti    => 'LTI',
10553:                   );
10554:     return %lt;
10555: }
10556: 
10557: sub context_names {
10558:     my %context_title = &Apache::lonlocal::texthash(
10559:        author => 'Creating users when an Author',
10560:        course => 'Creating users when in a course',
10561:        domain => 'Creating users when a Domain Coordinator',
10562:     );
10563:     return %context_title;
10564: }
10565: 
10566: sub print_usermodification {
10567:     my ($position,$dom,$settings,$rowtotal) = @_;
10568:     my $numinrow = 4;
10569:     my ($context,$datatable,$rowcount);
10570:     if ($position eq 'top') {
10571:         $rowcount = 0;
10572:         $context = 'author'; 
10573:         foreach my $role ('ca','aa') {
10574:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10575:                                                    $numinrow,$rowcount);
10576:             $$rowtotal ++;
10577:             $rowcount ++;
10578:         }
10579:     } elsif ($position eq 'bottom') {
10580:         $context = 'course';
10581:         $rowcount = 0;
10582:         foreach my $role ('st','ep','ta','in','cr') {
10583:             $datatable .= &modifiable_userdata_row($context,$role,$settings,
10584:                                                    $numinrow,$rowcount);
10585:             $$rowtotal ++;
10586:             $rowcount ++;
10587:         }
10588:     }
10589:     return $datatable;
10590: }
10591: 
10592: sub print_defaults {
10593:     my ($position,$dom,$settings,$rowtotal) = @_;
10594:     my $rownum = 0;
10595:     my ($datatable,$css_class,$titles);
10596:     unless ($position eq 'bottom') {
10597:         $titles = &defaults_titles($dom);
10598:     }
10599:     if ($position eq 'top') {
10600:         my @items = ('auth_def','auth_arg_def','lang_def','timezone_def',
10601:                      'datelocale_def','portal_def');
10602:         my %defaults;
10603:         if (ref($settings) eq 'HASH') {
10604:             %defaults = %{$settings};
10605:         } else {
10606:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
10607:             foreach my $item (@items) {
10608:                 $defaults{$item} = $domdefaults{$item};
10609:             }
10610:         }
10611:         foreach my $item (@items) {
10612:             if ($rownum%2) {
10613:                 $css_class = '';
10614:             } else {
10615:                 $css_class = ' class="LC_odd_row" ';
10616:             }
10617:             $datatable .= '<tr'.$css_class.'>'.
10618:                           '<td><span class="LC_nobreak">'.$titles->{$item}.
10619:                           '</span></td><td class="LC_right_item" colspan="3">';
10620:             if ($item eq 'auth_def') {
10621:                 my @authtypes = ('internal','krb4','krb5','localauth','lti');
10622:                 my %shortauth = (
10623:                                  internal => 'int',
10624:                                  krb4 => 'krb4',
10625:                                  krb5 => 'krb5',
10626:                                  localauth  => 'loc',
10627:                                  lti => 'lti',
10628:                                 );
10629:                 my %authnames = &authtype_names();
10630:                 foreach my $auth (@authtypes) {
10631:                     my $checked = ' ';
10632:                     if ($defaults{$item} eq $auth) {
10633:                         $checked = ' checked="checked" ';
10634:                     }
10635:                     $datatable .= '<label><input type="radio" name="'.$item.
10636:                                   '" value="'.$auth.'"'.$checked.'/>'.
10637:                                   $authnames{$shortauth{$auth}}.'</label>&nbsp;&nbsp;';
10638:                 }
10639:             } elsif ($item eq 'timezone_def') {
10640:                 my $includeempty = 1;
10641:                 $datatable .= &Apache::loncommon::select_timezone($item,$defaults{$item},undef,$includeempty);
10642:             } elsif ($item eq 'datelocale_def') {
10643:                 my $includeempty = 1;
10644:                 $datatable .= &Apache::loncommon::select_datelocale($item,$defaults{$item},undef,$includeempty);
10645:             } elsif ($item eq 'lang_def') {
10646:                 my $includeempty = 1;
10647:                 $datatable .= &Apache::loncommon::select_language($item,$defaults{$item},$includeempty);
10648:             } else {
10649:                 my $size;
10650:                 if ($item eq 'portal_def') {
10651:                     $size = ' size="25"';
10652:                 }
10653:                 $datatable .= '<input type="text" name="'.$item.'" value="'.
10654:                               $defaults{$item}.'"'.$size.' />';
10655:             }
10656:             $datatable .= '</td></tr>';
10657:             $rownum ++;
10658:         }
10659:     } else {
10660:         my %defaults;
10661:         if (ref($settings) eq 'HASH') {
10662:             if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
10663:                 my $maxnum = @{$settings->{'inststatusorder'}};
10664:                 for (my $i=0; $i<$maxnum; $i++) {
10665:                     $css_class = $rownum%2?' class="LC_odd_row"':'';
10666:                     my $item = $settings->{'inststatusorder'}->[$i];
10667:                     my $title = $settings->{'inststatustypes'}->{$item};
10668:                     my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'$item'".');"';
10669:                     $datatable .= '<tr'.$css_class.'>'.
10670:                                   '<td><span class="LC_nobreak">'.
10671:                                   '<select name="inststatus_pos_'.$item.'"'.$chgstr.'>';
10672:                     for (my $k=0; $k<=$maxnum; $k++) {
10673:                         my $vpos = $k+1;
10674:                         my $selstr;
10675:                         if ($k == $i) {
10676:                             $selstr = ' selected="selected" ';
10677:                         }
10678:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10679:                     }
10680:                     $datatable .= '</select>&nbsp;'.&mt('Internal ID:').'&nbsp;<b>'.$item.'</b>&nbsp;'.
10681:                                   '<input type="checkbox" name="inststatus_delete" value="'.$item.'" />'.
10682:                                   &mt('delete').'</span></td>'.
10683:                                   '<td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.&mt('Name displayed').':'.
10684:                                   '<input type="text" size="20" name="inststatus_title_'.$item.'" value="'.$title.'" />'.
10685:                                   '</span></td></tr>';
10686:                 }
10687:                 $css_class = $rownum%2?' class="LC_odd_row"':'';
10688:                 my $chgstr = ' onchange="javascript:reorderTypes(this.form,'."'addinststatus_pos'".');"';
10689:                 $datatable .= '<tr '.$css_class.'>'.
10690:                               '<td><span class="LC_nobreak"><select name="addinststatus_pos"'.$chgstr.'>';
10691:                 for (my $k=0; $k<=$maxnum; $k++) {
10692:                     my $vpos = $k+1;
10693:                     my $selstr;
10694:                     if ($k == $maxnum) {
10695:                         $selstr = ' selected="selected" ';
10696:                     }
10697:                     $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
10698:                 }
10699:                 $datatable .= '</select>&nbsp;'.&mt('Internal ID:').
10700:                               '<input type="text" size="10" name="addinststatus" value="" />'.
10701:                               '&nbsp;'.&mt('(new)').
10702:                               '</span></td><td class="LC_left_item" colspan="2"><span class="LC_nobreak">'.
10703:                               &mt('Name displayed').':'.
10704:                               '<input type="text" size="20" name="addinststatus_title" value="" /></span></td>'.
10705:                               '</tr>'."\n";
10706:                 $rownum ++;
10707:             }
10708:         }
10709:     }
10710:     $$rowtotal += $rownum;
10711:     return $datatable;
10712: }
10713: 
10714: sub get_languages_hash {
10715:     my %langchoices;
10716:     foreach my $id (&Apache::loncommon::languageids()) {
10717:         my $code = &Apache::loncommon::supportedlanguagecode($id);
10718:         if ($code ne '') {
10719:             $langchoices{$code} =  &Apache::loncommon::plainlanguagedescription($id);
10720:         }
10721:     }
10722:     return %langchoices;
10723: }
10724: 
10725: sub defaults_titles {
10726:     my ($dom) = @_;
10727:     my %titles = &Apache::lonlocal::texthash (
10728:                    'auth_def'      => 'Default authentication type',
10729:                    'auth_arg_def'  => 'Default authentication argument',
10730:                    'lang_def'      => 'Default language',
10731:                    'timezone_def'  => 'Default timezone',
10732:                    'datelocale_def' => 'Default locale for dates',
10733:                    'portal_def'     => 'Portal/Default URL',
10734:                    'intauth_cost'   => 'Encryption cost for bcrypt (positive integer)',
10735:                    'intauth_check'  => 'Check bcrypt cost if authenticated',
10736:                    'intauth_switch' => 'Existing crypt-based switched to bcrypt on authentication',
10737:                  );
10738:     if ($dom) {
10739:         my $uprimary_id = &Apache::lonnet::domain($dom,'primary');
10740:         my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
10741:         my $protocol = $Apache::lonnet::protocol{$uprimary_id};
10742:         $protocol = 'http' if ($protocol ne 'https');
10743:         if ($uint_dom) {
10744:             $titles{'portal_def'} .= ' '.&mt('(for example: [_1])',$protocol.'://loncapa.'.
10745:                                          $uint_dom);
10746:         }
10747:     }
10748:     return (\%titles);
10749: }
10750: 
10751: sub print_scantron {
10752:     my ($r,$position,$dom,$confname,$settings,$rowtotal) = @_;
10753:     if ($position eq 'top') {
10754:         return &print_scantronformat($r,$dom,$confname,$settings,\$rowtotal);
10755:     } else {
10756:         return &print_scantronconfig($dom,$settings,\$rowtotal);
10757:     }
10758: }
10759: 
10760: sub scantron_javascript {
10761:     return <<"ENDSCRIPT";
10762: 
10763: <script type="text/javascript">
10764: // <![CDATA[
10765: 
10766: function toggleScantron(form) {
10767:     var csvfieldset = new Array();
10768:     if (document.getElementById('scantroncsv_cols')) {
10769:         csvfieldset.push(document.getElementById('scantroncsv_cols'));
10770:     }
10771:     if (document.getElementById('scantroncsv_options')) {
10772:         csvfieldset.push(document.getElementById('scantroncsv_options'));
10773:     }
10774:     if (csvfieldset.length) {
10775:         if (document.getElementById('scantronconfcsv')) {
10776:             var scantroncsv = document.getElementById('scantronconfcsv');
10777:             if (scantroncsv.checked) {
10778:                 for (var i=0; i<csvfieldset.length; i++) {
10779:                     csvfieldset[i].style.display = 'block';
10780:                 }
10781:             } else {
10782:                 for (var i=0; i<csvfieldset.length; i++) {
10783:                     csvfieldset[i].style.display = 'none';
10784:                 }
10785:                 var csvselects = document.getElementsByClassName('scantronconfig_csv');
10786:                 if (csvselects.length) {
10787:                     for (var j=0; j<csvselects.length; j++) {
10788:                         csvselects[j].selectedIndex = 0;
10789:                     }
10790:                 }
10791:             }
10792:         }
10793:     }
10794:     return;
10795: }
10796: // ]]>
10797: </script>
10798: 
10799: ENDSCRIPT
10800: 
10801: }
10802: 
10803: sub print_scantronformat {
10804:     my ($r,$dom,$confname,$settings,$rowtotal) = @_;
10805:     my $itemcount = 1;
10806:     my ($datatable,$css_class,$scantronurl,$is_custom,%error,%scantronurls,
10807:         %confhash);
10808:     my $switchserver = &check_switchserver($dom,$confname);
10809:     my %lt = &Apache::lonlocal::texthash (
10810:                 default => 'Default bubblesheet format file error',
10811:                 custom  => 'Custom bubblesheet format file error',
10812:              );
10813:     my %scantronfiles = (
10814:         default => 'default.tab',
10815:         custom => 'custom.tab',
10816:     );
10817:     foreach my $key (keys(%scantronfiles)) {
10818:         $scantronurls{$key} = '/res/'.$dom.'/'.$confname.'/scantron/'
10819:                               .$scantronfiles{$key};
10820:     }
10821:     my @defaultinfo = &Apache::lonnet::stat_file($scantronurls{'default'});
10822:     if ((!@defaultinfo) || ($defaultinfo[0] eq 'no_such_dir')) {
10823:         if (!$switchserver) {
10824:             my $servadm = $r->dir_config('lonAdmEMail');
10825:             my ($configuserok,$author_ok) = &config_check($dom,$confname,$servadm);
10826:             if ($configuserok eq 'ok') {
10827:                 if ($author_ok eq 'ok') {
10828:                     my %legacyfile = (
10829:  default => $Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab',
10830:  custom  => $Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab',
10831:                     );
10832:                     my %md5chk;
10833:                     foreach my $type (keys(%legacyfile)) {
10834:                         ($md5chk{$type}) = split(/ /,`md5sum $legacyfile{$type}`);
10835:                         chomp($md5chk{$type});
10836:                     }
10837:                     if ($md5chk{'default'} ne $md5chk{'custom'}) {
10838:                         foreach my $type (keys(%legacyfile)) {
10839:                             ($scantronurls{$type},my $error) =
10840:                                 &legacy_scantronformat($r,$dom,$confname,
10841:                                                  $type,$legacyfile{$type},
10842:                                                  $scantronurls{$type},
10843:                                                  $scantronfiles{$type});
10844:                             if ($error ne '') {
10845:                                 $error{$type} = $error;
10846:                             }
10847:                         }
10848:                         if (keys(%error) == 0) {
10849:                             $is_custom = 1;
10850:                             $confhash{'scantron'}{'scantronformat'} =
10851:                                 $scantronurls{'custom'};
10852:                             my $putresult =
10853:                                 &Apache::lonnet::put_dom('configuration',
10854:                                                          \%confhash,$dom);
10855:                             if ($putresult ne 'ok') {
10856:                                 $error{'custom'} =
10857:                                     '<span class="LC_error">'.
10858:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10859:                             }
10860:                         }
10861:                     } else {
10862:                         ($scantronurls{'default'},my $error) =
10863:                             &legacy_scantronformat($r,$dom,$confname,
10864:                                           'default',$legacyfile{'default'},
10865:                                           $scantronurls{'default'},
10866:                                           $scantronfiles{'default'});
10867:                         if ($error eq '') {
10868:                             $confhash{'scantron'}{'scantronformat'} = ''; 
10869:                             my $putresult =
10870:                                 &Apache::lonnet::put_dom('configuration',
10871:                                                          \%confhash,$dom);
10872:                             if ($putresult ne 'ok') {
10873:                                 $error{'default'} =
10874:                                     '<span class="LC_error">'.
10875:                                     &mt('An error occurred updating the domain configuration: [_1]',$putresult).'</span>';
10876:                             }
10877:                         } else {
10878:                             $error{'default'} = $error;
10879:                         }
10880:                     }
10881:                 }
10882:             }
10883:         } else {
10884:             $error{'default'} = &mt("Unable to copy default bubblesheet formatfile to domain's RES space: [_1]",$switchserver);
10885:         }
10886:     }
10887:     if (ref($settings) eq 'HASH') {
10888:         if ($settings->{'scantronformat'} eq "/res/$dom/$confname/scantron/custom.tab") {
10889:             my @info = &Apache::lonnet::stat_file($settings->{'scantronformat'});
10890:             if ((!@info) || ($info[0] eq 'no_such_dir')) {
10891:                 $scantronurl = '';
10892:             } else {
10893:                 $scantronurl = $settings->{'scantronformat'};
10894:             }
10895:             $is_custom = 1;
10896:         } else {
10897:             $scantronurl = $scantronurls{'default'};
10898:         }
10899:     } else {
10900:         if ($is_custom) {
10901:             $scantronurl = $scantronurls{'custom'};
10902:         } else {
10903:             $scantronurl = $scantronurls{'default'};
10904:         }
10905:     }
10906:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
10907:     $datatable .= '<tr'.$css_class.'>';
10908:     if (!$is_custom) {
10909:         $datatable .= '<td>'.&mt('Default in use:').'<br />'.
10910:                       '<span class="LC_nobreak">';
10911:         if ($scantronurl) {
10912:             $datatable .= &Apache::loncommon::modal_link($scantronurl,&mt('Default bubblesheet format file'),600,500,
10913:                                                          undef,undef,undef,undef,'background-color:#ffffff');
10914:         } else {
10915:             $datatable = &mt('File unavailable for display');
10916:         }
10917:         $datatable .= '</span></td>';
10918:         if (keys(%error) == 0) { 
10919:             $datatable .= '<td style="vertical-align: bottom">';
10920:             if (!$switchserver) {
10921:                 $datatable .= &mt('Upload:').'<br />';
10922:             }
10923:         } else {
10924:             my $errorstr;
10925:             foreach my $key (sort(keys(%error))) {
10926:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10927:             }
10928:             $datatable .= '<td>'.$errorstr;
10929:         }
10930:     } else {
10931:         if (keys(%error) > 0) {
10932:             my $errorstr;
10933:             foreach my $key (sort(keys(%error))) {
10934:                 $errorstr .= $lt{$key}.': '.$error{$key}.'<br />';
10935:             } 
10936:             $datatable .= '<td>'.$errorstr.'</td><td>&nbsp;';
10937:         } elsif ($scantronurl) {
10938:             my $link =  &Apache::loncommon::modal_link($scantronurl,&mt('Custom bubblesheet format file'),600,500,
10939:                                                        undef,undef,undef,undef,'background-color:#ffffff');
10940:             $datatable .= '<td><span class="LC_nobreak">'.
10941:                           $link.
10942:                           '<label><input type="checkbox" name="scantronformat_del"'.
10943:                           ' value="1" />'.&mt('Delete?').'</label></span></td>'.
10944:                           '<td><span class="LC_nobreak">&nbsp;'.
10945:                           &mt('Replace:').'</span><br />';
10946:         }
10947:     }
10948:     if (keys(%error) == 0) {
10949:         if ($switchserver) {
10950:             $datatable .= &mt('Upload to library server: [_1]',$switchserver);
10951:         } else {
10952:             $datatable .='<span class="LC_nobreak">&nbsp;'.
10953:                          '<input type="file" name="scantronformat" /></span>';
10954:         }
10955:     }
10956:     $datatable .= '</td></tr>';
10957:     $$rowtotal ++;
10958:     return $datatable;
10959: }
10960: 
10961: sub legacy_scantronformat {
10962:     my ($r,$dom,$confname,$file,$legacyfile,$newurl,$newfile) = @_;
10963:     my ($url,$error);
10964:     my @statinfo = &Apache::lonnet::stat_file($newurl);
10965:     if ((!@statinfo) || ($statinfo[0] eq 'no_such_dir')) {
10966:         (my $result,$url) =
10967:             &publishlogo($r,'copy',$legacyfile,$dom,$confname,'scantron',
10968:                          '','',$newfile);
10969:         if ($result ne 'ok') {
10970:             $error = &mt("An error occurred publishing the [_1] bubblesheet format file in RES space. Error was: [_2].",$newfile,$result);
10971:         }
10972:     }
10973:     return ($url,$error);
10974: }
10975: 
10976: sub print_scantronconfig {
10977:     my ($dom,$settings,$rowtotal) = @_;
10978:     my $itemcount = 2;
10979:     my $is_checked = ' checked="checked"';
10980:     my %optionson = (
10981:                      hdr => ' checked="checked"',
10982:                      pad => ' checked="checked"',
10983:                      rem => ' checked="checked"',
10984:                     );
10985:     my %optionsoff = (
10986:                       hdr => '',
10987:                       pad => '',
10988:                       rem => '',
10989:                      );
10990:     my $currcsvsty = 'none';
10991:     my ($datatable,%csvfields,%checked,%onclick,%csvoptions);
10992:     my @fields = &scantroncsv_fields();
10993:     my %titles = &scantronconfig_titles();
10994:     if (ref($settings) eq 'HASH') {
10995:         if (ref($settings->{config}) eq 'HASH') {
10996:             if ($settings->{config}->{dat}) {
10997:                 $checked{'dat'} = $is_checked;
10998:             }
10999:             if (ref($settings->{config}->{csv}) eq 'HASH') {
11000:                 if (ref($settings->{config}->{csv}->{fields}) eq 'HASH') {
11001:                     %csvfields = %{$settings->{config}->{csv}->{fields}};
11002:                     if (keys(%csvfields) > 0) {
11003:                         $checked{'csv'} = $is_checked;
11004:                         $currcsvsty = 'block';
11005:                     }
11006:                 }
11007:                 if (ref($settings->{config}->{csv}->{options}) eq 'HASH') {
11008:                     %csvoptions = %{$settings->{config}->{csv}->{options}};
11009:                     foreach my $option (keys(%optionson)) {
11010:                         unless ($csvoptions{$option}) {
11011:                             $optionsoff{$option} = $optionson{$option};
11012:                             $optionson{$option} = '';
11013:                         }
11014:                     }
11015:                 }
11016:             }
11017:         } else {
11018:             $checked{'dat'} = $is_checked;
11019:         }
11020:     } else {
11021:         $checked{'dat'} = $is_checked;
11022:     }
11023:     $onclick{'csv'} = ' onclick="toggleScantron(this.form);"';
11024:     my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11025:     $datatable = '<tr '.$css_class.'><td>'.&mt('Supported formats').'</td>'.
11026:                  '<td class="LC_left_item" valign="top"><span class="LC_nobreak">';
11027:     foreach my $item ('dat','csv') {
11028:         my $id;
11029:         if ($item eq 'csv') {
11030:             $id = 'id="scantronconfcsv" ';
11031:         }
11032:         $datatable .= '<label><input type="checkbox" name="scantronconfig" '.$id.'value="'.$item.'"'.$checked{$item}.$onclick{$item}.' />'.
11033:                       $titles{$item}.'</label>'.('&nbsp;'x3);
11034:         if ($item eq 'csv') {
11035:             $datatable .= '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_cols">'.
11036:                           '<legend>'.&mt('CSV Column Mapping').'</legend>'.
11037:                           '<table><tr><th>'.&mt('Field').'</th><th>'.&mt('Location').'</th></tr>'."\n";
11038:             foreach my $col (@fields) {
11039:                 my $selnone;
11040:                 if ($csvfields{$col} eq '') {
11041:                     $selnone = ' selected="selected"';
11042:                 }
11043:                 $datatable .= '<tr><td>'.$titles{$col}.'</td>'.
11044:                               '<td><select name="scantronconfig_csv_'.$col.'" class="scantronconfig_csv">'.
11045:                               '<option value=""'.$selnone.'></option>';
11046:                 for (my $i=0; $i<20; $i++) {
11047:                     my $shown = $i+1;
11048:                     my $sel;
11049:                     unless ($selnone) {
11050:                         if (exists($csvfields{$col})) {
11051:                             if ($csvfields{$col} == $i) {
11052:                                 $sel = ' selected="selected"';
11053:                             }
11054:                         }
11055:                     }
11056:                     $datatable .= '<option value="'.$i.'"'.$sel.'>'.$shown.'</option>';
11057:                 }
11058:                 $datatable .= '</select></td></tr>';
11059:            }
11060:            $datatable .= '</table></fieldset>'.
11061:                          '<fieldset style="display:'.$currcsvsty.'" id="scantroncsv_options">'.
11062:                          '<legend>'.&mt('CSV Options').'</legend>';
11063:            foreach my $option ('hdr','pad','rem') {
11064:                $datatable .= '<span class="LC_nobreak">'.$titles{$option}.':'.
11065:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="1"'.$optionson{$option}.' />'.
11066:                          &mt('Yes').'</label>'.('&nbsp;'x2)."\n".
11067:                          '<label><input type="radio" name="scantroncsv_'.$option.'" value="0"'.$optionsoff{$option}.' />'.&mt('No').'</label></span><br />';
11068:            }
11069:            $datatable .= '</fieldset>';
11070:            $itemcount ++;
11071:         }
11072:     }
11073:     $datatable .= '</td></tr>';
11074:     $$rowtotal ++;
11075:     return $datatable;
11076: }
11077: 
11078: sub scantronconfig_titles {
11079:     return &Apache::lonlocal::texthash(
11080:                                           dat => 'Standard format (.dat)',
11081:                                           csv => 'Comma separated values (.csv)',
11082:                                           hdr => 'Remove first line in file (contains column titles)',
11083:                                           pad => 'Prepend 0s to PaperID',
11084:                                           rem => 'Remove leading spaces (except Question Response columns)',
11085:                                           CODE => 'CODE',
11086:                                           ID   => 'Student ID',
11087:                                           PaperID => 'Paper ID',
11088:                                           FirstName => 'First Name',
11089:                                           LastName => 'Last Name',
11090:                                           FirstQuestion => 'First Question Response',
11091:                                           Section => 'Section',
11092:     );
11093: }
11094: 
11095: sub scantroncsv_fields {
11096:     return ('PaperID','LastName','FirstName','ID','Section','CODE','FirstQuestion');
11097: }
11098: 
11099: sub print_coursecategories {
11100:     my ($position,$dom,$hdritem,$settings,$rowtotal) = @_;
11101:     my $datatable;
11102:     if ($position eq 'top') {
11103:         my (%checked);
11104:         my @catitems = ('unauth','auth');
11105:         my @cattypes = ('std','domonly','codesrch','none');
11106:         $checked{'unauth'} = 'std';
11107:         $checked{'auth'} = 'std';
11108:         if (ref($settings) eq 'HASH') {
11109:             foreach my $type (@cattypes) {
11110:                 if ($type eq $settings->{'unauth'}) {
11111:                     $checked{'unauth'} = $type;
11112:                 }
11113:                 if ($type eq $settings->{'auth'}) {
11114:                     $checked{'auth'} = $type;
11115:                 }
11116:             }
11117:         }
11118:         my %lt = &Apache::lonlocal::texthash (
11119:                                                unauth   => 'Catalog type for unauthenticated users',
11120:                                                auth     => 'Catalog type for authenticated users',
11121:                                                none     => 'No catalog',
11122:                                                std      => 'Standard catalog',
11123:                                                domonly  => 'Domain-only catalog',
11124:                                                codesrch => "Code search form",
11125:                                              );
11126:        my $itemcount = 0;
11127:        foreach my $item (@catitems) {
11128:            my $css_class = $itemcount%2? ' class="LC_odd_row"':'';
11129:            $datatable .= '<tr '.$css_class.'>'.
11130:                          '<td>'.$lt{$item}.'</td>'.
11131:                          '<td class="LC_right_item"><span class="LC_nobreak">';
11132:            foreach my $type (@cattypes) {
11133:                my $ischecked;
11134:                if ($checked{$item} eq $type) {
11135:                    $ischecked=' checked="checked"';
11136:                }
11137:                $datatable .= '<label>'.
11138:                              '<input type="radio" name="coursecat_'.$item.'" value="'.$type.'"'.$ischecked.
11139:                              ' />'.$lt{$type}.'</label>&nbsp;';
11140:            }
11141:            $datatable .= '</span></td></tr>';
11142:            $itemcount ++;
11143:         }
11144:         $$rowtotal += $itemcount;
11145:     } elsif ($position eq 'middle') {
11146:         my $toggle_cats_crs = ' ';
11147:         my $toggle_cats_dom = ' checked="checked" ';
11148:         my $can_cat_crs = ' ';
11149:         my $can_cat_dom = ' checked="checked" ';
11150:         my $toggle_catscomm_comm = ' ';
11151:         my $toggle_catscomm_dom = ' checked="checked" ';
11152:         my $can_catcomm_comm = ' ';
11153:         my $can_catcomm_dom = ' checked="checked" ';
11154:         my $toggle_catsplace_place = ' ';
11155:         my $toggle_catsplace_dom = ' checked="checked" ';
11156:         my $can_catplace_place = ' ';
11157:         my $can_catplace_dom = ' checked="checked" ';
11158: 
11159:         if (ref($settings) eq 'HASH') {
11160:             if ($settings->{'togglecats'} eq 'crs') {
11161:                 $toggle_cats_crs = $toggle_cats_dom;
11162:                 $toggle_cats_dom = ' ';
11163:             }
11164:             if ($settings->{'categorize'} eq 'crs') {
11165:                 $can_cat_crs = $can_cat_dom;
11166:                 $can_cat_dom = ' ';
11167:             }
11168:             if ($settings->{'togglecatscomm'} eq 'comm') {
11169:                 $toggle_catscomm_comm = $toggle_catscomm_dom;
11170:                 $toggle_catscomm_dom = ' ';
11171:             }
11172:             if ($settings->{'categorizecomm'} eq 'comm') {
11173:                 $can_catcomm_comm = $can_catcomm_dom;
11174:                 $can_catcomm_dom = ' ';
11175:             }
11176:             if ($settings->{'togglecatsplace'} eq 'place') {
11177:                 $toggle_catsplace_place = $toggle_catsplace_dom;
11178:                 $toggle_catsplace_dom = ' ';
11179:             }
11180:             if ($settings->{'categorizeplace'} eq 'place') {
11181:                 $can_catplace_place = $can_catplace_dom;
11182:                 $can_catplace_dom = ' ';
11183:             }
11184:         }
11185:         my %title = &Apache::lonlocal::texthash (
11186:                      togglecats      => 'Show/Hide a course in catalog',
11187:                      togglecatscomm  => 'Show/Hide a community in catalog',
11188:                      togglecatsplace => 'Show/Hide a placement test in catalog',
11189:                      categorize      => 'Assign a category to a course',
11190:                      categorizecomm  => 'Assign a category to a community',
11191:                      categorizeplace => 'Assign a category to a placement test',
11192:                     );
11193:         my %level = &Apache::lonlocal::texthash (
11194:                      dom   => 'Set in Domain',
11195:                      crs   => 'Set in Course',
11196:                      comm  => 'Set in Community',
11197:                      place => 'Set in Placement Test',
11198:                     );
11199:         $datatable = '<tr class="LC_odd_row">'.
11200:                   '<td>'.$title{'togglecats'}.'</td>'.
11201:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11202:                   '<input type="radio" name="togglecats"'.
11203:                   $toggle_cats_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11204:                   '<label><input type="radio" name="togglecats"'.
11205:                   $toggle_cats_crs.' value="crs" />'.$level{'crs'}.'</label></span></td>'.
11206:                   '</tr><tr>'.
11207:                   '<td>'.$title{'categorize'}.'</td>'.
11208:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11209:                   '<label><input type="radio" name="categorize"'.
11210:                   $can_cat_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11211:                   '<label><input type="radio" name="categorize"'.
11212:                   $can_cat_crs.'value="crs" />'.$level{'crs'}.'</label></span></td>'.
11213:                   '</tr><tr class="LC_odd_row">'.
11214:                   '<td>'.$title{'togglecatscomm'}.'</td>'.
11215:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11216:                   '<input type="radio" name="togglecatscomm"'.
11217:                   $toggle_catscomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11218:                   '<label><input type="radio" name="togglecatscomm"'.
11219:                   $toggle_catscomm_comm.' value="comm" />'.$level{'comm'}.'</label></span></td>'.
11220:                   '</tr><tr>'.
11221:                   '<td>'.$title{'categorizecomm'}.'</td>'.
11222:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11223:                   '<label><input type="radio" name="categorizecomm"'.
11224:                   $can_catcomm_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11225:                   '<label><input type="radio" name="categorizecomm"'.
11226:                   $can_catcomm_comm.'value="comm" />'.$level{'comm'}.'</label></span></td>'.
11227:                   '</tr><tr class="LC_odd_row">'.
11228:                   '<td>'.$title{'togglecatsplace'}.'</td>'.
11229:                   '<td class="LC_right_item"><span class="LC_nobreak"><label>'.
11230:                   '<input type="radio" name="togglecatsplace"'.
11231:                   $toggle_catsplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11232:                   '<label><input type="radio" name="togglecatscomm"'.
11233:                   $toggle_catsplace_place.' value="comm" />'.$level{'place'}.'</label></span></td>'.
11234:                   '</tr><tr>'.
11235:                   '<td>'.$title{'categorizeplace'}.'</td>'.
11236:                   '<td class="LC_right_item"><span class="LC_nobreak">'.
11237:                   '<label><input type="radio" name="categorizeplace"'.
11238:                   $can_catplace_dom.' value="dom" />'.$level{'dom'}.'</label>&nbsp;'.
11239:                   '<label><input type="radio" name="categorizeplace"'.
11240:                   $can_catplace_place.'value="place" />'.$level{'place'}.'</label></span></td>'.
11241:                   '</tr>';
11242:         $$rowtotal += 6;
11243:     } else {
11244:         my $css_class;
11245:         my $itemcount = 1;
11246:         my $cathash; 
11247:         if (ref($settings) eq 'HASH') {
11248:             $cathash = $settings->{'cats'};
11249:         }
11250:         if (ref($cathash) eq 'HASH') {
11251:             my (@cats,@trails,%allitems,%idx,@jsarray);
11252:             &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,
11253:                                                    \%allitems,\%idx,\@jsarray);
11254:             my $maxdepth = scalar(@cats);
11255:             my $colattrib = '';
11256:             if ($maxdepth > 2) {
11257:                 $colattrib = ' colspan="2" ';
11258:             }
11259:             my @path;
11260:             if (@cats > 0) {
11261:                 if (ref($cats[0]) eq 'ARRAY') {
11262:                     my $numtop = @{$cats[0]};
11263:                     my $maxnum = $numtop;
11264:                     my %default_names = (
11265:                           instcode    => &mt('Official courses'),
11266:                           communities => &mt('Communities'),
11267:                           placement   => &mt('Placement Tests'),
11268:                     );
11269: 
11270:                     if ((!grep(/^instcode$/,@{$cats[0]})) || 
11271:                         ($cathash->{'instcode::0'} eq '') ||
11272:                         (!grep(/^communities$/,@{$cats[0]})) || 
11273:                         ($cathash->{'communities::0'} eq '') ||
11274:                         (!grep(/^placement$/,@{$cats[0]})) ||
11275:                         ($cathash->{'placement::0'} eq '')) {
11276:                         $maxnum ++;
11277:                     }
11278:                     my $lastidx;
11279:                     for (my $i=0; $i<$numtop; $i++) {
11280:                         my $parent = $cats[0][$i];
11281:                         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11282:                         my $item = &escape($parent).'::0';
11283:                         my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$item','$idx{$item}'".');"';
11284:                         $lastidx = $idx{$item};
11285:                         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11286:                                       .'<select name="'.$item.'"'.$chgstr.'>';
11287:                         for (my $k=0; $k<=$maxnum; $k++) {
11288:                             my $vpos = $k+1;
11289:                             my $selstr;
11290:                             if ($k == $i) {
11291:                                 $selstr = ' selected="selected" ';
11292:                             }
11293:                             $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11294:                         }
11295:                         $datatable .= '</select></span></td><td>';
11296:                         if ($parent eq 'instcode' || $parent eq 'communities' || $parent eq 'placement') {
11297:                             $datatable .=  '<span class="LC_nobreak">'
11298:                                            .$default_names{$parent}.'</span>';
11299:                             if ($parent eq 'instcode') {
11300:                                 $datatable .= '<br /><span class="LC_nobreak">('
11301:                                               .&mt('with institutional codes')
11302:                                               .')</span></td><td'.$colattrib.'>';
11303:                             } else {
11304:                                 $datatable .= '<table><tr><td>';
11305:                             }
11306:                             $datatable .= '<span class="LC_nobreak">'
11307:                                           .'<label><input type="radio" name="'
11308:                                           .$parent.'" value="1" checked="checked" />'
11309:                                           .&mt('Display').'</label>';
11310:                             if ($parent eq 'instcode') {
11311:                                 $datatable .= '&nbsp;';
11312:                             } else {
11313:                                 $datatable .= '</span></td></tr><tr><td>'
11314:                                               .'<span class="LC_nobreak">';
11315:                             }
11316:                             $datatable .= '<label><input type="radio" name="'
11317:                                           .$parent.'" value="0" />'
11318:                                           .&mt('Do not display').'</label></span>';
11319:                             if (($parent eq 'communities') || ($parent eq 'placement')) {
11320:                                 $datatable .= '</td></tr></table>';
11321:                             }
11322:                             $datatable .= '</td>';
11323:                         } else {
11324:                             $datatable .= $parent
11325:                                           .'&nbsp;<span class="LC_nobreak"><label>'
11326:                                           .'<input type="checkbox" name="deletecategory" '
11327:                                           .'value="'.$item.'" />'.&mt('Delete').'</label></span></td>';
11328:                         }
11329:                         my $depth = 1;
11330:                         push(@path,$parent);
11331:                         $datatable .= &build_category_rows($itemcount,\@cats,$depth,$parent,\@path,\%idx);
11332:                         pop(@path);
11333:                         $datatable .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
11334:                         $itemcount ++;
11335:                     }
11336:                     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11337:                     my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','$lastidx'".');"';
11338:                     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="addcategory_pos"'.$chgstr.'>';
11339:                     for (my $k=0; $k<=$maxnum; $k++) {
11340:                         my $vpos = $k+1;
11341:                         my $selstr;
11342:                         if ($k == $numtop) {
11343:                             $selstr = ' selected="selected" ';
11344:                         }
11345:                         $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11346:                     }
11347:                     $datatable .= '</select></span></td><td colspan="2">'.&mt('Add category:').'&nbsp;'
11348:                                   .'<input type="text" size="20" name="addcategory_name" value="" /></td>'
11349:                                   .'</tr>'."\n";
11350:                     $itemcount ++;
11351:                     foreach my $default ('instcode','communities','placement') {
11352:                         if ((!grep(/^\Q$default\E$/,@{$cats[0]})) || ($cathash->{$default.'::0'} eq '')) {
11353:                             $css_class = $itemcount%2?' class="LC_odd_row"':'';
11354:                             my $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','$lastidx'".');"';
11355:                             $datatable .= '<tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr><tr '.$css_class.'><td>'.
11356:                                           '<span class="LC_nobreak"><select name="'.$default.'_pos"'.$chgstr.'>';
11357:                             for (my $k=0; $k<=$maxnum; $k++) {
11358:                                 my $vpos = $k+1;
11359:                                 my $selstr;
11360:                                 if ($k == $maxnum) {
11361:                                     $selstr = ' selected="selected" ';
11362:                                 }
11363:                                 $datatable .= '<option value="'.$k.'"'.$selstr.'>'.$vpos.'</option>';
11364:                             }
11365:                             $datatable .= '</select></span></td>'.
11366:                                           '<td><span class="LC_nobreak">'.
11367:                                           $default_names{$default}.'</span>';
11368:                             if ($default eq 'instcode') {
11369:                                 $datatable .= '<br /><span class="LC_nobreak">(' 
11370:                                               .&mt('with institutional codes').')</span>';
11371:                             }
11372:                             $datatable .= '</td>'
11373:                                           .'<td><span class="LC_nobreak"><label><input type="radio" name="'.$default.'" value="1" />'
11374:                                           .&mt('Display').'</label>&nbsp;'
11375:                                           .'<label><input type="radio" name="'.$default.'" value="0" checked="checked"/>'
11376:                                           .&mt('Do not display').'</label></span></td></tr>';
11377:                         }
11378:                     }
11379:                 }
11380:             } else {
11381:                 $datatable .= &initialize_categories($itemcount);
11382:             }
11383:         } else {
11384:             $datatable .= '<tr><td class="LC_right_item">'.$hdritem->{'header'}->[1]->{'col2'}.'</td></tr>'
11385:                           .&initialize_categories($itemcount);
11386:         }
11387:         $$rowtotal += $itemcount;
11388:     }
11389:     return $datatable;
11390: }
11391: 
11392: sub print_serverstatuses {
11393:     my ($dom,$settings,$rowtotal) = @_;
11394:     my $datatable;
11395:     my @pages = &serverstatus_pages();
11396:     my (%namedaccess,%machineaccess);
11397:     foreach my $type (@pages) {
11398:         $namedaccess{$type} = '';
11399:         $machineaccess{$type}= '';
11400:     }
11401:     if (ref($settings) eq 'HASH') {
11402:         foreach my $type (@pages) {
11403:             if (exists($settings->{$type})) {
11404:                 if (ref($settings->{$type}) eq 'HASH') {
11405:                     foreach my $key (keys(%{$settings->{$type}})) {
11406:                         if ($key eq 'namedusers') {
11407:                             $namedaccess{$type} = $settings->{$type}->{$key};
11408:                         } elsif ($key eq 'machines') {
11409:                             $machineaccess{$type} = $settings->{$type}->{$key};
11410:                         }
11411:                     }
11412:                 }
11413:             }
11414:         }
11415:     }
11416:     my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
11417:     my $rownum = 0;
11418:     my $css_class;
11419:     foreach my $type (@pages) {
11420:         $rownum ++;
11421:         $css_class = $rownum%2?' class="LC_odd_row"':'';
11422:         $datatable .= '<tr'.$css_class.'>'.
11423:                       '<td><span class="LC_nobreak">'.
11424:                       $titles->{$type}.'</span></td>'.
11425:                       '<td class="LC_left_item">'.
11426:                       '<input type="text" name="'.$type.'_namedusers" '.
11427:                       'value="'.$namedaccess{$type}.'" size="30" /></td>'.
11428:                       '<td class="LC_right_item">'.
11429:                       '<span class="LC_nobreak">'.
11430:                       '<input type="text" name="'.$type.'_machines" '.
11431:                       'value="'.$machineaccess{$type}.'" size="10" />'.
11432:                       '</span></td></tr>'."\n";
11433:     }
11434:     $$rowtotal += $rownum;
11435:     return $datatable;
11436: }
11437: 
11438: sub serverstatus_pages {
11439:     return ('userstatus','lonstatus','loncron','server-status','codeversions',
11440:             'checksums','clusterstatus','certstatus','metadata_keywords',
11441:             'metadata_harvest','takeoffline','takeonline','showenv','toggledebug',
11442:             'ping','domconf','uniquecodes','diskusage','coursecatalog');
11443: }
11444: 
11445: sub defaults_javascript {
11446:     my ($settings) = @_;
11447:     return unless (ref($settings) eq 'HASH');
11448:     if ((ref($settings->{'inststatusorder'}) eq 'ARRAY') && (ref($settings->{'inststatustypes'}) eq 'HASH')) {
11449:         my $maxnum = scalar(@{$settings->{'inststatusorder'}});
11450:         if ($maxnum eq '') {
11451:             $maxnum = 0;
11452:         }
11453:         $maxnum ++;
11454:         my $jstext = '    var inststatuses = Array('."'".join("','",@{$settings->{'inststatusorder'}})."'".');';  
11455:         return <<"ENDSCRIPT";
11456: <script type="text/javascript">
11457: // <![CDATA[
11458: function reorderTypes(form,caller) {
11459:     var changedVal;
11460: $jstext 
11461:     var newpos = 'addinststatus_pos';
11462:     var current = new Array;
11463:     var maxh = $maxnum;
11464:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11465:     var oldVal;
11466:     if (caller == newpos) {
11467:         changedVal = newitemVal;
11468:     } else {
11469:         var curritem = 'inststatus_pos_'+caller;
11470:         changedVal = form.elements[curritem].options[form.elements[curritem].selectedIndex].value;
11471:         current[newitemVal] = newpos;
11472:     }
11473:     for (var i=0; i<inststatuses.length; i++) {
11474:         if (inststatuses[i] != caller) {
11475:             var elementName = 'inststatus_pos_'+inststatuses[i];
11476:             if (form.elements[elementName]) {
11477:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11478:                 current[currVal] = elementName;
11479:             }
11480:         }
11481:     }
11482:     for (var j=0; j<maxh; j++) {
11483:         if (current[j] == undefined) {
11484:             oldVal = j;
11485:         }
11486:     }
11487:     if (oldVal < changedVal) {
11488:         for (var k=oldVal+1; k<=changedVal ; k++) {
11489:            var elementName = current[k];
11490:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11491:         }
11492:     } else {
11493:         for (var k=changedVal; k<oldVal; k++) {
11494:             var elementName = current[k];
11495:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11496:         }
11497:     }
11498:     return;
11499: }
11500: 
11501: // ]]>
11502: </script>
11503: 
11504: ENDSCRIPT
11505:     }
11506:     return;
11507: }
11508: 
11509: sub passwords_javascript {
11510:     my ($prefix) = @_;
11511:     my %intalert;
11512:     if ($prefix eq 'passwords') {
11513:         %intalert = &Apache::lonlocal::texthash (
11514:             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.',
11515:             authcost => 'Warning: bcrypt encryption cost for internal authentication must be an integer.',
11516:             passmin => 'Warning: minimum password length must be a positive integer greater than 6.',
11517:             passmax => 'Warning: maximum password length must be a positive integer (or blank).',
11518:             passexp => 'Warning: days before password expiration must be a positive integer (or blank).',
11519:             passnum => 'Warning: number of previous passwords to save must be a positive integer (or blank).',
11520:         );
11521:     } elsif ($prefix eq 'secrets') {
11522:         %intalert = &Apache::lonlocal::texthash (
11523:             passmin => 'Warning: minimum secret length must be a positive integer greater than 6.',
11524:             passmax => 'Warning: maximum secret length must be a positive integer (or blank).',
11525:         );
11526:     }
11527:     &js_escape(\%intalert);
11528:     my $defmin = $Apache::lonnet::passwdmin;
11529:     my $intauthjs; 
11530:     if ($prefix eq 'passwords') { $intauthjs = <<"ENDSCRIPT";
11531: 
11532: function warnIntAuth(field) {
11533:     if (field.name == 'intauth_check') {
11534:         if (field.value == '2') {
11535:             alert('$intalert{authcheck}');
11536:         }
11537:     }
11538:     if (field.name == 'intauth_cost') {
11539:         field.value.replace(/\s/g,'');
11540:         if (field.value != '') {
11541:             var regexdigit=/^\\d+\$/;
11542:             if (!regexdigit.test(field.value)) {
11543:                 alert('$intalert{authcost}');
11544:             }
11545:         }
11546:     }
11547:     return;
11548: }
11549: 
11550: ENDSCRIPT
11551: 
11552:      }
11553: 
11554:      $intauthjs .= <<"ENDSCRIPT";
11555: 
11556: function warnInt$prefix(field) {
11557:     field.value.replace(/^\s+/,'');
11558:     field.value.replace(/\s+\$/,'');
11559:     var regexdigit=/^\\d+\$/;
11560:     if (field.name == '$prefix\_min') {
11561:         if (field.value == '') {
11562:             alert('$intalert{passmin}');
11563:             field.value = '$defmin';
11564:         } else {
11565:             if (!regexdigit.test(field.value)) {
11566:                 alert('$intalert{passmin}');
11567:                 field.value = '$defmin';
11568:             }
11569:             var minval = parseInt(field.value,10);
11570:             if (minval < $defmin) {
11571:                 alert('$intalert{passmin}');
11572:                 field.value = '$defmin';
11573:             }
11574:         }
11575:     } else {
11576:         if (field.value == '0') {
11577:             field.value = '';
11578:         }
11579:         if (field.value != '') {
11580:             if (field.name == '$prefix\_expire') {
11581:                 var regexpposnum=/^\\d+(|\\.\\d*)\$/; 
11582:                 if (!regexpposnum.test(field.value)) {
11583:                     alert('$intalert{passexp}');
11584:                     field.value = '';
11585:                 } else {
11586:                     var expval = parseFloat(field.value);
11587:                     if (expval == 0) {
11588:                         alert('$intalert{passexp}');
11589:                         field.value = '';
11590:                     }
11591:                 }
11592:             } else {
11593:                 if (!regexdigit.test(field.value)) {
11594:                     if (field.name == '$prefix\_max') {
11595:                         alert('$intalert{passmax}');
11596:                     } else {
11597:                         if (field.name == '$prefix\_numsaved') {
11598:                             alert('$intalert{passnum}');
11599:                         }
11600:                     }
11601:                     field.value = '';
11602:                 }
11603:             }
11604:         }
11605:     }
11606:     return;
11607: }
11608: 
11609: ENDSCRIPT
11610:     return &Apache::lonhtmlcommon::scripttag($intauthjs);
11611: }
11612: 
11613: sub coursecategories_javascript {
11614:     my ($settings) = @_;
11615:     my ($output,$jstext,$cathash);
11616:     if (ref($settings) eq 'HASH') {
11617:         $cathash = $settings->{'cats'};
11618:     }
11619:     if (ref($cathash) eq 'HASH') {
11620:         my (@cats,@jsarray,%idx);
11621:         &Apache::loncommon::gather_categories($cathash,\@cats,\%idx,\@jsarray);
11622:         if (@jsarray > 0) {
11623:             $jstext = '    var categories = Array('.scalar(@jsarray).');'."\n";
11624:             for (my $i=0; $i<@jsarray; $i++) {
11625:                 if (ref($jsarray[$i]) eq 'ARRAY') {
11626:                     my $catstr = join('","',@{$jsarray[$i]});
11627:                     $jstext .= '    categories['.$i.'] = Array("'.$catstr.'");'."\n";
11628:                 }
11629:             }
11630:         }
11631:     } else {
11632:         $jstext  = '    var categories = Array(1);'."\n".
11633:                    '    categories[0] = Array("instcode_pos");'."\n"; 
11634:     }
11635:     my $instcode_reserved = &mt('The name: [_1] is a reserved category.','"instcode"');
11636:     my $communities_reserved = &mt('The name: [_1] is a reserved category.','"communities"');
11637:     my $placement_reserved = &mt('The name: [_1] is a reserved category.','"placement"');
11638:     my $choose_again = "\n".&mt('Please use a different name for the new top level category.'); 
11639:     &js_escape(\$instcode_reserved);
11640:     &js_escape(\$communities_reserved);
11641:     &js_escape(\$placement_reserved);
11642:     &js_escape(\$choose_again);
11643:     $output = <<"ENDSCRIPT";
11644: <script type="text/javascript">
11645: // <![CDATA[
11646: function reorderCats(form,parent,item,idx) {
11647:     var changedVal;
11648: $jstext
11649:     var newpos = 'addcategory_pos';
11650:     if (parent == '') {
11651:         var has_instcode = 0;
11652:         var maxtop = categories[idx].length;
11653:         for (var j=0; j<maxtop; j++) {
11654:             if (categories[idx][j] == 'instcode::0') {
11655:                 has_instcode == 1;
11656:             }
11657:         }
11658:         if (has_instcode == 0) {
11659:             categories[idx][maxtop] = 'instcode_pos';
11660:         }
11661:     } else {
11662:         newpos += '_'+parent;
11663:     }
11664:     var maxh = 1 + categories[idx].length;
11665:     var current = new Array;
11666:     var newitemVal = form.elements[newpos].options[form.elements[newpos].selectedIndex].value;
11667:     if (item == newpos) {
11668:         changedVal = newitemVal;
11669:     } else {
11670:         changedVal = form.elements[item].options[form.elements[item].selectedIndex].value;
11671:         current[newitemVal] = newpos;
11672:     }
11673:     for (var i=0; i<categories[idx].length; i++) {
11674:         var elementName = categories[idx][i];
11675:         if (elementName != item) {
11676:             if (form.elements[elementName]) {
11677:                 var currVal = form.elements[elementName].options[form.elements[elementName].selectedIndex].value;
11678:                 current[currVal] = elementName;
11679:             }
11680:         }
11681:     }
11682:     var oldVal;
11683:     for (var j=0; j<maxh; j++) {
11684:         if (current[j] == undefined) {
11685:             oldVal = j;
11686:         }
11687:     }
11688:     if (oldVal < changedVal) {
11689:         for (var k=oldVal+1; k<=changedVal ; k++) {
11690:            var elementName = current[k];
11691:            form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex - 1;
11692:         }
11693:     } else {
11694:         for (var k=changedVal; k<oldVal; k++) {
11695:             var elementName = current[k];
11696:             form.elements[elementName].selectedIndex = form.elements[elementName].selectedIndex + 1;
11697:         }
11698:     }
11699:     return;
11700: }
11701: 
11702: function categoryCheck(form) {
11703:     if (form.elements['addcategory_name'].value == 'instcode') {
11704:         alert('$instcode_reserved\\n$choose_again');
11705:         return false;
11706:     }
11707:     if (form.elements['addcategory_name'].value == 'communities') {
11708:         alert('$communities_reserved\\n$choose_again');
11709:         return false;
11710:     }
11711:     if (form.elements['addcategory_name'].value == 'placement') {
11712:         alert('$placement_reserved\\n$choose_again');
11713:         return false;
11714:     }
11715:     return true;
11716: }
11717: 
11718: // ]]>
11719: </script>
11720: 
11721: ENDSCRIPT
11722:     return $output;
11723: }
11724: 
11725: sub initialize_categories {
11726:     my ($itemcount) = @_;
11727:     my ($datatable,$css_class,$chgstr);
11728:     my %default_names = &Apache::lonlocal::texthash (
11729:                       instcode    => 'Official courses (with institutional codes)',
11730:                       communities => 'Communities',
11731:                       placement   => 'Placement Tests',
11732:                         );
11733:     my %selnum = (
11734:                    instcode    => '0',
11735:                    communities => '1',
11736:                    placement   => '2',
11737:                  );
11738:     my %selected;
11739:     foreach my $default ('instcode','communities','placement') {
11740:         $css_class = $itemcount%2?' class="LC_odd_row"':'';
11741:         $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','$default"."_pos','0'".');"';
11742:         map { $selected{$selnum{$_}} = '' } keys(%selnum);
11743:         $selected{$selnum{$default}} = ' selected="selected"';
11744:         $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11745:                      .'<select name="'.$default.'_pos"'.$chgstr.'>'
11746:                      .'<option value="0"'.$selected{'0'}.'>1</option>'
11747:                      .'<option value="1"'.$selected{'1'}.'>2</option>'
11748:                      .'<option value="2"'.$selected{'2'}.'>3</option>'
11749:                      .'<option value="3">4</option></select>&nbsp;'
11750:                      .$default_names{$default}
11751:                      .'</span></td><td><span class="LC_nobreak">'
11752:                      .'<label><input type="radio" name="'.$default.'" value="1" checked="checked" />'
11753:                      .&mt('Display').'</label>&nbsp;<label>'
11754:                      .'<input type="radio" name="'.$default.'" value="0" />'.&mt('Do not display')
11755:                  .'</label></span></td></tr>';
11756:         $itemcount ++;
11757:     }
11758:     $css_class = $itemcount%2?' class="LC_odd_row"':'';
11759:     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'','addcategory_pos','0'".');"';
11760:     $datatable .= '<tr '.$css_class.'><td><span class="LC_nobreak">'
11761:                   .'<select name="addcategory_pos"'.$chgstr.'>'
11762:                   .'<option value="0">1</option>'
11763:                   .'<option value="1">2</option>'
11764:                   .'<option value="2">3</option>'
11765:                   .'<option value="3" selected="selected">4</option></select>&nbsp;'
11766:                   .&mt('Add category').'</span></td><td><span class="LC_nobreak">'.&mt('Name:')
11767:                   .'&nbsp;<input type="text" size="20" name="addcategory_name" value="" /></span>'
11768:                   .'</td></tr>';
11769:     return $datatable;
11770: }
11771: 
11772: sub build_category_rows {
11773:     my ($itemcount,$cats,$depth,$parent,$path,$idx) = @_;
11774:     my ($text,$name,$item,$chgstr);
11775:     if (ref($cats) eq 'ARRAY') {
11776:         my $maxdepth = scalar(@{$cats});
11777:         if (ref($cats->[$depth]) eq 'HASH') {
11778:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
11779:                 my $numchildren = @{$cats->[$depth]{$parent}};
11780:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
11781:                 $text .= '<td><table class="LC_data_table">';
11782:                 my ($idxnum,$parent_name,$parent_item);
11783:                 my $higher = $depth - 1;
11784:                 if ($higher == 0) {
11785:                     $parent_name = &escape($parent).'::'.$higher;
11786:                 } else {
11787:                     if (ref($path) eq 'ARRAY') {
11788:                         $parent_name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11789:                     }
11790:                 }
11791:                 $parent_item = 'addcategory_pos_'.$parent_name;
11792:                 for (my $j=0; $j<=$numchildren; $j++) {
11793:                     if ($j < $numchildren) {
11794:                         $name = $cats->[$depth]{$parent}[$j];
11795:                         $item = &escape($name).':'.&escape($parent).':'.$depth;
11796:                         $idxnum = $idx->{$item};
11797:                     } else {
11798:                         $name = $parent_name;
11799:                         $item = $parent_item;
11800:                     }
11801:                     $chgstr = ' onchange="javascript:reorderCats(this.form,'."'$parent_name','$item','$idxnum'".');"';
11802:                     $text .= '<tr '.$css_class.'><td><span class="LC_nobreak"><select name="'.$item.'"'.$chgstr.'>';
11803:                     for (my $i=0; $i<=$numchildren; $i++) {
11804:                         my $vpos = $i+1;
11805:                         my $selstr;
11806:                         if ($j == $i) {
11807:                             $selstr = ' selected="selected" ';
11808:                         }
11809:                         $text .= '<option value="'.$i.'"'.$selstr.'>'.$vpos.'</option>';
11810:                     }
11811:                     $text .= '</select>&nbsp;';
11812:                     if ($j < $numchildren) {
11813:                         my $deeper = $depth+1;
11814:                         $text .= $name.'&nbsp;'
11815:                                  .'<label><input type="checkbox" name="deletecategory" value="'
11816:                                  .$item.'" />'.&mt('Delete').'</label></span></td><td>';
11817:                         if(ref($path) eq 'ARRAY') {
11818:                             push(@{$path},$name);
11819:                             $text .= &build_category_rows($itemcount,$cats,$deeper,$name,$path,$idx);
11820:                             pop(@{$path});
11821:                         }
11822:                     } else {
11823:                         $text .= &mt('Add subcategory:').'&nbsp;</span><input type="text" size="20" name="addcategory_name_';
11824:                         if ($j == $numchildren) {
11825:                             $text .= $name;
11826:                         } else {
11827:                             $text .= $item;
11828:                         }
11829:                         $text .= '" value="" />';
11830:                     }
11831:                     $text .= '</td></tr>';
11832:                 }
11833:                 $text .= '</table></td>';
11834:             } else {
11835:                 my $higher = $depth-1;
11836:                 if ($higher == 0) {
11837:                     $name = &escape($parent).'::'.$higher;
11838:                 } else {
11839:                     if (ref($path) eq 'ARRAY') {
11840:                         $name = &escape($parent).':'.&escape($path->[-2]).':'.$higher;
11841:                     }
11842:                 }
11843:                 my $colspan;
11844:                 if ($parent ne 'instcode') {
11845:                     $colspan = $maxdepth - $depth - 1;
11846:                     $text .= '<td colspan="'.$colspan.'">'.&mt('Add subcategory:').'<input type="text" size="20" name="subcat_'.$name.'" value="" /></td>';
11847:                 }
11848:             }
11849:         }
11850:     }
11851:     return $text;
11852: }
11853: 
11854: sub modifiable_userdata_row {
11855:     my ($context,$item,$settings,$numinrow,$rowcount,$usertypes,$fieldsref,$titlesref,
11856:         $rowid,$customcss,$rowstyle,$itemdesc) = @_;
11857:     my ($role,$rolename,$statustype);
11858:     $role = $item;
11859:     if ($context eq 'cancreate') {
11860:         if ($item =~ /^(emailusername)_(.+)$/) {
11861:             $role = $1;
11862:             $statustype = $2;
11863:             if (ref($usertypes) eq 'HASH') {
11864:                 if ($usertypes->{$statustype}) {
11865:                     $rolename = &mt('Data provided by [_1]',$usertypes->{$statustype});
11866:                 } else {
11867:                     $rolename = &mt('Data provided by user');
11868:                 }
11869:             }
11870:         }
11871:     } elsif ($context eq 'selfcreate') {
11872:         if (ref($usertypes) eq 'HASH') {
11873:             $rolename = $usertypes->{$role};
11874:         } else {
11875:             $rolename = $role;
11876:         }
11877:     } elsif ($context eq 'lti') {
11878:         $rolename = &mt('Institutional data used (if available)');
11879:     } elsif ($context eq 'privacy') {
11880:         $rolename = $itemdesc;
11881:     } else {
11882:         if ($role eq 'cr') {
11883:             $rolename = &mt('Custom role');
11884:         } else {
11885:             $rolename = &Apache::lonnet::plaintext($role);
11886:         }
11887:     }
11888:     my (@fields,%fieldtitles);
11889:     if (ref($fieldsref) eq 'ARRAY') {
11890:         @fields = @{$fieldsref};
11891:     } else {
11892:         @fields = ('lastname','firstname','middlename','generation',
11893:                    'permanentemail','id');
11894:     }
11895:     if ((ref($titlesref) eq 'HASH')) {
11896:         %fieldtitles = %{$titlesref};
11897:     } else {
11898:         %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
11899:     }
11900:     my $output;
11901:     my $css_class;
11902:     if ($rowcount%2) {
11903:         $css_class = 'LC_odd_row';
11904:     }
11905:     if ($customcss) {
11906:         $css_class .= " $customcss";
11907:     }
11908:     $css_class =~ s/^\s+//;
11909:     if ($css_class) {
11910:         $css_class = ' class="'.$css_class.'"';
11911:     }
11912:     if ($rowstyle) {
11913:         $css_class .= ' style="'.$rowstyle.'"';
11914:     }
11915:     if ($rowid) {
11916:         $rowid = ' id="'.$rowid.'"';
11917:     }
11918:     $output = '<tr '.$css_class.$rowid.'>'.
11919:               '<td><span class="LC_nobreak">'.$rolename.'</span></td>'.
11920:               '<td class="LC_left_item" colspan="2"><table>';
11921:     my $rem;
11922:     my %checks;
11923:     my %current;
11924:     if (ref($settings) eq 'HASH') {
11925:         my $hashref;
11926:         if ($context eq 'lti') {
11927:             if (ref($settings) eq 'HASH') {
11928:                 $hashref = $settings->{'instdata'};
11929:             }
11930:         } elsif ($context eq 'privacy') {
11931:             my ($key,$inner) = split(/_/,$role);
11932:             if (ref($settings) eq 'HASH') {
11933:                 if (ref($settings->{$key}) eq 'HASH') {
11934:                     $hashref = $settings->{$key}->{$inner};
11935:                 }
11936:             }
11937:         } elsif (ref($settings->{$context}) eq 'HASH') {
11938:             if (ref($settings->{$context}->{$role}) eq 'HASH') {
11939:                 $hashref = $settings->{'lti_instdata'};
11940:             }
11941:             if ($role eq 'emailusername') {
11942:                 if ($statustype) {
11943:                     if (ref($settings->{$context}->{$role}->{$statustype}) eq 'HASH') {
11944:                         $hashref = $settings->{$context}->{$role}->{$statustype};
11945:                     }
11946:                 }
11947:             }
11948:         }
11949:         if (ref($hashref) eq 'HASH') { 
11950:             foreach my $field (@fields) {
11951:                 if ($hashref->{$field}) {
11952:                     if ($role eq 'emailusername') {
11953:                         $checks{$field} = $hashref->{$field};
11954:                     } else {
11955:                         $checks{$field} = ' checked="checked" ';
11956:                     }
11957:                 }
11958:             }
11959:         }
11960:     }
11961:  
11962:     my $total = scalar(@fields);
11963:     for (my $i=0; $i<$total; $i++) {
11964:         $rem = $i%($numinrow);
11965:         if ($rem == 0) {
11966:             if ($i > 0) {
11967:                 $output .= '</tr>';
11968:             }
11969:             $output .= '<tr>';
11970:         }
11971:         my $check = ' ';
11972:         unless ($role eq 'emailusername') {
11973:             if (exists($checks{$fields[$i]})) {
11974:                 $check = $checks{$fields[$i]};
11975:             } elsif ($context eq 'privacy') {
11976:                 if ($role =~ /^priv_(domain|course)$/) {
11977:                     if (ref($settings) ne 'HASH') {
11978:                         $check = ' checked="checked" ';
11979:                     }
11980:                 } elsif ($role =~ /^priv_(author|community)$/) {
11981:                     if (ref($settings) ne 'HASH') {
11982:                         unless ($fields[$i] eq 'id') {
11983:                             $check = ' checked="checked" ';
11984:                         }
11985:                     }
11986:                 } elsif ($role =~ /^(unpriv|othdom)_/) {
11987:                     if (ref($settings) ne 'HASH') {
11988:                         if (($fields[$i] eq 'lastname') || ($fields[$i] eq 'firstname')) {
11989:                             $check = ' checked="checked" ';
11990:                         }
11991:                     }
11992:                 }
11993:             } elsif ($context ne 'lti') {
11994:                 if ($role eq 'st') {
11995:                     if (ref($settings) ne 'HASH') {
11996:                         $check = ' checked="checked" '; 
11997:                     }
11998:                 }
11999:             }
12000:         }
12001:         $output .= '<td class="LC_left_item">'.
12002:                    '<span class="LC_nobreak">';
12003:         my $prefix = 'canmodify';
12004:         if ($role eq 'emailusername') {
12005:             unless ($checks{$fields[$i]} =~ /^(required|optional)$/) {
12006:                 $checks{$fields[$i]} = 'omit';
12007:             }
12008:             foreach my $option ('required','optional','omit') {
12009:                 my $checked='';
12010:                 if ($checks{$fields[$i]} eq $option) {
12011:                     $checked='checked="checked" ';
12012:                 }
12013:                 $output .= '<label>'.
12014:                            '<input type="radio" name="'.$prefix.'_'.$item.'_'.$fields[$i].'" value="'.$option.'" '.$checked.'/>'.
12015:                            &mt($option).'</label>'.('&nbsp;' x2);
12016:             }
12017:             $output .= '<i>'.$fieldtitles{$fields[$i]}.'</i>';
12018:         } else {
12019:             if ($context eq 'lti') {
12020:                 $prefix = 'lti';
12021:             } elsif ($context eq 'privacy') {
12022:                 $prefix = 'privacy';
12023:             }
12024:             $output .= '<label>'.
12025:                        '<input type="checkbox" name="'.$prefix.'_'.$role.'" '.
12026:                        'value="'.$fields[$i].'"'.$check.'/>'.$fieldtitles{$fields[$i]}.
12027:                        '</label>';
12028:         }
12029:         $output .= '</span></td>';
12030:     }
12031:     $rem = $total%$numinrow;
12032:     my $colsleft;
12033:     if ($rem) {
12034:         $colsleft = $numinrow - $rem;
12035:     }
12036:     if ($colsleft > 1) {
12037:         $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">'.
12038:                    '&nbsp;</td>';
12039:     } elsif ($colsleft == 1) {
12040:         $output .= '<td class="LC_left_item">&nbsp;</td>';
12041:     }
12042:     $output .= '</tr></table></td></tr>';
12043:     return $output;
12044: }
12045: 
12046: sub insttypes_row {
12047:     my ($settings,$types,$usertypes,$dom,$numinrow,$othertitle,$context,$rowtotal,$onclick,
12048:         $customcss,$rowstyle) = @_;
12049:     my %lt = &Apache::lonlocal::texthash (
12050:                       cansearch => 'Users allowed to search',
12051:                       statustocreate => 'Institutional affiliation(s) able to create own account (login/SSO)',
12052:                       lockablenames => 'User preference to lock name',
12053:                       selfassign    => 'Self-reportable affiliations',
12054:                       overrides     => "Override domain's helpdesk settings based on requester's affiliation",
12055:              );
12056:     my $showdom;
12057:     if ($context eq 'cansearch') {
12058:         $showdom = ' ('.$dom.')';
12059:     }
12060:     my $class = 'LC_left_item';
12061:     if ($context eq 'statustocreate') {
12062:         $class = 'LC_right_item';
12063:     }
12064:     my $css_class;
12065:     if ($$rowtotal%2) {
12066:         $css_class = 'LC_odd_row';
12067:     }
12068:     if ($customcss) {
12069:         $css_class .= ' '.$customcss;
12070:     }
12071:     $css_class =~ s/^\s+//;
12072:     if ($css_class) {
12073:         $css_class = ' class="'.$css_class.'"';
12074:     }
12075:     if ($rowstyle) {
12076:         $css_class .= ' style="'.$rowstyle.'"';
12077:     }
12078:     if ($onclick) {
12079:         $onclick = 'onclick="'.$onclick.'" ';
12080:     }
12081:     my $output = '<tr'.$css_class.'>'.
12082:                  '<td>'.$lt{$context}.$showdom.
12083:                  '</td><td class="'.$class.'" colspan="2"><table>';
12084:     my $rem;
12085:     if (ref($types) eq 'ARRAY') {
12086:         for (my $i=0; $i<@{$types}; $i++) {
12087:             if (defined($usertypes->{$types->[$i]})) {
12088:                 my $rem = $i%($numinrow);
12089:                 if ($rem == 0) {
12090:                     if ($i > 0) {
12091:                         $output .= '</tr>';
12092:                     }
12093:                     $output .= '<tr>';
12094:                 }
12095:                 my $check = ' ';
12096:                 if (ref($settings) eq 'HASH') {
12097:                     if (ref($settings->{$context}) eq 'ARRAY') {
12098:                         if (grep(/^\Q$types->[$i]\E$/,@{$settings->{$context}})) {
12099:                             $check = ' checked="checked" ';
12100:                         }
12101:                     } elsif (ref($settings->{$context}) eq 'HASH') {
12102:                         if (ref($settings->{$context}->{$types->[$i]}) eq 'HASH') {
12103:                             $check = ' checked="checked" ';
12104:                         }
12105:                     } elsif ($context eq 'statustocreate') {
12106:                         $check = ' checked="checked" ';
12107:                     }
12108:                 }
12109:                 $output .= '<td class="LC_left_item">'.
12110:                            '<span class="LC_nobreak"><label>'.
12111:                            '<input type="checkbox" name="'.$context.'" '.
12112:                            'value="'.$types->[$i].'"'.$check.$onclick.' />'.
12113:                            $usertypes->{$types->[$i]}.'</label></span></td>';
12114:             }
12115:         }
12116:         $rem = @{$types}%($numinrow);
12117:     }
12118:     my $colsleft = $numinrow - $rem;
12119:     if ($context eq 'overrides') {
12120:         if ($colsleft > 1) {
12121:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12122:         } else {
12123:             $output .= '<td class="LC_left_item">';
12124:         }
12125:         $output .= '&nbsp;';  
12126:     } else {
12127:         if ($rem == 0) {
12128:             $output .= '<tr>';
12129:         }
12130:         if ($colsleft > 1) {
12131:             $output .= '<td colspan="'.$colsleft.'" class="LC_left_item">';
12132:         } else {
12133:             $output .= '<td class="LC_left_item">';
12134:         }
12135:         my $defcheck = ' ';
12136:         if (ref($settings) eq 'HASH') {  
12137:             if (ref($settings->{$context}) eq 'ARRAY') {
12138:                 if (grep(/^default$/,@{$settings->{$context}})) {
12139:                     $defcheck = ' checked="checked" ';
12140:                 }
12141:             } elsif ($context eq 'statustocreate') {
12142:                 $defcheck = ' checked="checked" ';
12143:             }
12144:         }
12145:         $output .= '<span class="LC_nobreak"><label>'.
12146:                    '<input type="checkbox" name="'.$context.'" '.
12147:                    'value="default"'.$defcheck.$onclick.' />'.
12148:                    $othertitle.'</label></span>';
12149:     }
12150:     $output .= '</td></tr></table></td></tr>';
12151:     return $output;
12152: }
12153: 
12154: sub sorted_searchtitles {
12155:     my %searchtitles = &Apache::lonlocal::texthash(
12156:                          'uname' => 'username',
12157:                          'lastname' => 'last name',
12158:                          'lastfirst' => 'last name, first name',
12159:                      );
12160:     my @titleorder = ('uname','lastname','lastfirst');
12161:     return (\%searchtitles,\@titleorder);
12162: }
12163: 
12164: sub sorted_searchtypes {
12165:     my %srchtypes_desc = (
12166:                            exact    => 'is exact match',
12167:                            contains => 'contains ..',
12168:                            begins   => 'begins with ..',
12169:                          );
12170:     my @srchtypeorder = ('exact','begins','contains');
12171:     return (\%srchtypes_desc,\@srchtypeorder);
12172: }
12173: 
12174: sub usertype_update_row {
12175:     my ($settings,$usertypes,$fieldtitles,$fields,$types,$rownums) = @_;
12176:     my $datatable;
12177:     my $numinrow = 4;
12178:     foreach my $type (@{$types}) {
12179:         if (defined($usertypes->{$type})) {
12180:             $$rownums ++;
12181:             my $css_class = $$rownums%2?' class="LC_odd_row"':'';
12182:             $datatable .= '<tr'.$css_class.'><td>'.$usertypes->{$type}.
12183:                           '</td><td class="LC_left_item"><table>';
12184:             for (my $i=0; $i<@{$fields}; $i++) {
12185:                 my $rem = $i%($numinrow);
12186:                 if ($rem == 0) {
12187:                     if ($i > 0) {
12188:                         $datatable .= '</tr>';
12189:                     }
12190:                     $datatable .= '<tr>';
12191:                 }
12192:                 my $check = ' ';
12193:                 if (ref($settings) eq 'HASH') {
12194:                     if (ref($settings->{'fields'}) eq 'HASH') {
12195:                         if (ref($settings->{'fields'}{$type}) eq 'ARRAY') {
12196:                             if (grep(/^\Q$fields->[$i]\E$/,@{$settings->{'fields'}{$type}})) {
12197:                                 $check = ' checked="checked" ';
12198:                             }
12199:                         }
12200:                     }
12201:                 }
12202: 
12203:                 if ($i == @{$fields}-1) {
12204:                     my $colsleft = $numinrow - $rem;
12205:                     if ($colsleft > 1) {
12206:                         $datatable .= '<td colspan="'.$colsleft.'">';
12207:                     } else {
12208:                         $datatable .= '<td>';
12209:                     }
12210:                 } else {
12211:                     $datatable .= '<td>';
12212:                 }
12213:                 $datatable .= '<span class="LC_nobreak"><label>'.
12214:                               '<input type="checkbox" name="updateable_'.$type.
12215:                               '_'.$fields->[$i].'" value="1"'.$check.'/>'.
12216:                               $fieldtitles->{$fields->[$i]}.'</label></span></td>';
12217:             }
12218:             $datatable .= '</tr></table></td></tr>';
12219:         }
12220:     }
12221:     return $datatable;
12222: }
12223: 
12224: sub modify_login {
12225:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
12226:     my ($resulttext,$errors,$colchgtext,%changes,%colchanges,%newfile,%newurl,
12227:         %curr_loginvia,%loginhash,@currlangs,@newlangs,$addedfile,%title,@offon,
12228:         %currsaml,%saml,%samltext,%samlimg,%samlalt,%samlurl,%samltitle,%samlnotsso);
12229:     %title = ( coursecatalog => 'Display course catalog',
12230:                adminmail => 'Display administrator E-mail address',
12231:                helpdesk  => 'Display "Contact Helpdesk" link',
12232:                newuser => 'Link for visitors to create a user account',
12233:                loginheader => 'Log-in box header',
12234:                saml => 'Dual SSO and non-SSO login');
12235:     @offon = ('off','on');
12236:     if (ref($domconfig{login}) eq 'HASH') {
12237:         if (ref($domconfig{login}{loginvia}) eq 'HASH') {
12238:             foreach my $lonhost (keys(%{$domconfig{login}{loginvia}})) {
12239:                 $curr_loginvia{$lonhost} = $domconfig{login}{loginvia}{$lonhost};
12240:             }
12241:         }
12242:         if (ref($domconfig{login}{'saml'}) eq 'HASH') {
12243:             foreach my $lonhost (keys(%{$domconfig{login}{'saml'}})) {
12244:                 if (ref($domconfig{login}{'saml'}{$lonhost}) eq 'HASH') {
12245:                     $currsaml{$lonhost} = $domconfig{login}{'saml'}{$lonhost};
12246:                     $saml{$lonhost} = 1;
12247:                     $samltext{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'text'};
12248:                     $samlurl{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'url'};
12249:                     $samlalt{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'alt'};
12250:                     $samlimg{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'img'};
12251:                     $samltitle{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'title'};
12252:                     $samlnotsso{$lonhost} = $domconfig{login}{'saml'}{$lonhost}{'notsso'};
12253:                 }
12254:             }
12255:         }
12256:     }
12257:     ($errors,%colchanges) = &modify_colors($r,$dom,$confname,['login'],
12258:                                            \%domconfig,\%loginhash);
12259:     my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12260:     foreach my $item (@toggles) {
12261:         $loginhash{login}{$item} = $env{'form.'.$item};
12262:     }
12263:     $loginhash{login}{loginheader} = $env{'form.loginheader'};
12264:     if (ref($colchanges{'login'}) eq 'HASH') {  
12265:         $colchgtext = &display_colorchgs($dom,\%colchanges,['login'],
12266:                                          \%loginhash);
12267:     }
12268: 
12269:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
12270:     my %domservers = &Apache::lonnet::get_servers($dom);
12271:     my @loginvia_attribs = ('serverpath','custompath','exempt');
12272:     if (keys(%servers) > 1) {
12273:         foreach my $lonhost (keys(%servers)) {
12274:             next if ($env{'form.'.$lonhost.'_server'} eq $lonhost);
12275:             if (ref($curr_loginvia{$lonhost}) eq 'HASH') {
12276:                 if ($env{'form.'.$lonhost.'_server'} eq $curr_loginvia{$lonhost}{'server'}) {
12277:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $curr_loginvia{$lonhost}{'server'};
12278:                 } elsif ($curr_loginvia{$lonhost}{'server'} ne '') {
12279:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12280:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12281:                         $changes{'loginvia'}{$lonhost} = 1;
12282:                     } else {
12283:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = '';
12284:                         $changes{'loginvia'}{$lonhost} = 1;
12285:                     }
12286:                 } else {
12287:                     if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12288:                         $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12289:                         $changes{'loginvia'}{$lonhost} = 1;
12290:                     }
12291:                 }
12292:                 if ($loginhash{login}{loginvia}{$lonhost}{'server'} eq '') {
12293:                     foreach my $item (@loginvia_attribs) {
12294:                         $loginhash{login}{loginvia}{$lonhost}{$item} = '';
12295:                     }
12296:                 } else {
12297:                     foreach my $item (@loginvia_attribs) {
12298:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12299:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12300:                             $env{'form.'.$lonhost.'_custompath'} =~ s/\s+//g;
12301:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12302:                                 $new = '/';
12303:                             }
12304:                         }
12305:                         if (($item eq 'custompath') && 
12306:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12307:                             $new = '';
12308:                         }
12309:                         if ($new ne $curr_loginvia{$lonhost}{$item}) {
12310:                             $changes{'loginvia'}{$lonhost} = 1;
12311:                         }
12312:                         if ($item eq 'exempt') {
12313:                             $new = &check_exempt_addresses($new);
12314:                         }
12315:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12316:                     }
12317:                 }
12318:             } else {
12319:                 if (defined($servers{$env{'form.'.$lonhost.'_server'}})) {
12320:                     $loginhash{login}{loginvia}{$lonhost}{'server'} = $env{'form.'.$lonhost.'_server'};
12321:                     $changes{'loginvia'}{$lonhost} = 1;
12322:                     foreach my $item (@loginvia_attribs) {
12323:                         my $new = $env{'form.'.$lonhost.'_'.$item};
12324:                         if (($item eq 'serverpath') && ($new eq 'custom')) {
12325:                             if ($env{'form.'.$lonhost.'_custompath'} eq '') {
12326:                                 $new = '/';
12327:                             }
12328:                         }
12329:                         if (($item eq 'custompath') && 
12330:                             ($env{'form.'.$lonhost.'_serverpath'} ne 'custom')) {
12331:                             $new = '';
12332:                         }
12333:                         $loginhash{login}{loginvia}{$lonhost}{$item} = $new;
12334:                     }
12335:                 }
12336:             }
12337:         }
12338:     }
12339: 
12340:     my $servadm = $r->dir_config('lonAdmEMail');
12341:     my %langchoices = &Apache::lonlocal::texthash(&get_languages_hash());
12342:     if (ref($domconfig{'login'}) eq 'HASH') {
12343:         if (ref($domconfig{'login'}{'helpurl'}) eq 'HASH') {
12344:             foreach my $lang (sort(keys(%{$domconfig{'login'}{'helpurl'}}))) {
12345:                 if ($lang eq 'nolang') {
12346:                     push(@currlangs,$lang);
12347:                 } elsif (defined($langchoices{$lang})) {
12348:                     push(@currlangs,$lang);
12349:                 } else {
12350:                     next;
12351:                 }
12352:             }
12353:         }
12354:     }
12355:     my @delurls = &Apache::loncommon::get_env_multiple('form.loginhelpurl_del');
12356:     if (@currlangs > 0) {
12357:         foreach my $lang (@currlangs) {
12358:             if (grep(/^\Q$lang\E$/,@delurls)) {
12359:                 $changes{'helpurl'}{$lang} = 1;
12360:             } elsif ($env{'form.loginhelpurl_'.$lang.'.filename'}) {
12361:                 $changes{'helpurl'}{$lang} = 1;
12362:                 $newfile{$lang} = $env{'form.loginhelpurl_'.$lang.'.filename'};
12363:                 push(@newlangs,$lang);
12364:             } else {
12365:                 $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12366:             }
12367:         }
12368:     }
12369:     unless (grep(/^nolang$/,@currlangs)) {
12370:         if ($env{'form.loginhelpurl_nolang.filename'}) {
12371:             $changes{'helpurl'}{'nolang'} = 1;
12372:             $newfile{'nolang'} = $env{'form.loginhelpurl_nolang.filename'};
12373:             push(@newlangs,'nolang');
12374:         }
12375:     }
12376:     if ($env{'form.loginhelpurl_add_lang'}) {
12377:         if ((defined($langchoices{$env{'form.loginhelpurl_add_lang'}})) &&
12378:             ($env{'form.loginhelpurl_add_file.filename'})) {
12379:             $newfile{$env{'form.loginhelpurl_add_lang'}} = $env{'form.loginhelpurl_add_file.filename'};
12380:             $addedfile = $env{'form.loginhelpurl_add_lang'};
12381:         }
12382:     }
12383:     if ((@newlangs > 0) || ($addedfile)) {
12384:         my $error;
12385:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12386:         if ($configuserok eq 'ok') {
12387:             if ($switchserver) {
12388:                 $error = &mt("Upload of custom help file is not permitted to this server: [_1]",$switchserver);
12389:             } elsif ($author_ok eq 'ok') {
12390:                 my @allnew = @newlangs;
12391:                 if ($addedfile ne '') {
12392:                     push(@allnew,$addedfile);
12393:                 }
12394:                 foreach my $lang (@allnew) {
12395:                     my $formelem = 'loginhelpurl_'.$lang;
12396:                     if ($lang eq $env{'form.loginhelpurl_add_lang'}) {
12397:                         $formelem = 'loginhelpurl_add_file';
12398:                     }
12399:                     (my $result,$newurl{$lang}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12400:                                                                "help/$lang",'','',$newfile{$lang});
12401:                     if ($result eq 'ok') {
12402:                         $loginhash{'login'}{'helpurl'}{$lang} = $newurl{$lang};
12403:                         $changes{'helpurl'}{$lang} = 1;
12404:                     } else {
12405:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$newfile{$lang},$result);
12406:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12407:                         if ((grep(/^\Q$lang\E$/,@currlangs)) &&
12408:                             (!grep(/^\Q$lang\E$/,@delurls))) {
12409:                             $loginhash{'login'}{'helpurl'}{$lang} = $domconfig{'login'}{'helpurl'}{$lang};
12410:                         }
12411:                     }
12412:                 }
12413:             } else {
12414:                 $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);
12415:             }
12416:         } else {
12417:             $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);
12418:         }
12419:         if ($error) {
12420:             &Apache::lonnet::logthis($error);
12421:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12422:         }
12423:     }
12424: 
12425:     my (%currheadtagurls,%currexempt,@newhosts,%newheadtagurls,%possexempt);
12426:     if (ref($domconfig{'login'}) eq 'HASH') {
12427:         if (ref($domconfig{'login'}{'headtag'}) eq 'HASH') {
12428:             foreach my $lonhost (keys(%{$domconfig{'login'}{'headtag'}})) {
12429:                 if ($domservers{$lonhost}) {
12430:                     if (ref($domconfig{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12431:                         $currheadtagurls{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'url'};
12432:                         $currexempt{$lonhost} = $domconfig{'login'}{'headtag'}{$lonhost}{'exempt'};
12433:                     }
12434:                 }
12435:             }
12436:         }
12437:     }
12438:     my @delheadtagurls = &Apache::loncommon::get_env_multiple('form.loginheadtag_del');
12439:     foreach my $lonhost (sort(keys(%domservers))) {
12440:         if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12441:             $changes{'headtag'}{$lonhost} = 1;
12442:         } else {
12443:             if ($env{'form.loginheadtagexempt_'.$lonhost}) {
12444:                 $possexempt{$lonhost} = &check_exempt_addresses($env{'form.loginheadtagexempt_'.$lonhost});
12445:             }
12446:             if ($env{'form.loginheadtag_'.$lonhost.'.filename'}) {
12447:                 push(@newhosts,$lonhost);
12448:             } elsif ($currheadtagurls{$lonhost}) {
12449:                 $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $currheadtagurls{$lonhost};
12450:                 if ($currexempt{$lonhost}) {
12451:                     if ((!exists($possexempt{$lonhost})) || ($possexempt{$lonhost} ne $currexempt{$lonhost})) {
12452:                         $changes{'headtag'}{$lonhost} = 1;
12453:                     }
12454:                 } elsif ($possexempt{$lonhost}) {
12455:                     $changes{'headtag'}{$lonhost} = 1;
12456:                 }
12457:                 if ($possexempt{$lonhost}) {
12458:                     $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12459:                 }
12460:             }
12461:         }
12462:     }
12463:     if (@newhosts) {
12464:         my $error;
12465:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12466:         if ($configuserok eq 'ok') {
12467:             if ($switchserver) {
12468:                 $error = &mt("Upload of custom markup is not permitted to this server: [_1]",$switchserver);
12469:             } elsif ($author_ok eq 'ok') {
12470:                 foreach my $lonhost (@newhosts) {
12471:                     my $formelem = 'loginheadtag_'.$lonhost;
12472:                     (my $result,$newheadtagurls{$lonhost}) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12473:                                                                           "login/headtag/$lonhost",'','',
12474:                                                                           $env{'form.loginheadtag_'.$lonhost.'.filename'});
12475:                     if ($result eq 'ok') {
12476:                         $loginhash{'login'}{'headtag'}{$lonhost}{'url'} = $newheadtagurls{$lonhost};
12477:                         $changes{'headtag'}{$lonhost} = 1;
12478:                         if ($possexempt{$lonhost}) {
12479:                             $loginhash{'login'}{'headtag'}{$lonhost}{'exempt'} = $possexempt{$lonhost};
12480:                         }
12481:                     } else {
12482:                         my $puberror = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",
12483:                                            $newheadtagurls{$lonhost},$result);
12484:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12485:                         if ((grep(/^\Q$lonhost\E$/,keys(%currheadtagurls))) &&
12486:                             (!grep(/^\Q$lonhost\E$/,@delheadtagurls))) {
12487:                             $loginhash{'login'}{'headtag'}{$lonhost} = $currheadtagurls{$lonhost};
12488:                         }
12489:                     }
12490:                 }
12491:             } else {
12492:                 $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);
12493:             }
12494:         } else {
12495:             $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);
12496:         }
12497:         if ($error) {
12498:             &Apache::lonnet::logthis($error);
12499:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12500:         }
12501:     }
12502:     my @delsamlimg = &Apache::loncommon::get_env_multiple('form.saml_img_del');
12503:     my @newsamlimgs;
12504:     foreach my $lonhost (keys(%domservers)) {
12505:         if ($env{'form.saml_'.$lonhost}) {
12506:             if ($env{'form.saml_img_'.$lonhost.'.filename'}) {
12507:                 push(@newsamlimgs,$lonhost);
12508:             }
12509:             foreach my $item ('text','alt','url','title','notsso') {
12510:                 $env{'form.saml_'.$item.'_'.$lonhost} =~ s/^\s+|\s+$//g;
12511:             }
12512:             if ($saml{$lonhost}) {
12513:                 if (grep(/^\Q$lonhost\E$/,@delsamlimg)) {
12514: #FIXME Need to obsolete published image
12515:                     delete($currsaml{$lonhost}{'img'});
12516:                     $changes{'saml'}{$lonhost} = 1;
12517:                 }
12518:                 if ($env{'form.saml_alt_'.$lonhost} ne $samlalt{$lonhost}) {
12519:                     $changes{'saml'}{$lonhost} = 1;
12520:                 }
12521:                 if ($env{'form.saml_text_'.$lonhost} ne $samltext{$lonhost}) {
12522:                     $changes{'saml'}{$lonhost} = 1;
12523:                 }
12524:                 if ($env{'form.saml_url_'.$lonhost} ne $samlurl{$lonhost}) {
12525:                     $changes{'saml'}{$lonhost} = 1;
12526:                 }
12527:                 if ($env{'form.saml_title_'.$lonhost} ne $samltitle{$lonhost}) {
12528:                     $changes{'saml'}{$lonhost} = 1;
12529:                 }
12530:                 if ($env{'form.saml_notsso_'.$lonhost} ne $samlnotsso{$lonhost}) {
12531:                     $changes{'saml'}{$lonhost} = 1;
12532:                 }
12533:             } else {
12534:                 $changes{'saml'}{$lonhost} = 1;
12535:             }
12536:             foreach my $item ('text','alt','url','title','notsso') {
12537:                 $currsaml{$lonhost}{$item} = $env{'form.saml_'.$item.'_'.$lonhost};
12538:             }
12539:         } else {
12540:             if ($saml{$lonhost}) {  
12541:                 $changes{'saml'}{$lonhost} = 1;
12542:                 delete($currsaml{$lonhost});
12543:             }
12544:         }
12545:     }
12546:     foreach my $posshost (keys(%currsaml)) {
12547:         unless (exists($domservers{$posshost})) { 
12548:             delete($currsaml{$posshost}); 
12549:         }
12550:     }
12551:     %{$loginhash{'login'}{'saml'}} = %currsaml;
12552:     if (@newsamlimgs) {
12553:         my $error;
12554:         my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
12555:         if ($configuserok eq 'ok') {
12556:             if ($switchserver) {
12557:                 $error = &mt("Upload of SSO Button Image is not permitted to this server: [_1].",$switchserver);
12558:             } elsif ($author_ok eq 'ok') {
12559:                 foreach my $lonhost (@newsamlimgs) {
12560:                     my $formelem = 'saml_img_'.$lonhost;
12561:                     my ($result,$imgurl) = &publishlogo($r,'upload',$formelem,$dom,$confname,
12562:                                                         "login/saml/$lonhost",'','',
12563:                                                         $env{'form.saml_img_'.$lonhost.'.filename'});
12564:                     if ($result eq 'ok') {
12565:                         $currsaml{$lonhost}{'img'} = $imgurl;
12566:                         $loginhash{'login'}{'saml'}{$lonhost}{'img'} = $imgurl;
12567:                         $changes{'saml'}{$lonhost} = 1;
12568:                     } else {
12569:                         my $puberror = &mt("Upload of SSO button image failed for [_1] because an error occurred publishing the file in RES space. Error was: [_2].",
12570:                                            $lonhost,$result);
12571:                         $errors .= '<li><span class="LC_error">'.$puberror.'</span></li>';
12572:                     }
12573:                 }
12574:             } else {
12575:                 $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);
12576:             }
12577:         } else {
12578:             $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);
12579:         }
12580:         if ($error) {
12581:             &Apache::lonnet::logthis($error);
12582:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12583:         }
12584:     }
12585:     &process_captcha('login',\%changes,$loginhash{'login'},$domconfig{'login'});
12586: 
12587:     my $defaulthelpfile = '/adm/loginproblems.html';
12588:     my $defaulttext = &mt('Default in use');
12589: 
12590:     my $putresult = &Apache::lonnet::put_dom('configuration',\%loginhash,
12591:                                              $dom);
12592:     if ($putresult eq 'ok') {
12593:         my @toggles = ('coursecatalog','adminmail','helpdesk','newuser');
12594:         my %defaultchecked = (
12595:                     'coursecatalog' => 'on',
12596:                     'helpdesk'      => 'on',
12597:                     'adminmail'     => 'off',
12598:                     'newuser'       => 'off',
12599:         );
12600:         if (ref($domconfig{'login'}) eq 'HASH') {
12601:             foreach my $item (@toggles) {
12602:                 if ($defaultchecked{$item} eq 'on') { 
12603:                     if (($domconfig{'login'}{$item} eq '0') &&
12604:                         ($env{'form.'.$item} eq '1')) {
12605:                         $changes{$item} = 1;
12606:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12607:                               $domconfig{'login'}{$item} eq '1') &&
12608:                              ($env{'form.'.$item} eq '0')) {
12609:                         $changes{$item} = 1;
12610:                     }
12611:                 } elsif ($defaultchecked{$item} eq 'off') {
12612:                     if (($domconfig{'login'}{$item} eq '1') &&
12613:                         ($env{'form.'.$item} eq '0')) {
12614:                         $changes{$item} = 1;
12615:                     } elsif (($domconfig{'login'}{$item} eq '' ||
12616:                               $domconfig{'login'}{$item} eq '0') &&
12617:                              ($env{'form.'.$item} eq '1')) {
12618:                         $changes{$item} = 1;
12619:                     }
12620:                 }
12621:             }
12622:         }
12623:         if (keys(%changes) > 0 || $colchgtext) {
12624:             &Apache::loncommon::devalidate_domconfig_cache($dom);
12625:             if (exists($changes{'saml'})) {
12626:                 my $hostid_in_use;
12627:                 my @hosts = &Apache::lonnet::current_machine_ids();
12628:                 if (@hosts > 1) {
12629:                     foreach my $hostid (@hosts) {
12630:                         if (&Apache::lonnet::host_domain($hostid) eq $dom) {
12631:                             $hostid_in_use = $hostid;
12632:                             last;
12633:                         }
12634:                     }
12635:                 } else {
12636:                     $hostid_in_use = $r->dir_config('lonHostID');
12637:                 }
12638:                 if (($hostid_in_use) &&
12639:                     (&Apache::lonnet::host_domain($hostid_in_use) eq $dom)) {
12640:                     &Apache::lonnet::devalidate_cache_new('samllanding',$hostid_in_use);
12641:                 }
12642:                 if (ref($lastactref) eq 'HASH') {
12643:                     if (ref($changes{'saml'}) eq 'HASH') {
12644:                         my %updates;
12645:                         map { $updates{$_} = 1; } keys(%{$changes{'saml'}});
12646:                         $lastactref->{'samllanding'} = \%updates;
12647:                     }
12648:                 }
12649:             }
12650:             if (ref($lastactref) eq 'HASH') {
12651:                 $lastactref->{'domainconfig'} = 1;
12652:             }
12653:             $resulttext = &mt('Changes made:').'<ul>';
12654:             foreach my $item (sort(keys(%changes))) {
12655:                 if ($item eq 'loginvia') {
12656:                     if (ref($changes{$item}) eq 'HASH') {
12657:                         $resulttext .= '<li>'.&mt('Log-in page availability:').'<ul>';
12658:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12659:                             if (defined($servers{$loginhash{login}{loginvia}{$lonhost}{'server'}})) {
12660:                                 if (ref($loginhash{login}{loginvia}{$lonhost}) eq 'HASH') {
12661:                                     my $protocol = $Apache::lonnet::protocol{$env{'form.'.$lonhost.'_server'}};
12662:                                     $protocol = 'http' if ($protocol ne 'https');
12663:                                     my $target = $protocol.'://'.$servers{$env{'form.'.$lonhost.'_server'}};
12664: 
12665:                                     if ($loginhash{login}{loginvia}{$lonhost}{'serverpath'} eq 'custom') {
12666:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'custompath'};
12667:                                     } else {
12668:                                         $target .= $loginhash{login}{loginvia}{$lonhost}{'serverpath'}; 
12669:                                     }
12670:                                     $resulttext .= '<li>'.&mt('Server: [_1] log-in page redirects to [_2].',$servers{$lonhost},'<a href="'.$target.'">'.$target.'</a>');
12671:                                     if ($loginhash{login}{loginvia}{$lonhost}{'exempt'} ne '') {
12672:                                         $resulttext .= '&nbsp;'.&mt('No redirection for clients from following IPs:').'&nbsp;'.$loginhash{login}{loginvia}{$lonhost}{'exempt'};
12673:                                     }
12674:                                     $resulttext .= '</li>';
12675:                                 } else {
12676:                                     $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$lonhost).'</li>';
12677:                                 }
12678:                             } else {
12679:                                 $resulttext .= '<li>'.&mt('Server: [_1] has standard log-in page.',$servers{$lonhost}).'</li>';
12680:                             }
12681:                         }
12682:                         $resulttext .= '</ul></li>';
12683:                     }
12684:                 } elsif ($item eq 'helpurl') {
12685:                     if (ref($changes{$item}) eq 'HASH') {
12686:                         foreach my $lang (sort(keys(%{$changes{$item}}))) {
12687:                             if (grep(/^\Q$lang\E$/,@delurls)) {
12688:                                 my ($chg,$link);
12689:                                 $link = &Apache::loncommon::modal_link($defaulthelpfile,$defaulttext,600,500);
12690:                                 if ($lang eq 'nolang') {
12691:                                     $chg = &mt('custom log-in help file removed for no preferred language; [_1]',$link);
12692:                                 } else {
12693:                                     $chg = &mt('custom log-in help file removed for specific language: [_1]; [_2]',$langchoices{$lang},$link);
12694:                                 }
12695:                                 $resulttext .= '<li>'.$chg.'</li>';
12696:                             } else {
12697:                                 my $chg;
12698:                                 if ($lang eq 'nolang') {
12699:                                     $chg = &mt('custom log-in help file for no preferred language');
12700:                                 } else {
12701:                                     $chg = &mt('custom log-in help file for specific language: [_1]',$langchoices{$lang});
12702:                                 }
12703:                                 $resulttext .= '<li>'.&Apache::loncommon::modal_link(
12704:                                                       $loginhash{'login'}{'helpurl'}{$lang}.
12705:                                                       '?inhibitmenu=yes',$chg,600,500).
12706:                                                '</li>';
12707:                             }
12708:                         }
12709:                     }
12710:                 } elsif ($item eq 'headtag') {
12711:                     if (ref($changes{$item}) eq 'HASH') {
12712:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12713:                             if (grep(/^\Q$lonhost\E$/,@delheadtagurls)) {
12714:                                 $resulttext .= '<li>'.&mt('custom markup file removed for [_1]',$domservers{$lonhost}).'</li>';
12715:                             } elsif (ref($loginhash{'login'}{'headtag'}{$lonhost}) eq 'HASH') {
12716:                                 $resulttext .= '<li><a href="'.
12717:                                                "javascript:void(open('$loginhash{'login'}{'headtag'}{$lonhost}{'url'}?inhibitmenu=yes','Custom_HeadTag',
12718:                                                'menubar=0,toolbar=1,scrollbars=1,width=600,height=500,resizable=yes'))".
12719:                                                '">'.&mt('custom markup').'</a> '.&mt('(for [_1])',$servers{$lonhost}).' ';
12720:                                 if ($possexempt{$lonhost}) {
12721:                                     $resulttext .= &mt('not included for client IP(s): [_1]',$possexempt{$lonhost});
12722:                                 } else {
12723:                                     $resulttext .= &mt('included for any client IP');
12724:                                 }
12725:                                 $resulttext .= '</li>';
12726:                             }
12727:                         }
12728:                     }
12729:                 } elsif ($item eq 'saml') {
12730:                     if (ref($changes{$item}) eq 'HASH') {
12731:                         my %notlt = (
12732:                                        text   => 'Text for log-in by SSO',
12733:                                        img    => 'SSO button image',
12734:                                        alt    => 'Alt text for button image',
12735:                                        url    => 'SSO URL',
12736:                                        title  => 'Tooltip for SSO link',
12737:                                        notsso => 'Text for non-SSO log-in',
12738:                                     );
12739:                         foreach my $lonhost (sort(keys(%{$changes{$item}}))) {
12740:                             if (ref($currsaml{$lonhost}) eq 'HASH') {
12741:                                 $resulttext .= '<li>'.&mt("$title{$item} in use for [_1]","<b>$lonhost</b>").
12742:                                                '<ul>';
12743:                                 foreach my $key ('text','img','alt','url','title','notsso') {
12744:                                     if ($currsaml{$lonhost}{$key} eq '') {
12745:                                         $resulttext .= '<li>'.&mt("$notlt{$key} not in use").'</li>';
12746:                                     } else {
12747:                                         my $value = "'$currsaml{$lonhost}{$key}'";
12748:                                         if ($key eq 'img') {
12749:                                             $value = '<img src="'.$currsaml{$lonhost}{$key}.'" />';
12750:                                         }
12751:                                         $resulttext .= '<li>'.&mt("$notlt{$key} set to: [_1]",
12752:                                                                   $value).'</li>';
12753:                                     }
12754:                                 }
12755:                                 $resulttext .= '</ul></li>';
12756:                             } else {
12757:                                 $resulttext .= '<li>'.&mt("$title{$item} not in use for [_1]",$lonhost).'</li>';
12758:                             }
12759:                         }
12760:                     }
12761:                 } elsif ($item eq 'captcha') {
12762:                     if (ref($loginhash{'login'}) eq 'HASH') {
12763:                         my $chgtxt;
12764:                         if ($loginhash{'login'}{$item} eq 'notused') {
12765:                             $chgtxt .= &mt('No CAPTCHA validation in use for helpdesk form.');
12766:                         } else {
12767:                             my %captchas = &captcha_phrases();
12768:                             if ($captchas{$loginhash{'login'}{$item}}) {
12769:                                 $chgtxt .= &mt("Validation for helpdesk form set to $captchas{$loginhash{'login'}{$item}}.");
12770:                             } else {
12771:                                 $chgtxt .= &mt('Validation for helpdesk form set to unknown type.');
12772:                             }
12773:                         }
12774:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12775:                     }
12776:                 } elsif ($item eq 'recaptchakeys') {
12777:                     if (ref($loginhash{'login'}) eq 'HASH') {
12778:                         my ($privkey,$pubkey);
12779:                         if (ref($loginhash{'login'}{$item}) eq 'HASH') {
12780:                             $pubkey = $loginhash{'login'}{$item}{'public'};
12781:                             $privkey = $loginhash{'login'}{$item}{'private'};
12782:                         }
12783:                         my $chgtxt .= &mt('ReCAPTCHA keys changes').'<ul>';
12784:                         if (!$pubkey) {
12785:                             $chgtxt .= '<li>'.&mt('Public key deleted').'</li>';
12786:                         } else {
12787:                             $chgtxt .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
12788:                         }
12789:                         if (!$privkey) {
12790:                             $chgtxt .= '<li>'.&mt('Private key deleted').'</li>';
12791:                         } else {
12792:                             $chgtxt .= '<li>'.&mt('Private key set to [_1]',$privkey).'</li>';
12793:                         }
12794:                         $chgtxt .= '</ul>';
12795:                         $resulttext .= '<li>'.$chgtxt.'</li>';
12796:                     }
12797:                 } elsif ($item eq 'recaptchaversion') {
12798:                     if (ref($loginhash{'login'}) eq 'HASH') {
12799:                         if ($loginhash{'login'}{'captcha'} eq 'recaptcha') {
12800:                             $resulttext .= '<li>'.&mt('ReCAPTCHA for helpdesk form set to version [_1]',$loginhash{'login'}{'recaptchaversion'}).
12801:                                            '</li>';
12802:                         }
12803:                     }
12804:                 } else {
12805:                     $resulttext .= '<li>'.&mt("$title{$item} set to $offon[$env{'form.'.$item}]").'</li>';
12806:                 }
12807:             }
12808:             $resulttext .= $colchgtext.'</ul>';
12809:         } else {
12810:             $resulttext = &mt('No changes made to log-in page settings');
12811:         }
12812:     } else {
12813:         $resulttext = '<span class="LC_error">'.
12814: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
12815:     }
12816:     if ($errors) {
12817:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
12818:                        $errors.'</ul>';
12819:     }
12820:     return $resulttext;
12821: }
12822: 
12823: sub check_exempt_addresses {
12824:     my ($iplist) = @_;
12825:     $iplist =~ s/^\s+//;
12826:     $iplist =~ s/\s+$//;
12827:     my @poss_ips = split(/\s*[,:]\s*/,$iplist);
12828:     my (@okips,$new);
12829:     foreach my $ip (@poss_ips) {
12830:         if ($ip =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/) {
12831:             if (($1 <= 255) && ($2 <= 255) && ($3 <= 255) && ($4 <= 255)) {
12832:                 push(@okips,$ip);
12833:             }
12834:         }
12835:     }
12836:     if (@okips > 0) {
12837:         $new = join(',',@okips);
12838:     } else {
12839:         $new = '';
12840:     }
12841:     return $new;
12842: }
12843: 
12844: sub color_font_choices {
12845:     my %choices =
12846:         &Apache::lonlocal::texthash (
12847:             img => "Header",
12848:             bgs => "Background colors",
12849:             links => "Link colors",
12850:             images => "Images",
12851:             font => "Font color",
12852:             fontmenu => "Font menu",
12853:             pgbg => "Page",
12854:             tabbg => "Header",
12855:             sidebg => "Border",
12856:             link => "Link",
12857:             alink => "Active link",
12858:             vlink => "Visited link",
12859:         );
12860:     return %choices;
12861: }
12862: 
12863: sub modify_ipaccess {
12864:     my ($dom,$lastactref,%domconfig) = @_;
12865:     my (@allpos,%changes,%confhash,$errors,$resulttext);
12866:     my (@items,%deletions,%itemids,@warnings);
12867:     my ($typeorder,$types) = &commblocktype_text();
12868:     if ($env{'form.ipaccess_add'}) {
12869:         my $name = $env{'form.ipaccess_name_add'};
12870:         my ($newid,$error) = &get_ipaccess_id($dom,$name);
12871:         if ($newid) {
12872:             $itemids{'add'} = $newid;
12873:             push(@items,'add');
12874:             $changes{$newid} = 1;
12875:         } else {
12876:             $error = &mt('Failed to acquire unique ID for new IP access control item');
12877:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
12878:         }
12879:     }
12880:     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
12881:         my @todelete = &Apache::loncommon::get_env_multiple('form.ipaccess_del');
12882:         if (@todelete) {
12883:             map { $deletions{$_} = 1; } @todelete;
12884:         }
12885:         my $maxnum = $env{'form.ipaccess_maxnum'};
12886:         for (my $i=0; $i<$maxnum; $i++) {
12887:             my $itemid = $env{'form.ipaccess_id_'.$i};
12888:             $itemid =~ s/\D+//g;
12889:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12890:                 if ($deletions{$itemid}) {
12891:                     $changes{$itemid} = $domconfig{'ipaccess'}{$itemid}{'name'};
12892:                 } else {
12893:                     push(@items,$i);
12894:                     $itemids{$i} = $itemid;
12895:                 }
12896:             }
12897:         }
12898:     }
12899:     foreach my $idx (@items) {
12900:         my $itemid = $itemids{$idx};
12901:         next unless ($itemid);
12902:         my %current;
12903:         unless ($idx eq 'add') {
12904:             if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
12905:                 %current = %{$domconfig{'ipaccess'}{$itemid}};
12906:             }
12907:         }
12908:         my $position = $env{'form.ipaccess_pos_'.$itemid};
12909:         $position =~ s/\D+//g;
12910:         if ($position ne '') {
12911:             $allpos[$position] = $itemid;
12912:         }
12913:         my $name = $env{'form.ipaccess_name_'.$idx};
12914:         $name =~ s/^\s+|\s+$//g;
12915:         $confhash{$itemid}{'name'} = $name;
12916:         my $possrange = $env{'form.ipaccess_range_'.$idx};
12917:         $possrange =~ s/^\s+|\s+$//g;
12918:         unless ($possrange eq '') {
12919:             $possrange =~ s/[\r\n]+/\s/g;
12920:             $possrange =~ s/\s*-\s*/-/g;
12921:             $possrange =~ s/\s+/,/g;
12922:             $possrange =~ s/,+/,/g;
12923:             if ($possrange ne '') {
12924:                 my (@ok,$count);
12925:                 $count = 0; 
12926:                 foreach my $poss (split(/\,/,$possrange)) {
12927:                     $count ++;
12928:                     $poss = &validate_ip_pattern($poss);
12929:                     if ($poss ne '') {
12930:                         push(@ok,$poss);
12931:                     }
12932:                 }
12933:                 my $diff = $count - scalar(@ok);
12934:                 if ($diff) {
12935:                     $errors .= '<li><span class="LC_error">'.
12936:                                &mt('[quant,_1,IP] invalid and excluded from saved value for IP range(s) for [_2]',
12937:                                    $diff,$name).
12938:                                '</span></li>';
12939:                 }
12940:                 if (@ok) {
12941:                     my @cidr_list;
12942:                     foreach my $item (@ok) {
12943:                         @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
12944:                     }
12945:                     $confhash{$itemid}{'ip'} = join(',',@cidr_list);
12946:                 }
12947:             }
12948:         }
12949:         foreach my $field ('name','ip') {
12950:             unless (($idx eq 'add') || ($changes{$itemid})) {
12951:                 if ($current{$field} ne $confhash{$itemid}{$field}) {
12952:                     $changes{$itemid} = 1;
12953:                     last;
12954:                 }
12955:             }
12956:         }
12957:         $confhash{$itemid}{'commblocks'} = {};
12958:          
12959:         my %commblocks;
12960:         map { $commblocks{$_} = 1; } &Apache::loncommon::get_env_multiple('form.ipaccess_block_'.$idx);  
12961:         foreach my $type (@{$typeorder}) {
12962:             if ($commblocks{$type}) {
12963:                 $confhash{$itemid}{'commblocks'}{$type} = 'on';
12964:             }
12965:             unless (($idx eq 'add') || ($changes{$itemid})) {
12966:                 if (ref($current{'commblocks'}) eq 'HASH') {
12967:                     if ($confhash{$itemid}{'commblocks'}{$type} ne $current{'commblocks'}{$type}) {
12968:                         $changes{$itemid} = 1;
12969:                     }
12970:                 } elsif ($confhash{$itemid}{'commblocks'}{$type}) {
12971:                     $changes{$itemid} = 1;
12972:                 }
12973:             }
12974:         }
12975:         $confhash{$itemid}{'courses'} = {};
12976:         my %crsdeletions;
12977:         my @delcrs = &Apache::loncommon::get_env_multiple('form.ipaccess_course_delete_'.$idx);
12978:         if (@delcrs) {
12979:             map { $crsdeletions{$_} = 1; } @delcrs;
12980:         }
12981:         if (ref($current{'courses'}) eq 'HASH') {
12982:             foreach my $cid (sort(keys(%{$current{'courses'}}))) {
12983:                 if ($crsdeletions{$cid}) {
12984:                     $changes{$itemid} = 1;
12985:                 } else {
12986:                     $confhash{$itemid}{'courses'}{$cid} = 1;
12987:                 }
12988:             }
12989:         }
12990:         $env{'form.ipaccess_cnum_'.$idx} =~ s/^\s+|\s+$//g;
12991:         $env{'form.ipaccess_cdom_'.$idx} =~ s/^\s+|\s+$//g;
12992:         if (($env{'form.ipaccess_cnum_'.$idx} =~ /^$match_courseid$/) && 
12993:             ($env{'form.ipaccess_cdom_'.$idx} =~ /^$match_domain$/)) {
12994:             if (&Apache::lonnet::homeserver($env{'form.ipaccess_cnum_'.$idx},
12995:                                             $env{'form.ipaccess_cdom_'.$idx}) eq 'no_host') {
12996:                 $errors .= '<li><span class="LC_error">'.
12997:                            &mt('Invalid courseID [_1] omitted from list of allowed courses',
12998:                                $env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}).
12999:                            '</span></li>';
13000:             } else {
13001:                 $confhash{$itemid}{'courses'}{$env{'form.ipaccess_cdom_'.$idx}.'_'.$env{'form.ipaccess_cnum_'.$idx}} = 1;
13002:                 $changes{$itemid} = 1;
13003:             }
13004:         }
13005:     }
13006:     if (@allpos > 0) {
13007:         my $idx = 0;
13008:         foreach my $itemid (@allpos) {
13009:             if ($itemid ne '') {
13010:                 $confhash{$itemid}{'order'} = $idx;
13011:                 unless ($changes{$itemid}) {
13012:                     if (ref($domconfig{'ipaccess'}) eq 'HASH') {
13013:                         if (ref($domconfig{'ipaccess'}{$itemid}) eq 'HASH') {
13014:                             if ($domconfig{'ipaccess'}{$itemid}{'order'} ne $idx) {
13015:                                 $changes{$itemid} = 1;
13016:                             }
13017:                         }
13018:                     }
13019:                 }
13020:                 $idx ++;
13021:             }
13022:         }
13023:     }
13024:     if (keys(%changes)) {
13025:         my %defaultshash = (
13026:                               ipaccess => \%confhash,
13027:                            );
13028:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
13029:                                                  $dom);
13030:         if ($putresult eq 'ok') {
13031:             my $cachetime = 1800;
13032:             &Apache::lonnet::do_cache_new('ipaccess',$dom,\%confhash,$cachetime);
13033:             if (ref($lastactref) eq 'HASH') {
13034:                 $lastactref->{'ipaccess'} = 1;
13035:             }
13036:             $resulttext = &mt('Changes made:').'<ul>';
13037:             my %bynum;
13038:             foreach my $itemid (sort(keys(%changes))) {
13039:                 if (ref($confhash{$itemid}) eq 'HASH') {
13040:                     my $position = $confhash{$itemid}{'order'};
13041:                     if ($position =~ /^\d+$/) {
13042:                         $bynum{$position} = $itemid;
13043:                     }
13044:                 }
13045:             }
13046:             if (keys(%deletions)) {
13047:                 foreach my $itemid (sort { $a <=> $b } keys(%deletions)) {
13048:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
13049:                 }
13050:             }
13051:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
13052:                 my $itemid = $bynum{$pos};
13053:                 if (ref($confhash{$itemid}) eq 'HASH') {
13054:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'name'}.'</b><ul>';
13055:                     my $position = $pos + 1;
13056:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
13057:                     if ($confhash{$itemid}{'ip'} eq '') {
13058:                         $resulttext .= '<li>'.&mt('No IP Range(s) set').'</li>';
13059:                     } else {
13060:                         $resulttext .= '<li>'.&mt('IP Range(s): [_1]',$confhash{$itemid}{'ip'}).'</li>';
13061:                     }
13062:                     if (keys(%{$confhash{$itemid}{'commblocks'}})) {
13063:                         $resulttext .= '<li>'.&mt('Functionality Blocked: [_1]',
13064:                                                   join(', ', map { $types->{$_}; } sort(keys(%{$confhash{$itemid}{'commblocks'}})))).
13065:                                        '</li>';
13066:                     } else {
13067:                         $resulttext .= '<li>'.&mt('No functionality blocked').'</li>';
13068:                     }
13069:                     if (keys(%{$confhash{$itemid}{'courses'}})) {
13070:                         my @courses;
13071:                         foreach my $cid (sort(keys(%{$confhash{$itemid}{'courses'}}))) {
13072:                             my %courseinfo = &Apache::lonnet::coursedescription($cid,{'one_time' => 1}); 
13073:                             push(@courses,$courseinfo{'description'}.' ('.$cid.')');
13074:                         }
13075:                         $resulttext .= '<li>'.&mt('Courses/Communities allowed').':<ul><li>'.
13076:                                              join('</li><li>',@courses).'</li></ul>';
13077:                     } else {
13078:                         $resulttext .= '<li>'.&mt('No courses allowed').'</li>';
13079:                     }
13080:                     $resulttext .= '</ul></li>';
13081:                 }
13082:             }
13083:             $resulttext .= '</ul>';
13084:         } else {
13085:             $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
13086:         }
13087:     } else {
13088:         $resulttext = &mt('No changes made');
13089:     }
13090:     if ($errors) {
13091:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
13092:                        $errors.'</ul></p>';
13093:     }
13094:     return $resulttext;
13095: }
13096: 
13097: sub get_ipaccess_id {
13098:     my ($domain,$location) = @_;
13099:     # get lock on ipaccess db
13100:     my $lockhash = {
13101:                       lock => $env{'user.name'}.
13102:                               ':'.$env{'user.domain'},
13103:                    };
13104:     my $tries = 0;
13105:     my $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13106:     my ($id,$error);
13107: 
13108:     while (($gotlock ne 'ok') && ($tries<10)) {
13109:         $tries ++;
13110:         sleep (0.1);
13111:         $gotlock = &Apache::lonnet::newput_dom('ipaccess',$lockhash,$domain);
13112:     }
13113:     if ($gotlock eq 'ok') {
13114:         my %currids = &Apache::lonnet::dump_dom('ipaccess',$domain);
13115:         if ($currids{'lock'}) {
13116:             delete($currids{'lock'});
13117:             if (keys(%currids)) {
13118:                 my @curr = sort { $a <=> $b } keys(%currids);
13119:                 if ($curr[-1] =~ /^\d+$/) {
13120:                     $id = 1 + $curr[-1];
13121:                 }
13122:             } else {
13123:                 $id = 1;
13124:             }
13125:             if ($id) {
13126:                 unless (&Apache::lonnet::newput_dom('ipaccess',{ $id => $location },$domain) eq 'ok') {
13127:                     $error = 'nostore';
13128:                 }
13129:             } else {
13130:                 $error = 'nonumber';
13131:             }
13132:         }
13133:         my $dellockoutcome = &Apache::lonnet::del_dom('ipaccess',['lock'],$domain);
13134:     } else {
13135:         $error = 'nolock';
13136:     }
13137:     return ($id,$error);
13138: }
13139: 
13140: sub modify_rolecolors {
13141:     my ($r,$dom,$confname,$roles,$lastactref,%domconfig) = @_;
13142:     my ($resulttext,%rolehash);
13143:     $rolehash{'rolecolors'} = {};
13144:     if (ref($domconfig{'rolecolors'}) ne 'HASH') {
13145:         if ($domconfig{'rolecolors'} eq '') {
13146:             $domconfig{'rolecolors'} = {};
13147:         }
13148:     }
13149:     my ($errors,%changes) = &modify_colors($r,$dom,$confname,$roles,
13150:                          $domconfig{'rolecolors'},$rolehash{'rolecolors'});
13151:     my $putresult = &Apache::lonnet::put_dom('configuration',\%rolehash,
13152:                                              $dom);
13153:     if ($putresult eq 'ok') {
13154:         if (keys(%changes) > 0) {
13155:             &Apache::loncommon::devalidate_domconfig_cache($dom);
13156:             if (ref($lastactref) eq 'HASH') {
13157:                 $lastactref->{'domainconfig'} = 1;
13158:             }
13159:             $resulttext = &display_colorchgs($dom,\%changes,$roles,
13160:                                              $rolehash{'rolecolors'});
13161:         } else {
13162:             $resulttext = &mt('No changes made to default color schemes');
13163:         }
13164:     } else {
13165:         $resulttext = '<span class="LC_error">'.
13166: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
13167:     }
13168:     if ($errors) {
13169:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
13170:                        $errors.'</ul>';
13171:     }
13172:     return $resulttext;
13173: }
13174: 
13175: sub modify_colors {
13176:     my ($r,$dom,$confname,$roles,$domconfig,$confhash) = @_;
13177:     my (%changes,%choices);
13178:     my @bgs;
13179:     my @links = ('link','alink','vlink');
13180:     my @logintext;
13181:     my @images;
13182:     my $servadm = $r->dir_config('lonAdmEMail');
13183:     my $errors;
13184:     my %defaults;
13185:     foreach my $role (@{$roles}) {
13186:         if ($role eq 'login') {
13187:             %choices = &login_choices();
13188:             @logintext = ('textcol','bgcol');
13189:         } else {
13190:             %choices = &color_font_choices();
13191:         }
13192:         if ($role eq 'login') {
13193:             @images = ('img','logo','domlogo','login');
13194:             @bgs = ('pgbg','mainbg','sidebg');
13195:         } else {
13196:             @images = ('img');
13197:             @bgs = ('pgbg','tabbg','sidebg');
13198:         }
13199:         my %defaults = &role_defaults($role,\@bgs,\@links,\@images,\@logintext);
13200:         unless ($env{'form.'.$role.'_font'} eq $defaults{'font'}) {
13201:             $confhash->{$role}{'font'} = $env{'form.'.$role.'_font'};
13202:         }
13203:         if ($role eq 'login') {
13204:             foreach my $item (@logintext) {
13205:                 $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13206:                 if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13207:                     $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13208:                 }
13209:                 unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'logintext'}{$item})) {
13210:                     $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13211:                 }
13212:             }
13213:         } else {
13214:             $env{'form.'.$role.'_fontmenu'} = lc($env{'form.'.$role.'_fontmenu'});
13215:             if ($env{'form.'.$role.'_fontmenu'} =~ /^\w+/) {
13216:                 $env{'form.'.$role.'_fontmenu'} = '#'.$env{'form.'.$role.'_fontmenu'};
13217:             }
13218:             unless($env{'form.'.$role.'_fontmenu'} eq lc($defaults{'fontmenu'})) {
13219:                 $confhash->{$role}{'fontmenu'} = $env{'form.'.$role.'_fontmenu'};
13220:             }
13221:         }
13222:         foreach my $item (@bgs) {
13223:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13224:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13225:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13226:             }
13227:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'bgs'}{$item})) {
13228:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13229:             }
13230:         }
13231:         foreach my $item (@links) {
13232:             $env{'form.'.$role.'_'.$item} = lc($env{'form.'.$role.'_'.$item});
13233:             if ($env{'form.'.$role.'_'.$item} =~ /^\w+/) {
13234:                 $env{'form.'.$role.'_'.$item} = '#'.$env{'form.'.$role.'_'.$item};
13235:             }
13236:             unless ($env{'form.'.$role.'_'.$item} eq lc($defaults{'links'}{$item})) {
13237:                 $confhash->{$role}{$item} = $env{'form.'.$role.'_'.$item};
13238:             }
13239:         }
13240:         my ($configuserok,$author_ok,$switchserver) = 
13241:             &config_check($dom,$confname,$servadm);
13242:         my ($width,$height) = &thumb_dimensions();
13243:         if (ref($domconfig->{$role}) ne 'HASH') {
13244:             $domconfig->{$role} = {};
13245:         }
13246:         foreach my $img (@images) {
13247:             if ($role eq 'login') {
13248:                 if (($img eq 'img') || ($img eq 'logo')) {  
13249:                     if (defined($env{'form.login_showlogo_'.$img})) {
13250:                         $confhash->{$role}{'showlogo'}{$img} = 1;
13251:                     } else { 
13252:                         $confhash->{$role}{'showlogo'}{$img} = 0;
13253:                     }
13254:                 }
13255:                 if ($env{'form.login_alt_'.$img} ne '') {
13256:                     $confhash->{$role}{'alttext'}{$img} = $env{'form.login_alt_'.$img};
13257:                 }
13258:             }
13259: 	    if ( ! $env{'form.'.$role.'_'.$img.'.filename'} 
13260: 		 && !defined($domconfig->{$role}{$img})
13261: 		 && !$env{'form.'.$role.'_del_'.$img}
13262: 		 && $env{'form.'.$role.'_import_'.$img}) {
13263: 		# import the old configured image from the .tab setting
13264: 		# if they haven't provided a new one 
13265: 		$domconfig->{$role}{$img} = 
13266: 		    $env{'form.'.$role.'_import_'.$img};
13267: 	    }
13268:             if ($env{'form.'.$role.'_'.$img.'.filename'} ne '') {
13269:                 my $error;
13270:                 if ($configuserok eq 'ok') {
13271:                     if ($switchserver) {
13272:                         $error = &mt("Upload of [_1] image for $role page(s) is not permitted to this server: [_2]",$choices{$img},$switchserver);
13273:                     } else {
13274:                         if ($author_ok eq 'ok') {
13275:                             my ($result,$logourl) = 
13276:                                 &publishlogo($r,'upload',$role.'_'.$img,
13277:                                            $dom,$confname,$img,$width,$height);
13278:                             if ($result eq 'ok') {
13279:                                 $confhash->{$role}{$img} = $logourl;
13280:                                 $changes{$role}{'images'}{$img} = 1;
13281:                             } else {
13282:                                 $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);
13283:                             }
13284:                         } else {
13285:                             $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);
13286:                         }
13287:                     }
13288:                 } else {
13289:                     $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);
13290:                 }
13291:                 if ($error) {
13292:                     &Apache::lonnet::logthis($error);
13293:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
13294:                 }
13295:             } elsif ($domconfig->{$role}{$img} ne '') {
13296:                 if ($domconfig->{$role}{$img} !~ m-^(/res/\Q$dom\E/\Q$confname\E/\Q$img\E)/([^/]+)$-) {
13297:                     my $error;
13298:                     if ($configuserok eq 'ok') {
13299: # is confname an author?
13300:                         if ($switchserver eq '') {
13301:                             if ($author_ok eq 'ok') {
13302:                                 my ($result,$logourl) = 
13303:                                &publishlogo($r,'copy',$domconfig->{$role}{$img},
13304:                                             $dom,$confname,$img,$width,$height);
13305:                                 if ($result eq 'ok') {
13306:                                     $confhash->{$role}{$img} = $logourl;
13307: 				    $changes{$role}{'images'}{$img} = 1;
13308:                                 }
13309:                             }
13310:                         }
13311:                     }
13312:                 }
13313:             }
13314:         }
13315:         if (ref($domconfig) eq 'HASH') {
13316:             if (ref($domconfig->{$role}) eq 'HASH') {
13317:                 foreach my $img (@images) {
13318:                     if ($domconfig->{$role}{$img} ne '') {
13319:                         if ($env{'form.'.$role.'_del_'.$img}) {
13320:                             $confhash->{$role}{$img} = '';
13321:                             $changes{$role}{'images'}{$img} = 1;
13322:                         } else {
13323:                             if ($confhash->{$role}{$img} eq '') {
13324:                                 $confhash->{$role}{$img} = $domconfig->{$role}{$img};
13325:                             }
13326:                         }
13327:                     } else {
13328:                         if ($env{'form.'.$role.'_del_'.$img}) {
13329:                             $confhash->{$role}{$img} = '';
13330:                             $changes{$role}{'images'}{$img} = 1;
13331:                         } 
13332:                     }
13333:                     if ($role eq 'login') {
13334:                         if (($img eq 'logo') || ($img eq 'img')) {
13335:                             if (ref($domconfig->{'login'}{'showlogo'}) eq 'HASH') {
13336:                                 if ($confhash->{$role}{'showlogo'}{$img} ne 
13337:                                     $domconfig->{$role}{'showlogo'}{$img}) {
13338:                                     $changes{$role}{'showlogo'}{$img} = 1; 
13339:                                 }
13340:                             } else {
13341:                                 if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13342:                                     $changes{$role}{'showlogo'}{$img} = 1;
13343:                                 }
13344:                             }
13345:                         }
13346:                         if ($img ne 'login') {
13347:                             if (ref($domconfig->{$role}{'alttext'}) eq 'HASH') {
13348:                                 if ($confhash->{$role}{'alttext'}{$img} ne
13349:                                     $domconfig->{$role}{'alttext'}{$img}) {
13350:                                     $changes{$role}{'alttext'}{$img} = 1;
13351:                                 }
13352:                             } else {
13353:                                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13354:                                     $changes{$role}{'alttext'}{$img} = 1;
13355:                                 }
13356:                             }
13357:                         }
13358:                     }
13359:                 }
13360:                 if ($domconfig->{$role}{'font'} ne '') {
13361:                     if ($confhash->{$role}{'font'} ne $domconfig->{$role}{'font'}) {
13362:                         $changes{$role}{'font'} = 1;
13363:                     }
13364:                 } else {
13365:                     if ($confhash->{$role}{'font'}) {
13366:                         $changes{$role}{'font'} = 1;
13367:                     }
13368:                 }
13369:                 if ($role ne 'login') {
13370:                     if ($domconfig->{$role}{'fontmenu'} ne '') {
13371:                         if ($confhash->{$role}{'fontmenu'} ne $domconfig->{$role}{'fontmenu'}) {
13372:                             $changes{$role}{'fontmenu'} = 1;
13373:                         }
13374:                     } else {
13375:                         if ($confhash->{$role}{'fontmenu'}) {
13376:                             $changes{$role}{'fontmenu'} = 1;
13377:                         }
13378:                     }
13379:                 }
13380:                 foreach my $item (@bgs) {
13381:                     if ($domconfig->{$role}{$item} ne '') {
13382:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13383:                             $changes{$role}{'bgs'}{$item} = 1;
13384:                         } 
13385:                     } else {
13386:                         if ($confhash->{$role}{$item}) {
13387:                             $changes{$role}{'bgs'}{$item} = 1;
13388:                         }
13389:                     }
13390:                 }
13391:                 foreach my $item (@links) {
13392:                     if ($domconfig->{$role}{$item} ne '') {
13393:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13394:                             $changes{$role}{'links'}{$item} = 1;
13395:                         }
13396:                     } else {
13397:                         if ($confhash->{$role}{$item}) {
13398:                             $changes{$role}{'links'}{$item} = 1;
13399:                         }
13400:                     }
13401:                 }
13402:                 foreach my $item (@logintext) {
13403:                     if ($domconfig->{$role}{$item} ne '') {
13404:                         if ($confhash->{$role}{$item} ne $domconfig->{$role}{$item}) {
13405:                             $changes{$role}{'logintext'}{$item} = 1;
13406:                         }
13407:                     } else {
13408:                         if ($confhash->{$role}{$item}) {
13409:                             $changes{$role}{'logintext'}{$item} = 1;
13410:                         }
13411:                     }
13412:                 }
13413:             } else {
13414:                 &default_change_checker($role,\@images,\@links,\@bgs,
13415:                                         \@logintext,$confhash,\%changes); 
13416:             }
13417:         } else {
13418:             &default_change_checker($role,\@images,\@links,\@bgs,
13419:                                     \@logintext,$confhash,\%changes); 
13420:         }
13421:     }
13422:     return ($errors,%changes);
13423: }
13424: 
13425: sub config_check {
13426:     my ($dom,$confname,$servadm) = @_;
13427:     my ($configuserok,$author_ok,$switchserver,%currroles);
13428:     my $uhome = &Apache::lonnet::homeserver($confname,$dom,1);
13429:     ($configuserok,%currroles) = &check_configuser($uhome,$dom,
13430:                                                    $confname,$servadm);
13431:     if ($configuserok eq 'ok') {
13432:         $switchserver = &check_switchserver($dom,$confname);
13433:         if ($switchserver eq '') {
13434:             $author_ok = &check_authorstatus($dom,$confname,%currroles);
13435:         }
13436:     }
13437:     return ($configuserok,$author_ok,$switchserver);
13438: }
13439: 
13440: sub default_change_checker {
13441:     my ($role,$images,$links,$bgs,$logintext,$confhash,$changes) = @_;
13442:     foreach my $item (@{$links}) {
13443:         if ($confhash->{$role}{$item}) {
13444:             $changes->{$role}{'links'}{$item} = 1;
13445:         }
13446:     }
13447:     foreach my $item (@{$bgs}) {
13448:         if ($confhash->{$role}{$item}) {
13449:             $changes->{$role}{'bgs'}{$item} = 1;
13450:         }
13451:     }
13452:     foreach my $item (@{$logintext}) {
13453:         if ($confhash->{$role}{$item}) {
13454:             $changes->{$role}{'logintext'}{$item} = 1;
13455:         }
13456:     }
13457:     foreach my $img (@{$images}) {
13458:         if ($env{'form.'.$role.'_del_'.$img}) {
13459:             $confhash->{$role}{$img} = '';
13460:             $changes->{$role}{'images'}{$img} = 1;
13461:         }
13462:         if ($role eq 'login') {
13463:             if ($confhash->{$role}{'showlogo'}{$img} == 0) {
13464:                 $changes->{$role}{'showlogo'}{$img} = 1;
13465:             }
13466:             if (ref($confhash->{$role}{'alttext'}) eq 'HASH') {
13467:                 if ($confhash->{$role}{'alttext'}{$img} ne '') {
13468:                     $changes->{$role}{'alttext'}{$img} = 1;
13469:                 }
13470:             }
13471:         }
13472:     }
13473:     if ($confhash->{$role}{'font'}) {
13474:         $changes->{$role}{'font'} = 1;
13475:     }
13476: }
13477: 
13478: sub display_colorchgs {
13479:     my ($dom,$changes,$roles,$confhash) = @_;
13480:     my (%choices,$resulttext);
13481:     if (!grep(/^login$/,@{$roles})) {
13482:         $resulttext = &mt('Changes made:').'<br />';
13483:     }
13484:     foreach my $role (@{$roles}) {
13485:         if ($role eq 'login') {
13486:             %choices = &login_choices();
13487:         } else {
13488:             %choices = &color_font_choices();
13489:         }
13490:         if (ref($changes->{$role}) eq 'HASH') {
13491:             if ($role ne 'login') {
13492:                 $resulttext .= '<h4>'.&mt($role).'</h4>';
13493:             }
13494:             foreach my $key (sort(keys(%{$changes->{$role}}))) {
13495:                 if ($role ne 'login') {
13496:                     $resulttext .= '<ul>';
13497:                 }
13498:                 if (ref($changes->{$role}{$key}) eq 'HASH') {
13499:                     if ($role ne 'login') {
13500:                         $resulttext .= '<li>'.&mt($choices{$key}).':<ul>';
13501:                     }
13502:                     foreach my $item (sort(keys(%{$changes->{$role}{$key}}))) {
13503:                         if (($role eq 'login') && ($key eq 'showlogo')) {
13504:                             if ($confhash->{$role}{$key}{$item}) {
13505:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to be displayed").'</li>';
13506:                             } else {
13507:                                 $resulttext .= '<li>'.&mt("$choices{$item} set to not be displayed").'</li>';
13508:                             }
13509:                         } elsif (($role eq 'login') && ($key eq 'alttext')) {
13510:                             if ($confhash->{$role}{$key}{$item} ne '') {
13511:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} set to [_1].",
13512:                                                $confhash->{$role}{$key}{$item}).'</li>';
13513:                             } else {
13514:                                 $resulttext .= '<li>'.&mt("$choices{$key} for $choices{$item} deleted.").'</li>';
13515:                             }
13516:                         } elsif ($confhash->{$role}{$item} eq '') {
13517:                             $resulttext .= '<li>'.&mt("$choices{$item} set to default").'</li>';
13518:                         } else {
13519:                             my $newitem = $confhash->{$role}{$item};
13520:                             if ($key eq 'images') {
13521:                                 $newitem = '<img src="'.$confhash->{$role}{$item}.'" alt="'.$choices{$item}.'" style="vertical-align: bottom" />';
13522:                             }
13523:                             $resulttext .= '<li>'.&mt("$choices{$item} set to [_1]",$newitem).'</li>';
13524:                         }
13525:                     }
13526:                     if ($role ne 'login') {
13527:                         $resulttext .= '</ul></li>';
13528:                     }
13529:                 } else {
13530:                     if ($confhash->{$role}{$key} eq '') {
13531:                         $resulttext .= '<li>'.&mt("$choices{$key} set to default").'</li>';
13532:                     } else {
13533:                         $resulttext .= '<li>'.&mt("$choices{$key} set to [_1]",$confhash->{$role}{$key}).'</li>';
13534:                     }
13535:                 }
13536:                 if ($role ne 'login') {
13537:                     $resulttext .= '</ul>';
13538:                 }
13539:             }
13540:         }
13541:     }
13542:     return $resulttext;
13543: }
13544: 
13545: sub thumb_dimensions {
13546:     return ('200','50');
13547: }
13548: 
13549: sub check_dimensions {
13550:     my ($inputfile) = @_;
13551:     my ($fullwidth,$fullheight);
13552:     if ($inputfile =~ m|^[/\w.\-]+$|) {
13553:         if (open(PIPE,"identify $inputfile 2>&1 |")) {
13554:             my $imageinfo = <PIPE>;
13555:             if (!close(PIPE)) {
13556:                 &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
13557:             }
13558:             chomp($imageinfo);
13559:             my ($fullsize) = 
13560:                 ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
13561:             if ($fullsize) {
13562:                 ($fullwidth,$fullheight) = split(/x/,$fullsize);
13563:             }
13564:         }
13565:     }
13566:     return ($fullwidth,$fullheight);
13567: }
13568: 
13569: sub check_configuser {
13570:     my ($uhome,$dom,$confname,$servadm) = @_;
13571:     my ($configuserok,%currroles);
13572:     if ($uhome eq 'no_host') {
13573:         srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand.
13574:         my $configpass = &LONCAPA::Enrollment::create_password($dom);
13575:         $configuserok = 
13576:             &Apache::lonnet::modifyuser($dom,$confname,'','internal',
13577:                              $configpass,'','','','','',undef,$servadm);
13578:     } else {
13579:         $configuserok = 'ok';
13580:         %currroles = 
13581:             &Apache::lonnet::get_my_roles($confname,$dom,'userroles');
13582:     }
13583:     return ($configuserok,%currroles);
13584: }
13585: 
13586: sub check_authorstatus {
13587:     my ($dom,$confname,%currroles) = @_;
13588:     my $author_ok;
13589:     if (!$currroles{':'.$dom.':au'}) {
13590:         my $start = time;
13591:         my $end = 0;
13592:         $author_ok = 
13593:             &Apache::lonnet::assignrole($dom,$confname,'/'.$dom.'/',
13594:                                         'au',$end,$start,'','','domconfig');
13595:     } else {
13596:         $author_ok = 'ok';
13597:     }
13598:     return $author_ok;
13599: }
13600: 
13601: sub publishlogo {
13602:     my ($r,$action,$formname,$dom,$confname,$subdir,$thumbwidth,$thumbheight,$savefileas) = @_;
13603:     my ($output,$fname,$logourl,$madethumb);
13604:     if ($action eq 'upload') {
13605:         $fname=$env{'form.'.$formname.'.filename'};
13606:         chop($env{'form.'.$formname});
13607:     } else {
13608:         ($fname) = ($formname =~ /([^\/]+)$/);
13609:     }
13610:     if ($savefileas ne '') {
13611:         $fname = $savefileas;
13612:     }
13613:     $fname=&Apache::lonnet::clean_filename($fname);
13614: # See if there is anything left
13615:     unless ($fname) { return ('error: no uploaded file'); }
13616:     $fname="$subdir/$fname";
13617:     my $docroot=$r->dir_config('lonDocRoot');
13618:     my $filepath="$docroot/priv";
13619:     my $relpath = "$dom/$confname";
13620:     my ($fnamepath,$file,$fetchthumb);
13621:     $file=$fname;
13622:     if ($fname=~m|/|) {
13623:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
13624:     }
13625:     my @parts=split(/\//,"$filepath/$relpath/$fnamepath");
13626:     my $count;
13627:     for ($count=5;$count<=$#parts;$count++) {
13628:         $filepath.="/$parts[$count]";
13629:         if ((-e $filepath)!=1) {
13630:             mkdir($filepath,02770);
13631:         }
13632:     }
13633:     # Check for bad extension and disallow upload
13634:     if ($file=~/\.(\w+)$/ &&
13635:         (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
13636:         $output = 
13637:             &mt('Invalid file extension ([_1]) - reserved for internal use.',$1); 
13638:     } elsif ($file=~/\.(\w+)$/ &&
13639:         !defined(&Apache::loncommon::fileembstyle($1))) {
13640:         $output = &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1);
13641:     } elsif ($file=~/\.(\d+)\.(\w+)$/) {
13642:         $output = &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2);
13643:     } elsif (-d "$filepath/$file") {
13644:         $output = &mt('Filename is a directory name - rename the file and re-upload');
13645:     } else {
13646:         my $source = $filepath.'/'.$file;
13647:         my $logfile;
13648:         if (!open($logfile,">>",$source.'.log')) {
13649:             return (&mt('No write permission to Authoring Space'));
13650:         }
13651:         print $logfile
13652: "\n================= Publish ".localtime()." ================\n".
13653: $env{'user.name'}.':'.$env{'user.domain'}."\n";
13654: # Save the file
13655:         if (!open(FH,">",$source)) {
13656:             &Apache::lonnet::logthis('Failed to create '.$source);
13657:             return (&mt('Failed to create file'));
13658:         }
13659:         if ($action eq 'upload') {
13660:             if (!print FH ($env{'form.'.$formname})) {
13661:                 &Apache::lonnet::logthis('Failed to write to '.$source);
13662:                 return (&mt('Failed to write file'));
13663:             }
13664:         } else {
13665:             my $original = &Apache::lonnet::filelocation('',$formname);
13666:             if(!copy($original,$source)) {
13667:                 &Apache::lonnet::logthis('Failed to copy '.$original.' to '.$source);
13668:                 return (&mt('Failed to write file'));
13669:             }
13670:         }
13671:         close(FH);
13672:         chmod(0660, $source); # Permissions to rw-rw---.
13673: 
13674:         my $targetdir=$docroot.'/res/'.$dom.'/'.$confname .'/'.$fnamepath;
13675:         my $copyfile=$targetdir.'/'.$file;
13676: 
13677:         my @parts=split(/\//,$targetdir);
13678:         my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
13679:         for (my $count=5;$count<=$#parts;$count++) {
13680:             $path.="/$parts[$count]";
13681:             if (!-e $path) {
13682:                 print $logfile "\nCreating directory ".$path;
13683:                 mkdir($path,02770);
13684:             }
13685:         }
13686:         my $versionresult;
13687:         if (-e $copyfile) {
13688:             $versionresult = &logo_versioning($targetdir,$file,$logfile);
13689:         } else {
13690:             $versionresult = 'ok';
13691:         }
13692:         if ($versionresult eq 'ok') {
13693:             if (copy($source,$copyfile)) {
13694:                 print $logfile "\nCopied original source to ".$copyfile."\n";
13695:                 $output = 'ok';
13696:                 $logourl = '/res/'.$dom.'/'.$confname.'/'.$fname;
13697:                 push(@{$modified_urls},[$copyfile,$source]);
13698:                 my $metaoutput = 
13699:                     &write_metadata($dom,$confname,$formname,$targetdir,$file,$logfile);
13700:                 unless ($registered_cleanup) {
13701:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13702:                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13703:                     $registered_cleanup=1;
13704:                 }
13705:             } else {
13706:                 print $logfile "\nUnable to write ".$copyfile.':'.$!."\n";
13707:                 $output = &mt('Failed to copy file to RES space').", $!";
13708:             }
13709:             if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
13710:                 my $inputfile = $filepath.'/'.$file;
13711:                 my $outfile = $filepath.'/'.'tn-'.$file;
13712:                 my ($fullwidth,$fullheight) = &check_dimensions($inputfile);
13713:                 if ($fullwidth ne '' && $fullheight ne '') { 
13714:                     if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
13715:                         my $thumbsize = $thumbwidth.'x'.$thumbheight;
13716:                         my @args = ('convert','-sample',$thumbsize,$inputfile,$outfile);
13717:                         system({$args[0]} @args);
13718:                         chmod(0660, $filepath.'/tn-'.$file);
13719:                         if (-e $outfile) {
13720:                             my $copyfile=$targetdir.'/tn-'.$file;
13721:                             if (copy($outfile,$copyfile)) {
13722:                                 print $logfile "\nCopied source to ".$copyfile."\n";
13723:                                 my $thumb_metaoutput = 
13724:                                     &write_metadata($dom,$confname,$formname,
13725:                                                     $targetdir,'tn-'.$file,$logfile);
13726:                                 push(@{$modified_urls},[$copyfile,$outfile]);
13727:                                 unless ($registered_cleanup) {
13728:                                     my $handlers = $r->get_handlers('PerlCleanupHandler');
13729:                                     $r->set_handlers('PerlCleanupHandler' => [\&notifysubscribed,@{$handlers}]);
13730:                                     $registered_cleanup=1;
13731:                                 }
13732:                                 $madethumb = 1;
13733:                             } else {
13734:                                 print $logfile "\nUnable to write ".$copyfile.
13735:                                                ':'.$!."\n";
13736:                             }
13737:                         }
13738:                     }
13739:                 }
13740:             }
13741:         } else {
13742:             $output = $versionresult;
13743:         }
13744:     }
13745:     return ($output,$logourl,$madethumb);
13746: }
13747: 
13748: sub logo_versioning {
13749:     my ($targetdir,$file,$logfile) = @_;
13750:     my $target = $targetdir.'/'.$file;
13751:     my ($maxversion,$fn,$extn,$output);
13752:     $maxversion = 0;
13753:     if ($file =~ /^(.+)\.(\w+)$/) {
13754:         $fn=$1;
13755:         $extn=$2;
13756:     }
13757:     opendir(DIR,$targetdir);
13758:     while (my $filename=readdir(DIR)) {
13759:         if ($filename=~/\Q$fn\E\.(\d+)\.\Q$extn\E$/) {
13760:             $maxversion=($1>$maxversion)?$1:$maxversion;
13761:         }
13762:     }
13763:     $maxversion++;
13764:     print $logfile "\nCreating old version ".$maxversion."\n";
13765:     my $copyfile=$targetdir.'/'.$fn.'.'.$maxversion.'.'.$extn;
13766:     if (copy($target,$copyfile)) {
13767:         print $logfile "Copied old target to ".$copyfile."\n";
13768:         $copyfile=$copyfile.'.meta';
13769:         if (copy($target.'.meta',$copyfile)) {
13770:             print $logfile "Copied old target metadata to ".$copyfile."\n";
13771:             $output = 'ok';
13772:         } else {
13773:             print $logfile "Unable to write metadata ".$copyfile.':'.$!."\n";
13774:             $output = &mt('Failed to copy old meta').", $!, ";
13775:         }
13776:     } else {
13777:         print $logfile "Unable to write ".$copyfile.':'.$!."\n";
13778:         $output = &mt('Failed to copy old target').", $!, ";
13779:     }
13780:     return $output;
13781: }
13782: 
13783: sub write_metadata {
13784:     my ($dom,$confname,$formname,$targetdir,$file,$logfile) = @_;
13785:     my (%metadatafields,%metadatakeys,$output);
13786:     $metadatafields{'title'}=$formname;
13787:     $metadatafields{'creationdate'}=time;
13788:     $metadatafields{'lastrevisiondate'}=time;
13789:     $metadatafields{'copyright'}='public';
13790:     $metadatafields{'modifyinguser'}=$env{'user.name'}.':'.
13791:                                          $env{'user.domain'};
13792:     $metadatafields{'authorspace'}=$confname.':'.$dom;
13793:     $metadatafields{'domain'}=$dom;
13794:     {
13795:         print $logfile "\nWrite metadata file for ".$targetdir.'/'.$file;
13796:         my $mfh;
13797:         if (open($mfh,">",$targetdir.'/'.$file.'.meta')) {
13798:             foreach (sort(keys(%metadatafields))) {
13799:                 unless ($_=~/\./) {
13800:                     my $unikey=$_;
13801:                     $unikey=~/^([A-Za-z]+)/;
13802:                     my $tag=$1;
13803:                     $tag=~tr/A-Z/a-z/;
13804:                     print $mfh "\n\<$tag";
13805:                     foreach (split(/\,/,$metadatakeys{$unikey})) {
13806:                         my $value=$metadatafields{$unikey.'.'.$_};
13807:                         $value=~s/\"/\'\'/g;
13808:                         print $mfh ' '.$_.'="'.$value.'"';
13809:                     }
13810:                     print $mfh '>'.
13811:                         &HTML::Entities::encode($metadatafields{$unikey},'<>&"')
13812:                             .'</'.$tag.'>';
13813:                 }
13814:             }
13815:             $output = 'ok';
13816:             print $logfile "\nWrote metadata";
13817:             close($mfh);
13818:         } else {
13819:             print $logfile "\nFailed to open metadata file";
13820:             $output = &mt('Could not write metadata');
13821:         }
13822:     }
13823:     return $output;
13824: }
13825: 
13826: sub notifysubscribed {
13827:     foreach my $targetsource (@{$modified_urls}){
13828:         next unless (ref($targetsource) eq 'ARRAY');
13829:         my ($target,$source)=@{$targetsource};
13830:         if ($source ne '') {
13831:             if (open(my $logfh,">>",$source.'.log')) {
13832:                 print $logfh "\nCleanup phase: Notifications\n";
13833:                 my @subscribed=&subscribed_hosts($target);
13834:                 foreach my $subhost (@subscribed) {
13835:                     print $logfh "\nNotifying host ".$subhost.':';
13836:                     my $reply=&Apache::lonnet::critical('update:'.$target,$subhost);
13837:                     print $logfh $reply;
13838:                 }
13839:                 my @subscribedmeta=&subscribed_hosts("$target.meta");
13840:                 foreach my $subhost (@subscribedmeta) {
13841:                     print $logfh "\nNotifying host for metadata only ".$subhost.':';
13842:                     my $reply=&Apache::lonnet::critical('update:'.$target.'.meta',
13843:                                                         $subhost);
13844:                     print $logfh $reply;
13845:                 }
13846:                 print $logfh "\n============ Done ============\n";
13847:                 close($logfh);
13848:             }
13849:         }
13850:     }
13851:     return OK;
13852: }
13853: 
13854: sub subscribed_hosts {
13855:     my ($target) = @_;
13856:     my @subscribed;
13857:     if (open(my $fh,"<","$target.subscription")) {
13858:         while (my $subline=<$fh>) {
13859:             if ($subline =~ /^($match_lonid):/) {
13860:                 my $host = $1;
13861:                 if ($host ne $Apache::lonnet::perlvar{'lonHostID'}) {
13862:                     unless (grep(/^\Q$host\E$/,@subscribed)) {
13863:                         push(@subscribed,$host);
13864:                     }
13865:                 }
13866:             }
13867:         }
13868:     }
13869:     return @subscribed;
13870: }
13871: 
13872: sub check_switchserver {
13873:     my ($dom,$confname) = @_;
13874:     my ($allowed,$switchserver);
13875:     my $home = &Apache::lonnet::homeserver($confname,$dom);
13876:     if ($home eq 'no_host') {
13877:         $home = &Apache::lonnet::domain($dom,'primary');
13878:     }
13879:     my @ids=&Apache::lonnet::current_machine_ids();
13880:     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
13881:     if (!$allowed) {
13882: 	$switchserver='<a href="/adm/switchserver?otherserver='.$home.'&amp;role=dc./'.$dom.'/&amp;destinationurl=/adm/domainprefs">'.&mt('Switch Server').'</a>';
13883:     }
13884:     return $switchserver;
13885: }
13886: 
13887: sub modify_quotas {
13888:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
13889:     my ($context,@usertools,@options,%validations,%titles,%confhash,%toolshash,
13890:         %limithash,$toolregexp,%conditions,$resulttext,%changes,$confname,$configuserok,
13891:         $author_ok,$switchserver,$errors,$validationitemsref,$validationnamesref,
13892:         $validationfieldsref);
13893:     if ($action eq 'quotas') {
13894:         $context = 'tools'; 
13895:     } else {
13896:         $context = $action;
13897:     }
13898:     if ($context eq 'requestcourses') {
13899:         @usertools = ('official','unofficial','community','textbook','placement','lti');
13900:         @options =('norequest','approval','validate','autolimit');
13901:         %validations = &Apache::lonnet::auto_courserequest_checks($dom);
13902:         %titles = &courserequest_titles();
13903:         $toolregexp = join('|',@usertools);
13904:         %conditions = &courserequest_conditions();
13905:         $confname = $dom.'-domainconfig';
13906:         my $servadm = $r->dir_config('lonAdmEMail');
13907:         ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
13908:         ($validationitemsref,$validationnamesref,$validationfieldsref) = 
13909:             &Apache::loncoursequeueadmin::requestcourses_validation_types();
13910:     } elsif ($context eq 'requestauthor') {
13911:         @usertools = ('author');
13912:         %titles = &authorrequest_titles();
13913:     } else {
13914:         @usertools = ('aboutme','blog','webdav','portfolio');
13915:         %titles = &tool_titles();
13916:     }
13917:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
13918:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
13919:     foreach my $key (keys(%env)) {
13920:         if ($context eq 'requestcourses') {
13921:             if ($key =~ /^form\.crsreq_($toolregexp)_(.+)$/) {
13922:                 my $item = $1;
13923:                 my $type = $2;
13924:                 if ($type =~ /^limit_(.+)/) {
13925:                     $limithash{$item}{$1} = $env{$key};
13926:                 } else {
13927:                     $confhash{$item}{$type} = $env{$key};
13928:                 }
13929:             }
13930:         } elsif ($context eq 'requestauthor') {
13931:             if ($key =~ /^\Qform.authorreq_\E(.+)$/) {
13932:                 $confhash{$1} = $env{$key};
13933:             }
13934:         } else {
13935:             if ($key =~ /^form\.quota_(.+)$/) {
13936:                 $confhash{'defaultquota'}{$1} = $env{$key};
13937:             } elsif ($key =~ /^form\.authorquota_(.+)$/) {
13938:                 $confhash{'authorquota'}{$1} = $env{$key};
13939:             } elsif ($key =~ /^form\.\Q$context\E_(.+)$/) {
13940:                 @{$toolshash{$1}} = &Apache::loncommon::get_env_multiple($key);
13941:             }
13942:         }
13943:     }
13944:     if (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
13945:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.'.$context.'notifyapproval');
13946:         @approvalnotify = sort(@approvalnotify);
13947:         $confhash{'notify'}{'approval'} = join(',',@approvalnotify);
13948:         my @crstypes = ('official','unofficial','community','textbook','placement','lti');
13949:         my @hasuniquecode = &Apache::loncommon::get_env_multiple('form.uniquecode');
13950:         foreach my $type (@hasuniquecode) {
13951:             if (grep(/^\Q$type\E$/,@crstypes)) {
13952:                 $confhash{'uniquecode'}{$type} = 1;
13953:             }
13954:         }
13955:         my (%newbook,%allpos);
13956:         if ($context eq 'requestcourses') {
13957:             foreach my $type ('textbooks','templates') {
13958:                 @{$allpos{$type}} = (); 
13959:                 my $invalid;
13960:                 if ($type eq 'textbooks') {
13961:                     $invalid = &mt('Invalid LON-CAPA course for textbook');
13962:                 } else {
13963:                     $invalid = &mt('Invalid LON-CAPA course for template');
13964:                 }
13965:                 if ($env{'form.'.$type.'_addbook'}) {
13966:                     if (($env{'form.'.$type.'_addbook_cnum'} =~ /^$match_courseid$/) &&
13967:                         ($env{'form.'.$type.'_addbook_cdom'} =~ /^$match_domain$/)) {
13968:                         if (&Apache::lonnet::homeserver($env{'form.'.$type.'_addbook_cnum'},
13969:                                                         $env{'form.'.$type.'_addbook_cdom'}) eq 'no_host') {
13970:                             $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
13971:                         } else {
13972:                             $newbook{$type} = $env{'form.'.$type.'_addbook_cdom'}.'_'.$env{'form.'.$type.'_addbook_cnum'};
13973:                             my $position = $env{'form.'.$type.'_addbook_pos'};
13974:                             $position =~ s/\D+//g;
13975:                             if ($position ne '') {
13976:                                 $allpos{$type}[$position] = $newbook{$type};
13977:                             }
13978:                         }
13979:                     } else {
13980:                         $errors .= '<li><span class="LC_error">'.$invalid.'</span></li>';
13981:                     }
13982:                 }
13983:             } 
13984:         }
13985:         if (ref($domconfig{$action}) eq 'HASH') {
13986:             if (ref($domconfig{$action}{'notify'}) eq 'HASH') {
13987:                 if ($domconfig{$action}{'notify'}{'approval'} ne $confhash{'notify'}{'approval'}) {
13988:                     $changes{'notify'}{'approval'} = 1;
13989:                 }
13990:             } else {
13991:                 if ($confhash{'notify'}{'approval'}) {
13992:                     $changes{'notify'}{'approval'} = 1;
13993:                 }
13994:             }
13995:             if (ref($domconfig{$action}{'uniquecode'}) eq 'HASH') {
13996:                 if (ref($confhash{'uniquecode'}) eq 'HASH') {
13997:                     foreach my $crstype (keys(%{$domconfig{$action}{'uniquecode'}})) {
13998:                         unless ($confhash{'uniquecode'}{$crstype}) {
13999:                             $changes{'uniquecode'} = 1;
14000:                         }
14001:                     }
14002:                     unless ($changes{'uniquecode'}) {
14003:                         foreach my $crstype (keys(%{$confhash{'uniquecode'}})) {
14004:                             unless ($domconfig{$action}{'uniquecode'}{$crstype}) {
14005:                                 $changes{'uniquecode'} = 1;
14006:                             }
14007:                         }
14008:                     }
14009:                } else {
14010:                    $changes{'uniquecode'} = 1;
14011:                }
14012:             } elsif (ref($confhash{'uniquecode'}) eq 'HASH') {
14013:                 $changes{'uniquecode'} = 1;
14014:             }
14015:             if ($context eq 'requestcourses') {
14016:                 foreach my $type ('textbooks','templates') {
14017:                     if (ref($domconfig{$action}{$type}) eq 'HASH') {
14018:                         my %deletions;
14019:                         my @todelete = &Apache::loncommon::get_env_multiple('form.'.$type.'_del');
14020:                         if (@todelete) {
14021:                             map { $deletions{$_} = 1; } @todelete;
14022:                         }
14023:                         my %imgdeletions;
14024:                         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.'.$type.'_image_del');
14025:                         if (@todeleteimages) {
14026:                             map { $imgdeletions{$_} = 1; } @todeleteimages;
14027:                         }
14028:                         my $maxnum = $env{'form.'.$type.'_maxnum'};
14029:                         for (my $i=0; $i<=$maxnum; $i++) {
14030:                             my $itemid = $env{'form.'.$type.'_id_'.$i};
14031:                             my ($key) = ($itemid =~ /^\Q$type\E_(\w+)$/); 
14032:                             if (ref($domconfig{$action}{$type}{$key}) eq 'HASH') {
14033:                                 if ($deletions{$key}) {
14034:                                     if ($domconfig{$action}{$type}{$key}{'image'}) {
14035:                                         #FIXME need to obsolete item in RES space
14036:                                     }
14037:                                     next;
14038:                                 } else {
14039:                                     my $newpos = $env{'form.'.$itemid};
14040:                                     $newpos =~ s/\D+//g;
14041:                                     foreach my $item ('subject','title','publisher','author') {
14042:                                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14043:                                                  ($type eq 'templates'));
14044:                                         $confhash{$type}{$key}{$item} = $env{'form.'.$type.'_'.$item.'_'.$i};
14045:                                         if ($domconfig{$action}{$type}{$key}{$item} ne $confhash{$type}{$key}{$item}) {
14046:                                             $changes{$type}{$key} = 1;
14047:                                         }
14048:                                     }
14049:                                     $allpos{$type}[$newpos] = $key;
14050:                                 }
14051:                                 if ($imgdeletions{$key}) {
14052:                                     $changes{$type}{$key} = 1;
14053:                                     #FIXME need to obsolete item in RES space
14054:                                 } elsif ($env{'form.'.$type.'_image_'.$i.'.filename'}) {
14055:                                     my ($cdom,$cnum) = split(/_/,$key);
14056:                                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14057:                                         $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14058:                                     } else {
14059:                                         my ($imgurl,$error) = &process_textbook_image($r,$dom,$confname,$type.'_image_'.$i,
14060:                                                                                       $cdom,$cnum,$type,$configuserok,
14061:                                                                                       $switchserver,$author_ok);
14062:                                         if ($imgurl) {
14063:                                             $confhash{$type}{$key}{'image'} = $imgurl;
14064:                                             $changes{$type}{$key} = 1; 
14065:                                         }
14066:                                         if ($error) {
14067:                                             &Apache::lonnet::logthis($error);
14068:                                             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14069:                                         }
14070:                                     }
14071:                                 } elsif ($domconfig{$action}{$type}{$key}{'image'}) {
14072:                                     $confhash{$type}{$key}{'image'} = 
14073:                                         $domconfig{$action}{$type}{$key}{'image'};
14074:                                 }
14075:                             }
14076:                         }
14077:                     }
14078:                 }
14079:             }
14080:         } else {
14081:             if ($confhash{'notify'}{'approval'}) {
14082:                 $changes{'notify'}{'approval'} = 1;
14083:             }
14084:             if (ref($confhash{'uniquecode'} eq 'HASH')) {
14085:                 $changes{'uniquecode'} = 1;
14086:             }
14087:         }
14088:         if ($context eq 'requestcourses') {
14089:             foreach my $type ('textbooks','templates') {
14090:                 if ($newbook{$type}) {
14091:                     $changes{$type}{$newbook{$type}} = 1;
14092:                     foreach my $item ('subject','title','publisher','author') {
14093:                         next if ((($item eq 'author') || ($item eq 'publisher')) &&
14094:                                  ($type eq 'template'));
14095:                         $env{'form.'.$type.'_addbook_'.$item} =~ s/(`)/'/g;
14096:                         if ($env{'form.'.$type.'_addbook_'.$item}) {
14097:                             $confhash{$type}{$newbook{$type}}{$item} = $env{'form.'.$type.'_addbook_'.$item};
14098:                         }
14099:                     }
14100:                     if ($type eq 'textbooks') {
14101:                         if ($env{'form.'.$type.'_addbook_image.filename'} ne '') {
14102:                             my ($cdom,$cnum) = split(/_/,$newbook{$type});
14103:                             if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
14104:                                 $errors .= '<li><span class="LC_error">'.&mt('Image not saved: could not find textbook course').'</li>';
14105:                             } else {
14106:                                 my ($imageurl,$error) =
14107:                                     &process_textbook_image($r,$dom,$confname,$type.'_addbook_image',$cdom,$cnum,$type,
14108:                                                             $configuserok,$switchserver,$author_ok);
14109:                                 if ($imageurl) {
14110:                                     $confhash{$type}{$newbook{$type}}{'image'} = $imageurl;
14111:                                 }
14112:                                 if ($error) {
14113:                                     &Apache::lonnet::logthis($error);
14114:                                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14115:                                 }
14116:                             }
14117:                         }
14118:                     }
14119:                 }
14120:                 if (@{$allpos{$type}} > 0) {
14121:                     my $idx = 0;
14122:                     foreach my $item (@{$allpos{$type}}) {
14123:                         if ($item ne '') {
14124:                             $confhash{$type}{$item}{'order'} = $idx;
14125:                             if (ref($domconfig{$action}) eq 'HASH') {
14126:                                 if (ref($domconfig{$action}{$type}) eq 'HASH') {
14127:                                     if (ref($domconfig{$action}{$type}{$item}) eq 'HASH') {
14128:                                         if ($domconfig{$action}{$type}{$item}{'order'} ne $idx) {
14129:                                             $changes{$type}{$item} = 1;
14130:                                         }
14131:                                     }
14132:                                 }
14133:                             }
14134:                             $idx ++;
14135:                         }
14136:                     }
14137:                 }
14138:             }
14139:             if (ref($validationitemsref) eq 'ARRAY') {
14140:                 foreach my $item (@{$validationitemsref}) {
14141:                     if ($item eq 'fields') {
14142:                         my @changed;
14143:                         @{$confhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.requestcourses_validation_'.$item);
14144:                         if (@{$confhash{'validation'}{$item}} > 0) {
14145:                             @{$confhash{'validation'}{$item}} = sort(@{$confhash{'validation'}{$item}});
14146:                         }
14147:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14148:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14149:                                 if (ref($domconfig{'requestcourses'}{'validation'}{$item}) eq 'ARRAY') {
14150:                                     @changed = &Apache::loncommon::compare_arrays($confhash{'validation'}{$item},
14151:                                                                                   $domconfig{'requestcourses'}{'validation'}{$item});
14152:                                 } else {
14153:                                     @changed = @{$confhash{'validation'}{$item}};
14154:                                 }
14155:                             } else {
14156:                                 @changed = @{$confhash{'validation'}{$item}};
14157:                             }
14158:                         } else {
14159:                             @changed = @{$confhash{'validation'}{$item}};
14160:                         }
14161:                         if (@changed) {
14162:                             if ($confhash{'validation'}{$item}) {
14163:                                 $changes{'validation'}{$item} = join(', ',@{$confhash{'validation'}{$item}});
14164:                             } else {
14165:                                 $changes{'validation'}{$item} = &mt('None');
14166:                             }
14167:                         }
14168:                     } else {
14169:                         $confhash{'validation'}{$item} = $env{'form.requestcourses_validation_'.$item};
14170:                         if ($item eq 'markup') {
14171:                             if ($env{'form.requestcourses_validation_'.$item}) {
14172:                                 $env{'form.requestcourses_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
14173:                             }
14174:                         }
14175:                         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14176:                             if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14177:                                 if ($domconfig{'requestcourses'}{'validation'}{$item} ne $confhash{'validation'}{$item}) {
14178:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14179:                                 }
14180:                             } else {
14181:                                 if ($confhash{'validation'}{$item} ne '') {
14182:                                     $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14183:                                 }
14184:                             }
14185:                         } else {
14186:                             if ($confhash{'validation'}{$item} ne '') {
14187:                                 $changes{'validation'}{$item} = $confhash{'validation'}{$item};
14188:                             }
14189:                         }
14190:                     }
14191:                 }
14192:             }
14193:             if ($env{'form.validationdc'}) {
14194:                 my $newval = $env{'form.validationdc'};
14195:                 my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
14196:                 if (exists($domcoords{$newval})) {
14197:                     $confhash{'validation'}{'dc'} = $newval;
14198:                 }
14199:             }
14200:             if (ref($confhash{'validation'}) eq 'HASH') {
14201:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14202:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14203:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14204:                             unless ($confhash{'validation'}{'dc'} eq $domconfig{'requestcourses'}{'validation'}{'dc'}) {
14205:                                 if ($confhash{'validation'}{'dc'} eq '') {
14206:                                     $changes{'validation'}{'dc'} = &mt('None');
14207:                                 } else {
14208:                                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14209:                                 }
14210:                             }
14211:                         } elsif ($confhash{'validation'}{'dc'} ne '') {
14212:                             $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14213:                         }
14214:                     } elsif ($confhash{'validation'}{'dc'} ne '') {
14215:                         $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14216:                     }
14217:                 } elsif ($confhash{'validation'}{'dc'} ne '') {
14218:                     $changes{'validation'}{'dc'} = $confhash{'validation'}{'dc'};
14219:                 }
14220:             } else {
14221:                 if (ref($domconfig{'requestcourses'}) eq 'HASH') {
14222:                     if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
14223:                         if ($domconfig{'requestcourses'}{'validation'}{'dc'}) {
14224:                             $changes{'validation'}{'dc'} = &mt('None');
14225:                         }
14226:                     }
14227:                 }
14228:             }
14229:         }
14230:     } else {
14231:         $confhash{'defaultquota'}{'default'} = $env{'form.defaultquota'};
14232:         $confhash{'authorquota'}{'default'} = $env{'form.authorquota'};
14233:     }
14234:     foreach my $item (@usertools) {
14235:         foreach my $type (@{$types},'default','_LC_adv') {
14236:             my $unset; 
14237:             if ($context eq 'requestcourses') {
14238:                 $unset = '0';
14239:                 if ($type eq '_LC_adv') {
14240:                     $unset = '';
14241:                 }
14242:                 if ($confhash{$item}{$type} eq 'autolimit') {
14243:                     $confhash{$item}{$type} .= '=';
14244:                     unless ($limithash{$item}{$type} =~ /\D/) {
14245:                         $confhash{$item}{$type} .= $limithash{$item}{$type};
14246:                     }
14247:                 }
14248:             } elsif ($context eq 'requestauthor') {
14249:                 $unset = '0';
14250:                 if ($type eq '_LC_adv') {
14251:                     $unset = '';
14252:                 }
14253:             } else {
14254:                 if (grep(/^\Q$type\E$/,@{$toolshash{$item}})) {
14255:                     $confhash{$item}{$type} = 1;
14256:                 } else {
14257:                     $confhash{$item}{$type} = 0;
14258:                 }
14259:             }
14260:             if (ref($domconfig{$action}) eq 'HASH') {
14261:                 if ($action eq 'requestauthor') {
14262:                     if ($domconfig{$action}{$type} ne $confhash{$type}) {
14263:                         $changes{$type} = 1;
14264:                     }
14265:                 } elsif (ref($domconfig{$action}{$item}) eq 'HASH') {
14266:                     if ($domconfig{$action}{$item}{$type} ne $confhash{$item}{$type}) {
14267:                         $changes{$item}{$type} = 1;
14268:                     }
14269:                 } else {
14270:                     if ($context eq 'requestcourses') {
14271:                         if ($confhash{$item}{$type} ne $unset) {
14272:                             $changes{$item}{$type} = 1;
14273:                         }
14274:                     } else {
14275:                         if (!$confhash{$item}{$type}) {
14276:                             $changes{$item}{$type} = 1;
14277:                         }
14278:                     }
14279:                 }
14280:             } else {
14281:                 if ($context eq 'requestcourses') {
14282:                     if ($confhash{$item}{$type} ne $unset) {
14283:                         $changes{$item}{$type} = 1;
14284:                     }
14285:                 } elsif ($context eq 'requestauthor') {
14286:                     if ($confhash{$type} ne $unset) {
14287:                         $changes{$type} = 1;
14288:                     }
14289:                 } else {
14290:                     if (!$confhash{$item}{$type}) {
14291:                         $changes{$item}{$type} = 1;
14292:                     }
14293:                 }
14294:             }
14295:         }
14296:     }
14297:     unless (($context eq 'requestcourses') || ($context eq 'requestauthor')) {
14298:         if (ref($domconfig{'quotas'}) eq 'HASH') {
14299:             if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14300:                 foreach my $key (keys(%{$domconfig{'quotas'}{'defaultquota'}})) {
14301:                     if (exists($confhash{'defaultquota'}{$key})) {
14302:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{'defaultquota'}{$key}) {
14303:                             $changes{'defaultquota'}{$key} = 1;
14304:                         }
14305:                     } else {
14306:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{'defaultquota'}{$key};
14307:                     }
14308:                 }
14309:             } else {
14310:                 foreach my $key (keys(%{$domconfig{'quotas'}})) {
14311:                     if (exists($confhash{'defaultquota'}{$key})) {
14312:                         if ($confhash{'defaultquota'}{$key} ne $domconfig{'quotas'}{$key}) {
14313:                             $changes{'defaultquota'}{$key} = 1;
14314:                         }
14315:                     } else {
14316:                         $confhash{'defaultquota'}{$key} = $domconfig{'quotas'}{$key};
14317:                     }
14318:                 }
14319:             }
14320:             if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14321:                 foreach my $key (keys(%{$domconfig{'quotas'}{'authorquota'}})) {
14322:                     if (exists($confhash{'authorquota'}{$key})) {
14323:                         if ($confhash{'authorquota'}{$key} ne $domconfig{'quotas'}{'authorquota'}{$key}) {
14324:                             $changes{'authorquota'}{$key} = 1;
14325:                         }
14326:                     } else {
14327:                         $confhash{'authorquota'}{$key} = $domconfig{'quotas'}{'authorquota'}{$key};
14328:                     }
14329:                 }
14330:             }
14331:         }
14332:         if (ref($confhash{'defaultquota'}) eq 'HASH') {
14333:             foreach my $key (keys(%{$confhash{'defaultquota'}})) {
14334:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14335:                     if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
14336:                         if (!exists($domconfig{'quotas'}{'defaultquota'}{$key})) {
14337:                             $changes{'defaultquota'}{$key} = 1;
14338:                         }
14339:                     } else {
14340:                         if (!exists($domconfig{'quotas'}{$key})) {
14341:                             $changes{'defaultquota'}{$key} = 1;
14342:                         }
14343:                     }
14344:                 } else {
14345:                     $changes{'defaultquota'}{$key} = 1;
14346:                 }
14347:             }
14348:         }
14349:         if (ref($confhash{'authorquota'}) eq 'HASH') {
14350:             foreach my $key (keys(%{$confhash{'authorquota'}})) {
14351:                 if (ref($domconfig{'quotas'}) eq 'HASH') {
14352:                     if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
14353:                         if (!exists($domconfig{'quotas'}{'authorquota'}{$key})) {
14354:                             $changes{'authorquota'}{$key} = 1;
14355:                         }
14356:                     } else {
14357:                         $changes{'authorquota'}{$key} = 1;
14358:                     }
14359:                 } else {
14360:                     $changes{'authorquota'}{$key} = 1;
14361:                 }
14362:             }
14363:         }
14364:     }
14365: 
14366:     if ($context eq 'requestauthor') {
14367:         $domdefaults{'requestauthor'} = \%confhash;
14368:     } else {
14369:         foreach my $key (keys(%confhash)) {
14370:             unless (($context eq 'requestcourses') && (($key eq 'textbooks') || ($key eq 'templates'))) {
14371:                 $domdefaults{$key} = $confhash{$key};
14372:             }
14373:         }
14374:     }
14375: 
14376:     my %quotahash = (
14377:                       $action => { %confhash }
14378:                     );
14379:     my $putresult = &Apache::lonnet::put_dom('configuration',\%quotahash,
14380:                                              $dom);
14381:     if ($putresult eq 'ok') {
14382:         if (keys(%changes) > 0) {
14383:             my $cachetime = 24*60*60;
14384:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
14385:             if (ref($lastactref) eq 'HASH') {
14386:                 $lastactref->{'domdefaults'} = 1;
14387:             }
14388:             $resulttext = &mt('Changes made:').'<ul>';
14389:             unless (($context eq 'requestcourses') ||
14390:                     ($context eq 'requestauthor')) {
14391:                 if (ref($changes{'defaultquota'}) eq 'HASH') {
14392:                     $resulttext .= '<li>'.&mt('Portfolio default quotas').'<ul>';
14393:                     foreach my $type (@{$types},'default') {
14394:                         if (defined($changes{'defaultquota'}{$type})) {
14395:                             my $typetitle = $usertypes->{$type};
14396:                             if ($type eq 'default') {
14397:                                 $typetitle = $othertitle;
14398:                             }
14399:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'defaultquota'}{$type}).'</li>';
14400:                         }
14401:                     }
14402:                     $resulttext .= '</ul></li>';
14403:                 }
14404:                 if (ref($changes{'authorquota'}) eq 'HASH') {
14405:                     $resulttext .= '<li>'.&mt('Authoring Space default quotas').'<ul>';
14406:                     foreach my $type (@{$types},'default') {
14407:                         if (defined($changes{'authorquota'}{$type})) {
14408:                             my $typetitle = $usertypes->{$type};
14409:                             if ($type eq 'default') {
14410:                                 $typetitle = $othertitle;
14411:                             }
14412:                             $resulttext .= '<li>'.&mt('[_1] set to [_2] MB',$typetitle,$confhash{'authorquota'}{$type}).'</li>';
14413:                         }
14414:                     }
14415:                     $resulttext .= '</ul></li>';
14416:                 }
14417:             }
14418:             my %newenv;
14419:             foreach my $item (@usertools) {
14420:                 my (%haschgs,%inconf);
14421:                 if ($context eq 'requestauthor') {
14422:                     %haschgs = %changes;
14423:                     %inconf = %confhash;
14424:                 } else {
14425:                     if (ref($changes{$item}) eq 'HASH') {
14426:                         %haschgs = %{$changes{$item}};
14427:                     }
14428:                     if (ref($confhash{$item}) eq 'HASH') {
14429:                         %inconf = %{$confhash{$item}};
14430:                     }
14431:                 }
14432:                 if (keys(%haschgs) > 0) {
14433:                     my $newacc = 
14434:                         &Apache::lonnet::usertools_access($env{'user.name'},
14435:                                                           $env{'user.domain'},
14436:                                                           $item,'reload',$context);
14437:                     if (($context eq 'requestcourses') ||
14438:                         ($context eq 'requestauthor')) {
14439:                         if ($env{'environment.canrequest.'.$item} ne $newacc) {
14440:                             $newenv{'environment.canrequest.'.$item} = $newacc;
14441:                         }
14442:                     } else {
14443:                         if ($env{'environment.availabletools.'.$item} ne $newacc) { 
14444:                             $newenv{'environment.availabletools.'.$item} = $newacc;
14445:                         }
14446:                     }
14447:                     unless ($context eq 'requestauthor') {
14448:                         $resulttext .= '<li>'.$titles{$item}.'<ul>';
14449:                     }
14450:                     foreach my $type (@{$types},'default','_LC_adv') {
14451:                         if ($haschgs{$type}) {
14452:                             my $typetitle = $usertypes->{$type};
14453:                             if ($type eq 'default') {
14454:                                 $typetitle = $othertitle;
14455:                             } elsif ($type eq '_LC_adv') {
14456:                                 $typetitle = 'LON-CAPA Advanced Users'; 
14457:                             }
14458:                             if ($inconf{$type}) {
14459:                                 if ($context eq 'requestcourses') {
14460:                                     my $cond;
14461:                                     if ($inconf{$type} =~ /^autolimit=(\d*)$/) {
14462:                                         if ($1 eq '') {
14463:                                             $cond = &mt('(Automatic processing of any request).');
14464:                                         } else {
14465:                                             $cond = &mt('(Automatic processing of requests up to limit of [quant,_1,request] per user).',$1);
14466:                                         }
14467:                                     } else { 
14468:                                         $cond = $conditions{$inconf{$type}};
14469:                                     }
14470:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1].',$typetitle).' '.$cond.'</li>';
14471:                                 } elsif ($context eq 'requestauthor') {
14472:                                     $resulttext .= '<li>'.&mt('Set to "[_1]" for "[_2]".',
14473:                                                              $titles{$inconf{$type}},$typetitle);
14474: 
14475:                                 } else {
14476:                                     $resulttext .= '<li>'.&mt('Set to be available to [_1]',$typetitle).'</li>';
14477:                                 }
14478:                             } else {
14479:                                 if ($type eq '_LC_adv') {
14480:                                     if ($inconf{$type} eq '0') {
14481:                                         $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14482:                                     } else { 
14483:                                         $resulttext .= '<li>'.&mt('No override set for [_1]',$typetitle).'</li>';
14484:                                     }
14485:                                 } else {
14486:                                     $resulttext .= '<li>'.&mt('Set to be unavailable to [_1]',$typetitle).'</li>';
14487:                                 }
14488:                             }
14489:                         }
14490:                     }
14491:                     unless ($context eq 'requestauthor') {
14492:                         $resulttext .= '</ul></li>';
14493:                     }
14494:                 }
14495:             }
14496:             if (($action eq 'requestcourses') || ($action eq 'requestauthor')) {
14497:                 if (ref($changes{'notify'}) eq 'HASH') {
14498:                     if ($changes{'notify'}{'approval'}) {
14499:                         if (ref($confhash{'notify'}) eq 'HASH') {
14500:                             if ($confhash{'notify'}{'approval'}) {
14501:                                 $resulttext .= '<li>'.&mt('Notification of requests requiring approval will be sent to: ').$confhash{'notify'}{'approval'}.'</li>';
14502:                             } else {
14503:                                 $resulttext .= '<li>'.&mt('No Domain Coordinators will receive notification of requests requiring approval.').'</li>';
14504:                             }
14505:                         }
14506:                     }
14507:                 }
14508:             }
14509:             if ($action eq 'requestcourses') {
14510:                 my @offon = ('off','on');
14511:                 if ($changes{'uniquecode'}) {
14512:                     if (ref($confhash{'uniquecode'}) eq 'HASH') {
14513:                         my $codestr = join(' ',map{ &mt($_); } sort(keys(%{$confhash{'uniquecode'}})));
14514:                         $resulttext .= '<li>'.
14515:                                        &mt('Generation of six character code as course identifier for distribution to students set to on for: [_1].','<b>'.$codestr.'</b>').
14516:                                        '</li>';
14517:                     } else {
14518:                         $resulttext .= '<li>'.&mt('Generation of six character code as course identifier for distribution to students set to off.').
14519:                                        '</li>';
14520:                     }
14521:                 }
14522:                 foreach my $type ('textbooks','templates') {
14523:                     if (ref($changes{$type}) eq 'HASH') {
14524:                         $resulttext .= '<li>'.&mt("Available $type updated").'<ul>';
14525:                         foreach my $key (sort(keys(%{$changes{$type}}))) {
14526:                             my %coursehash = &Apache::lonnet::coursedescription($key);
14527:                             my $coursetitle = $coursehash{'description'};
14528:                             my $position = $confhash{$type}{$key}{'order'} + 1;
14529:                             $resulttext .= '<li>';
14530:                             foreach my $item ('subject','title','publisher','author') {
14531:                                 next if ((($item eq 'author') || ($item eq 'publisher')) &&
14532:                                          ($type eq 'templates'));
14533:                                 my $name = $item.':';
14534:                                 $name =~ s/^(\w)/\U$1/;
14535:                                 $resulttext .= &mt($name).' '.$confhash{$type}{$key}{$item}.'<br />';
14536:                             }
14537:                             $resulttext .= ' '.&mt('Order: [_1]',$position).'<br />';
14538:                             if ($type eq 'textbooks') {
14539:                                 if ($confhash{$type}{$key}{'image'}) {
14540:                                     $resulttext .= ' '.&mt('Image: [_1]',
14541:                                                    '<img src="'.$confhash{$type}{$key}{'image'}.'"'.
14542:                                                    ' alt="Textbook cover" />').'<br />';
14543:                                 }
14544:                             }
14545:                             $resulttext .= ' '.&mt('LON-CAPA Course: [_1]',$coursetitle).'</li>';
14546:                         }
14547:                         $resulttext .= '</ul></li>';
14548:                     }
14549:                 }
14550:                 if (ref($changes{'validation'}) eq 'HASH') {
14551:                     if ((ref($validationitemsref) eq 'ARRAY') && (ref($validationnamesref) eq 'HASH')) {
14552:                         $resulttext .= '<li>'.&mt('Validation of courses/communities updated').'<ul>';
14553:                         foreach my $item (@{$validationitemsref}) {
14554:                             if (exists($changes{'validation'}{$item})) {
14555:                                 if ($item eq 'markup') {
14556:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14557:                                                               '<br /><pre>'.$changes{'validation'}{$item}.'</pre>').'</li>';
14558:                                 } else {
14559:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$validationnamesref->{$item},
14560:                                                               '<b>'.$changes{'validation'}{$item}.'</b>').'</li>';
14561:                                 }
14562:                             }
14563:                         }
14564:                         if (exists($changes{'validation'}{'dc'})) {
14565:                             $resulttext .= '<li>'.&mt('Validated course requests identified as processed by: [_1]',
14566:                                                      '<b>'.$changes{'validation'}{'dc'}.'</b>').'</li>';
14567:                         }
14568:                     }
14569:                 }
14570:             }
14571:             $resulttext .= '</ul>';
14572:             if (keys(%newenv)) {
14573:                 &Apache::lonnet::appenv(\%newenv);
14574:             }
14575:         } else {
14576:             if ($context eq 'requestcourses') {
14577:                 $resulttext = &mt('No changes made to rights to request creation of courses.');
14578:             } elsif ($context eq 'requestauthor') {
14579:                 $resulttext = &mt('No changes made to rights to request author space.');
14580:             } else {
14581:                 $resulttext = &mt('No changes made to availability of personal information pages, blogs, portfolios or default quotas');
14582:             }
14583:         }
14584:     } else {
14585:         $resulttext = '<span class="LC_error">'.
14586: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
14587:     }
14588:     if ($errors) {
14589:         $resulttext .= '<p>'.&mt('The following errors occurred when modifying Textbook settings.').
14590:                        '<ul>'.$errors.'</ul></p>';
14591:     }
14592:     return $resulttext;
14593: }
14594: 
14595: sub process_textbook_image {
14596:     my ($r,$dom,$confname,$caller,$cdom,$cnum,$type,$configuserok,$switchserver,$author_ok) = @_;
14597:     my $filename = $env{'form.'.$caller.'.filename'};
14598:     my ($error,$url);
14599:     my ($width,$height) = (50,50);
14600:     if ($configuserok eq 'ok') {
14601:         if ($switchserver) {
14602:             $error = &mt('Upload of textbook image is not permitted to this server: [_1]',
14603:                          $switchserver);
14604:         } elsif ($author_ok eq 'ok') {
14605:             my ($result,$imageurl) =
14606:                 &publishlogo($r,'upload',$caller,$dom,$confname,
14607:                              "$type/$cdom/$cnum/cover",$width,$height);
14608:             if ($result eq 'ok') {
14609:                 $url = $imageurl;
14610:             } else {
14611:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
14612:             }
14613:         } else {
14614:             $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);
14615:         }
14616:     } else {
14617:         $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);
14618:     }
14619:     return ($url,$error);
14620: }
14621: 
14622: sub modify_ltitools {
14623:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
14624:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
14625:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
14626:     my $confname = $dom.'-domainconfig';
14627:     my $servadm = $r->dir_config('lonAdmEMail');
14628:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
14629:     my (%posslti,%possfield);
14630:     my @courseroles = ('cc','in','ta','ep','st');
14631:     my @ltiroles = qw(Instructor ContentDeveloper TeachingAssistant Learner);
14632:     map { $posslti{$_} = 1; } @ltiroles;
14633:     my @allfields = ('fullname','firstname','lastname','email','user','roles');
14634:     map { $possfield{$_} = 1; } @allfields;
14635:     my %lt = &ltitools_names(); 
14636:     if ($env{'form.ltitools_add'}) {
14637:         my $title = $env{'form.ltitools_add_title'};
14638:         $title =~ s/(`)/'/g;
14639:         ($newid,my $error) = &get_ltitools_id($dom,$title);
14640:         if ($newid) {
14641:             my $position = $env{'form.ltitools_add_pos'};
14642:             $position =~ s/\D+//g;
14643:             if ($position ne '') {
14644:                 $allpos[$position] = $newid;
14645:             }
14646:             $changes{$newid} = 1;
14647:             foreach my $item ('title','url','key','secret','lifetime') {
14648:                 $env{'form.ltitools_add_'.$item} =~ s/(`)/'/g;
14649:                 if ($item eq 'lifetime') {
14650:                     $env{'form.ltitools_add_'.$item} =~ s/[^\d.]//g;
14651:                 }
14652:                 if ($env{'form.ltitools_add_'.$item}) {
14653:                     if (($item eq 'key') || ($item eq 'secret')) {
14654:                         $encconfig{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14655:                     } else {
14656:                         $confhash{$newid}{$item} = $env{'form.ltitools_add_'.$item};
14657:                     }
14658:                 }
14659:             }
14660:             if ($env{'form.ltitools_add_version'} eq 'LTI-1p0') {
14661:                 $confhash{$newid}{'version'} = $env{'form.ltitools_add_version'};
14662:             }
14663:             if ($env{'form.ltitools_add_msgtype'} eq 'basic-lti-launch-request') {
14664:                 $confhash{$newid}{'msgtype'} = $env{'form.ltitools_add_msgtype'};
14665:             }
14666:             if ($env{'form.ltitools_add_sigmethod'} eq 'HMAC-SHA256') {
14667:                 $confhash{$newid}{'sigmethod'} = $env{'form.ltitools_add_sigmethod'};
14668:             } else {
14669:                 $confhash{$newid}{'sigmethod'} = 'HMAC-SHA1';
14670:             }
14671:             foreach my $item ('width','height','linktext','explanation') {
14672:                 $env{'form.ltitools_add_'.$item} =~ s/^\s+//;
14673:                 $env{'form.ltitools_add_'.$item} =~ s/\s+$//;
14674:                 if (($item eq 'width') || ($item eq 'height')) {
14675:                     if ($env{'form.ltitools_add_'.$item} =~ /^\d+$/) {
14676:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item};
14677:                     }
14678:                 } else {
14679:                     if ($env{'form.ltitools_add_'.$item} ne '') {
14680:                         $confhash{$newid}{'display'}{$item} = $env{'form.ltitools_add_'.$item}; 
14681:                     }
14682:                 }
14683:             }
14684:             if ($env{'form.ltitools_add_target'} eq 'window') {
14685:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14686:             } elsif ($env{'form.ltitools_add_target'} eq 'tab') {
14687:                 $confhash{$newid}{'display'}{'target'} = $env{'form.ltitools_add_target'};
14688:             } else {
14689:                 $confhash{$newid}{'display'}{'target'} = 'iframe';
14690:             }
14691:             foreach my $item ('passback','roster') {
14692:                 if ($env{'form.ltitools_'.$item.'_add'}) {
14693:                     $confhash{$newid}{$item} = 1;
14694:                     if ($env{'form.ltitools_'.$item.'valid_add'} ne '') {
14695:                         my $lifetime = $env{'form.ltitools_'.$item.'valid_add'};
14696:                         $lifetime =~ s/^\s+|\s+$//g;
14697:                         if ($lifetime =~ /^\d+\.?\d*$/) {
14698:                             $confhash{$newid}{$item.'valid'} = $lifetime;
14699:                         }
14700:                     }
14701:                 }
14702:             }
14703:             if ($env{'form.ltitools_add_image.filename'} ne '') {
14704:                 my ($imageurl,$error) =
14705:                     &process_ltitools_image($r,$dom,$confname,'ltitools_add_image',$newid,
14706:                                             $configuserok,$switchserver,$author_ok);
14707:                 if ($imageurl) {
14708:                     $confhash{$newid}{'image'} = $imageurl;
14709:                 }
14710:                 if ($error) {
14711:                     &Apache::lonnet::logthis($error);
14712:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14713:                 }
14714:             }
14715:             my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_add_fields');
14716:             foreach my $field (@fields) {
14717:                 if ($possfield{$field}) {
14718:                     if ($field eq 'roles') {
14719:                         foreach my $role (@courseroles) {
14720:                             my $choice = $env{'form.ltitools_add_roles_'.$role};
14721:                             if (($choice ne '') && ($posslti{$choice})) {
14722:                                 $confhash{$newid}{'roles'}{$role} = $choice;
14723:                                 if ($role eq 'cc') {
14724:                                     $confhash{$newid}{'roles'}{'co'} = $choice; 
14725:                                 }
14726:                             }
14727:                         }
14728:                     } else {
14729:                         $confhash{$newid}{'fields'}{$field} = 1;
14730:                     }
14731:                 }
14732:             }
14733:             if (ref($confhash{$newid}{'fields'}) eq 'HASH') {
14734:                 if ($confhash{$newid}{'fields'}{'user'}) {
14735:                     if ($env{'form.ltitools_userincdom_add'}) {
14736:                         $confhash{$newid}{'incdom'} = 1;
14737:                     }
14738:                 }
14739:             }
14740:             my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig');
14741:             foreach my $item (@courseconfig) {
14742:                 $confhash{$newid}{'crsconf'}{$item} = 1;
14743:             }
14744:             if ($env{'form.ltitools_add_custom'}) {
14745:                 my $name = $env{'form.ltitools_add_custom_name'};
14746:                 my $value = $env{'form.ltitools_add_custom_value'};
14747:                 $value =~ s/(`)/'/g;
14748:                 $name =~ s/(`)/'/g;
14749:                 $confhash{$newid}{'custom'}{$name} = $value;
14750:             }
14751:         } else {
14752:             my $error = &mt('Failed to acquire unique ID for new external tool');   
14753:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14754:         }
14755:     }
14756:     if (ref($domconfig{$action}) eq 'HASH') {
14757:         my %deletions;
14758:         my @todelete = &Apache::loncommon::get_env_multiple('form.ltitools_del');
14759:         if (@todelete) {
14760:             map { $deletions{$_} = 1; } @todelete;
14761:         }
14762:         my %customadds;
14763:         my @newcustom = &Apache::loncommon::get_env_multiple('form.ltitools_customadd');
14764:         if (@newcustom) {
14765:             map { $customadds{$_} = 1; } @newcustom;
14766:         } 
14767:         my %imgdeletions;
14768:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.ltitools_image_del');
14769:         if (@todeleteimages) {
14770:             map { $imgdeletions{$_} = 1; } @todeleteimages;
14771:         }
14772:         my $maxnum = $env{'form.ltitools_maxnum'};
14773:         for (my $i=0; $i<=$maxnum; $i++) {
14774:             my $itemid = $env{'form.ltitools_id_'.$i};
14775:             $itemid =~ s/\D+//g;
14776:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
14777:                 if ($deletions{$itemid}) {
14778:                     if ($domconfig{$action}{$itemid}{'image'}) {
14779:                         #FIXME need to obsolete item in RES space
14780:                     }
14781:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'title'};
14782:                     next;
14783:                 } else {
14784:                     my $newpos = $env{'form.ltitools_'.$itemid};
14785:                     $newpos =~ s/\D+//g;
14786:                     foreach my $item ('title','url','lifetime') {
14787:                         $confhash{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14788:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
14789:                             $changes{$itemid} = 1;
14790:                         }
14791:                     }
14792:                     foreach my $item ('key','secret') {
14793:                         $encconfig{$itemid}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14794:                         if ($domconfig{$action}{$itemid}{$item} ne $encconfig{$itemid}{$item}) {
14795:                             $changes{$itemid} = 1;
14796:                         }
14797:                     }
14798:                     if ($env{'form.ltitools_version_'.$i} eq 'LTI-1p0') {
14799:                         $confhash{$itemid}{'version'} = $env{'form.ltitools_version_'.$i};
14800:                     }
14801:                     if ($env{'form.ltitools_msgtype_'.$i} eq 'basic-lti-launch-request') {
14802:                         $confhash{$itemid}{'msgtype'} = $env{'form.ltitools_msgtype_'.$i};
14803:                     }
14804:                     if ($env{'form.ltitools_sigmethod_'.$i} eq 'HMAC-SHA256') {
14805:                         $confhash{$itemid}{'sigmethod'} = $env{'form.ltitools_sigmethod_'.$i};
14806:                     } else {
14807:                         $confhash{$itemid}{'sigmethod'} = 'HMAC-SHA1'; 
14808:                     }
14809:                     if ($domconfig{$action}{$itemid}{'sigmethod'} eq '') {
14810:                         if ($confhash{$itemid}{'sigmethod'} ne 'HMAC-SHA1') {
14811:                             $changes{$itemid} = 1;
14812:                         }
14813:                     } elsif ($domconfig{$action}{$itemid}{'sigmethod'} ne $confhash{$itemid}{'sigmethod'}) {
14814:                         $changes{$itemid} = 1;
14815:                     }
14816:                     foreach my $size ('width','height') {
14817:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/^\s+//;
14818:                         $env{'form.ltitools_'.$size.'_'.$i} =~ s/\s+$//;
14819:                         if ($env{'form.ltitools_'.$size.'_'.$i} =~ /^\d+$/) {
14820:                             $confhash{$itemid}{'display'}{$size} = $env{'form.ltitools_'.$size.'_'.$i};
14821:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14822:                                 if ($domconfig{$action}{$itemid}{'display'}{$size} ne $confhash{$itemid}{'display'}{$size}) {
14823:                                     $changes{$itemid} = 1;
14824:                                 }
14825:                             } else {
14826:                                 $changes{$itemid} = 1;
14827:                             }
14828:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14829:                             if ($domconfig{$action}{$itemid}{'display'}{$size} ne '') {
14830:                                 $changes{$itemid} = 1;
14831:                             }
14832:                         }
14833:                     }
14834:                     foreach my $item ('linktext','explanation') {
14835:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/^\s+//;
14836:                         $env{'form.ltitools_'.$item.'_'.$i} =~ s/\s+$//;
14837:                         if ($env{'form.ltitools_'.$item.'_'.$i} ne '') {
14838:                             $confhash{$itemid}{'display'}{$item} = $env{'form.ltitools_'.$item.'_'.$i};
14839:                             if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14840:                                 if ($domconfig{$action}{$itemid}{'display'}{$item} ne $confhash{$itemid}{'display'}{$item}) {
14841:                                     $changes{$itemid} = 1;
14842:                                 }
14843:                             } else {
14844:                                 $changes{$itemid} = 1;
14845:                             }
14846:                         } elsif (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14847:                             if ($domconfig{$action}{$itemid}{'display'}{$item} ne '') {
14848:                                 $changes{$itemid} = 1;
14849:                             }
14850:                         }
14851:                     }
14852:                     if ($env{'form.ltitools_target_'.$i} eq 'window') {
14853:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14854:                     } elsif ($env{'form.ltitools_target_'.$i} eq 'tab') {
14855:                         $confhash{$itemid}{'display'}{'target'} = $env{'form.ltitools_target_'.$i};
14856:                     } else {
14857:                         $confhash{$itemid}{'display'}{'target'} = 'iframe';
14858:                     }
14859:                     if (ref($domconfig{$action}{$itemid}{'display'}) eq 'HASH') {
14860:                         if ($domconfig{$action}{$itemid}{'display'}{'target'} ne $confhash{$itemid}{'display'}{'target'}) {
14861:                             $changes{$itemid} = 1;
14862:                         }
14863:                     } else {
14864:                         $changes{$itemid} = 1;
14865:                     }
14866:                     foreach my $extra ('passback','roster') {
14867:                         if ($env{'form.ltitools_'.$extra.'_'.$i}) {
14868:                             $confhash{$itemid}{$extra} = 1;
14869:                             if ($env{'form.ltitools_'.$extra.'valid_'.$i} ne '') {
14870:                                 my $lifetime = $env{'form.ltitools_'.$extra.'valid_'.$i};
14871:                                 $lifetime =~ s/^\s+|\s+$//g;
14872:                                 if ($lifetime =~ /^\d+\.?\d*$/) {
14873:                                     $confhash{$itemid}{$extra.'valid'} = $lifetime;
14874:                                 }
14875:                             }
14876:                         }
14877:                         if ($domconfig{$action}{$itemid}{$extra} ne $confhash{$itemid}{$extra}) {
14878:                             $changes{$itemid} = 1;
14879:                         }
14880:                         if ($domconfig{$action}{$itemid}{$extra.'valid'} ne $confhash{$itemid}{$extra.'valid'}) {
14881:                             $changes{$itemid} = 1;
14882:                         }
14883:                     }
14884:                     my @courseconfig = &Apache::loncommon::get_env_multiple('form.ltitools_courseconfig_'.$i);
14885:                     foreach my $item ('label','title','target','linktext','explanation','append') {
14886:                         if (grep(/^\Q$item\E$/,@courseconfig)) {
14887:                             $confhash{$itemid}{'crsconf'}{$item} = 1;
14888:                             if (ref($domconfig{$action}{$itemid}{'crsconf'}) eq 'HASH') {
14889:                                 if ($domconfig{$action}{$itemid}{'crsconf'}{$item} ne $confhash{$itemid}{'crsconf'}{$item}) {
14890:                                     $changes{$itemid} = 1;
14891:                                 }
14892:                             } else {
14893:                                 $changes{$itemid} = 1;
14894:                             }
14895:                         }
14896:                     }
14897:                     my @fields = &Apache::loncommon::get_env_multiple('form.ltitools_fields_'.$i);
14898:                     foreach my $field (@fields) {
14899:                         if ($possfield{$field}) {
14900:                             if ($field eq 'roles') {
14901:                                 foreach my $role (@courseroles) {
14902:                                     my $choice = $env{'form.ltitools_roles_'.$role.'_'.$i};
14903:                                     if (($choice ne '') && ($posslti{$choice})) {
14904:                                         $confhash{$itemid}{'roles'}{$role} = $choice;
14905:                                         if ($role eq 'cc') {
14906:                                             $confhash{$itemid}{'roles'}{'co'} = $choice;
14907:                                         }
14908:                                     }
14909:                                     if (ref($domconfig{$action}{$itemid}{'roles'}) eq 'HASH') {
14910:                                         if ($domconfig{$action}{$itemid}{'roles'}{$role} ne $confhash{$itemid}{'roles'}{$role}) {
14911:                                             $changes{$itemid} = 1;
14912:                                         }
14913:                                     } elsif ($confhash{$itemid}{'roles'}{$role}) {
14914:                                         $changes{$itemid} = 1;
14915:                                     }
14916:                                 }
14917:                             } else {
14918:                                 $confhash{$itemid}{'fields'}{$field} = 1;
14919:                                 if (ref($domconfig{$action}{$itemid}{'fields'}) eq 'HASH') {
14920:                                     if ($domconfig{$action}{$itemid}{'fields'}{$field} ne $confhash{$itemid}{'fields'}{$field}) {
14921:                                         $changes{$itemid} = 1;
14922:                                     }
14923:                                 } else {
14924:                                     $changes{$itemid} = 1;
14925:                                 }
14926:                             }
14927:                         }
14928:                     }
14929:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
14930:                         if ($confhash{$itemid}{'fields'}{'user'}) {
14931:                             if ($env{'form.ltitools_userincdom_'.$i}) {
14932:                                 $confhash{$itemid}{'incdom'} = 1;
14933:                             }
14934:                             if ($domconfig{$action}{$itemid}{'incdom'} ne $confhash{$itemid}{'incdom'}) {
14935:                                 $changes{$itemid} = 1;
14936:                             }
14937:                         }
14938:                     }
14939:                     $allpos[$newpos] = $itemid;
14940:                 }
14941:                 if ($imgdeletions{$itemid}) {
14942:                     $changes{$itemid} = 1;
14943:                     #FIXME need to obsolete item in RES space
14944:                 } elsif ($env{'form.ltitools_image_'.$i.'.filename'}) {
14945:                     my ($imgurl,$error) = &process_ltitools_image($r,$dom,$confname,'ltitools_image_'.$i,
14946:                                                                  $itemid,$configuserok,$switchserver,
14947:                                                                  $author_ok);
14948:                     if ($imgurl) {
14949:                         $confhash{$itemid}{'image'} = $imgurl;
14950:                         $changes{$itemid} = 1;
14951:                     }
14952:                     if ($error) {
14953:                         &Apache::lonnet::logthis($error);
14954:                         $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
14955:                     }
14956:                 } elsif ($domconfig{$action}{$itemid}{'image'}) {
14957:                     $confhash{$itemid}{'image'} =
14958:                        $domconfig{$action}{$itemid}{'image'};
14959:                 }
14960:                 if ($customadds{$i}) {
14961:                     my $name = $env{'form.ltitools_custom_name_'.$i};
14962:                     $name =~ s/(`)/'/g;
14963:                     $name =~ s/^\s+//;
14964:                     $name =~ s/\s+$//;
14965:                     my $value = $env{'form.ltitools_custom_value_'.$i};
14966:                     $value =~ s/(`)/'/g;
14967:                     $value =~ s/^\s+//;
14968:                     $value =~ s/\s+$//;
14969:                     if ($name ne '') {
14970:                         $confhash{$itemid}{'custom'}{$name} = $value;
14971:                         $changes{$itemid} = 1;
14972:                     }
14973:                 }
14974:                 my %customdels;
14975:                 my @customdeletions = &Apache::loncommon::get_env_multiple('form.ltitools_customdel_'.$i); 
14976:                 if (@customdeletions) {
14977:                     $changes{$itemid} = 1;
14978:                 }
14979:                 map { $customdels{$_} = 1; } @customdeletions;
14980:                 if (ref($domconfig{$action}{$itemid}{'custom'}) eq 'HASH') {
14981:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}{'custom'}})) {
14982:                         unless ($customdels{$key}) {
14983:                             if ($env{'form.ltitools_customval_'.$key.'_'.$i} ne '') {
14984:                                 $confhash{$itemid}{'custom'}{$key} = $env{'form.ltitools_customval_'.$key.'_'.$i}; 
14985:                             }
14986:                             if ($domconfig{$action}{$itemid}{'custom'}{$key} ne $env{'form.ltitools_customval_'.$key.'_'.$i}) {
14987:                                 $changes{$itemid} = 1;
14988:                             }
14989:                         }
14990:                     }
14991:                 }
14992:                 unless ($changes{$itemid}) {
14993:                     foreach my $key (keys(%{$domconfig{$action}{$itemid}})) {
14994:                         if (ref($domconfig{$action}{$itemid}{$key}) eq 'HASH') {
14995:                             if (ref($confhash{$itemid}{$key}) eq 'HASH') {
14996:                                 foreach my $innerkey (keys(%{$domconfig{$action}{$itemid}{$key}})) {
14997:                                     unless (exists($confhash{$itemid}{$key}{$innerkey})) {
14998:                                         $changes{$itemid} = 1;
14999:                                         last;
15000:                                     }
15001:                                 }
15002:                             } elsif (keys(%{$domconfig{$action}{$itemid}{$key}}) > 0) {
15003:                                 $changes{$itemid} = 1;
15004:                             }
15005:                         }
15006:                         last if ($changes{$itemid});
15007:                     }
15008:                 }
15009:             }
15010:         }
15011:     }
15012:     if (@allpos > 0) {
15013:         my $idx = 0;
15014:         foreach my $itemid (@allpos) {
15015:             if ($itemid ne '') {
15016:                 $confhash{$itemid}{'order'} = $idx;
15017:                 if (ref($domconfig{$action}) eq 'HASH') {
15018:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15019:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
15020:                             $changes{$itemid} = 1;
15021:                         }
15022:                     }
15023:                 }
15024:                 $idx ++;
15025:             }
15026:         }
15027:     }
15028:     my %ltitoolshash = (
15029:                           $action => { %confhash }
15030:                        );
15031:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltitoolshash,
15032:                                              $dom);
15033:     if ($putresult eq 'ok') {
15034:         my %ltienchash = (
15035:                              $action => { %encconfig }
15036:                          );
15037:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
15038:         if (keys(%changes) > 0) {
15039:             my $cachetime = 24*60*60;
15040:             my %ltiall = %confhash;
15041:             foreach my $id (keys(%ltiall)) {
15042:                 if (ref($encconfig{$id}) eq 'HASH') {
15043:                     foreach my $item ('key','secret') {
15044:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
15045:                     }
15046:                 }
15047:             }
15048:             &Apache::lonnet::do_cache_new('ltitools',$dom,\%ltiall,$cachetime);
15049:             if (ref($lastactref) eq 'HASH') {
15050:                 $lastactref->{'ltitools'} = 1;
15051:             }
15052:             $resulttext = &mt('Changes made:').'<ul>';
15053:             my %bynum;
15054:             foreach my $itemid (sort(keys(%changes))) {
15055:                 my $position = $confhash{$itemid}{'order'};
15056:                 $bynum{$position} = $itemid;
15057:             }
15058:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15059:                 my $itemid = $bynum{$pos}; 
15060:                 if (ref($confhash{$itemid}) ne 'HASH') {
15061:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
15062:                 } else {
15063:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'title'}.'</b>';
15064:                     if ($confhash{$itemid}{'image'}) {
15065:                         $resulttext .= '&nbsp;'.
15066:                                        '<img src="'.$confhash{$itemid}{'image'}.'"'.
15067:                                        ' alt="'.&mt('Tool Provider icon').'" />';
15068:                     }
15069:                     $resulttext .= '</li><ul>';
15070:                     my $position = $pos + 1;
15071:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15072:                     foreach my $item ('version','msgtype','sigmethod','url','lifetime') {
15073:                         if ($confhash{$itemid}{$item} ne '') {
15074:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
15075:                         }
15076:                     }
15077:                     if ($encconfig{$itemid}{'key'} ne '') {
15078:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
15079:                     }
15080:                     if ($encconfig{$itemid}{'secret'} ne '') {
15081:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15082:                         my $num = length($encconfig{$itemid}{'secret'});
15083:                         $resulttext .= ('*'x$num).'</li>';
15084:                     }
15085:                     $resulttext .= '<li>'.&mt('Configurable in course:');
15086:                     my @possconfig = ('label','title','target','linktext','explanation','append');
15087:                     my $numconfig = 0; 
15088:                     if (ref($confhash{$itemid}{'crsconf'}) eq 'HASH') { 
15089:                         foreach my $item (@possconfig) {
15090:                             if ($confhash{$itemid}{'crsconf'}{$item}) {
15091:                                 $numconfig ++;
15092:                                 $resulttext .= ' "'.$lt{'crs'.$item}.'"';
15093:                             }
15094:                         }
15095:                     }
15096:                     if (!$numconfig) {
15097:                         $resulttext .= '&nbsp;'.&mt('None');
15098:                     }
15099:                     $resulttext .= '</li>';
15100:                     foreach my $item ('passback','roster') {
15101:                         $resulttext .= '<li>'.$lt{$item}.'&nbsp;';
15102:                         if ($confhash{$itemid}{$item}) {
15103:                             $resulttext .= &mt('Yes');
15104:                             if ($confhash{$itemid}{$item.'valid'}) {
15105:                                 if ($item eq 'passback') {
15106:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,day] after launch',
15107:                                                            $confhash{$itemid}{$item.'valid'});
15108:                                 } else {
15109:                                     $resulttext .= ' '.&mt('valid for at least [quant,_1,second] after launch',
15110:                                                            $confhash{$itemid}{$item.'valid'});
15111:                                 }
15112:                             }
15113:                         } else {
15114:                             $resulttext .= &mt('No');
15115:                         }
15116:                         $resulttext .= '</li>';
15117:                     }
15118:                     if (ref($confhash{$itemid}{'display'}) eq 'HASH') {
15119:                         my $displaylist;
15120:                         if ($confhash{$itemid}{'display'}{'target'}) {
15121:                             $displaylist = &mt('Display target').':&nbsp;'.
15122:                                            $confhash{$itemid}{'display'}{'target'}.',';
15123:                         }
15124:                         foreach my $size ('width','height') { 
15125:                             if ($confhash{$itemid}{'display'}{$size}) {
15126:                                 $displaylist .= ('&nbsp;'x2).$lt{$size}.':&nbsp;'.
15127:                                                 $confhash{$itemid}{'display'}{$size}.',';
15128:                             }
15129:                         }
15130:                         if ($displaylist) {
15131:                             $displaylist =~ s/,$//;
15132:                             $resulttext .= '<li>'.$displaylist.'</li>';
15133:                         }
15134:                         foreach my $item ('linktext','explanation') {
15135:                             if ($confhash{$itemid}{'display'}{$item}) {
15136:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{'display'}{$item}.'</li>';
15137:                             }
15138:                         }
15139:                     }
15140:                     if (ref($confhash{$itemid}{'fields'}) eq 'HASH') {
15141:                         my $fieldlist;
15142:                         foreach my $field (@allfields) {
15143:                             if ($confhash{$itemid}{'fields'}{$field}) {
15144:                                 $fieldlist .= ('&nbsp;'x2).$lt{$field}.',';
15145:                             }
15146:                         }
15147:                         if ($fieldlist) {
15148:                             $fieldlist =~ s/,$//;
15149:                             if ($confhash{$itemid}{'fields'}{'user'}) {
15150:                                 if ($confhash{$itemid}{'incdom'}) {
15151:                                     $fieldlist .= ' ('.&mt('username:domain').')';
15152:                                 } else {
15153:                                     $fieldlist .= ' ('.&mt('username').')';
15154:                                 }
15155:                             }
15156:                             $resulttext .= '<li>'.&mt('Data sent').':'.$fieldlist.'</li>';
15157:                         }
15158:                     }
15159:                     if (ref($confhash{$itemid}{'roles'}) eq 'HASH') {
15160:                         my $rolemaps;
15161:                         foreach my $role (@courseroles) {
15162:                             if ($confhash{$itemid}{'roles'}{$role}) {
15163:                                 $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15164:                                              $confhash{$itemid}{'roles'}{$role}.',';
15165:                             }
15166:                         }
15167:                         if ($rolemaps) {
15168:                             $rolemaps =~ s/,$//; 
15169:                             $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15170:                         }
15171:                     }
15172:                     if (ref($confhash{$itemid}{'custom'}) eq 'HASH') {
15173:                         my $customlist;
15174:                         if (keys(%{$confhash{$itemid}{'custom'}})) {
15175:                             foreach my $key (sort(keys(%{$confhash{$itemid}{'custom'}}))) {
15176:                                 $customlist .= $key.':'.$confhash{$itemid}{'custom'}{$key}.('&nbsp;'x2);
15177:                             } 
15178:                         }
15179:                         if ($customlist) {
15180:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15181:                         }
15182:                     } 
15183:                     $resulttext .= '</ul></li>';
15184:                 }
15185:             }
15186:             $resulttext .= '</ul>';
15187:         } else {
15188:             $resulttext = &mt('No changes made.');
15189:         }
15190:     } else {
15191:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15192:     }
15193:     if ($errors) {
15194:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15195:                        $errors.'</ul>';
15196:     }
15197:     return $resulttext;
15198: }
15199: 
15200: sub process_ltitools_image {
15201:     my ($r,$dom,$confname,$caller,$itemid,$configuserok,$switchserver,$author_ok) = @_;
15202:     my $filename = $env{'form.'.$caller.'.filename'};
15203:     my ($error,$url);
15204:     my ($width,$height) = (21,21);
15205:     if ($configuserok eq 'ok') {
15206:         if ($switchserver) {
15207:             $error = &mt('Upload of Tool Provider (LTI) icon is not permitted to this server: [_1]',
15208:                          $switchserver);
15209:         } elsif ($author_ok eq 'ok') {
15210:             my ($result,$imageurl,$madethumb) =
15211:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15212:                              "ltitools/$itemid/icon",$width,$height);
15213:             if ($result eq 'ok') {
15214:                 if ($madethumb) {
15215:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15216:                     my $imagethumb = "$path/tn-".$imagefile;
15217:                     $url = $imagethumb;
15218:                 } else {
15219:                     $url = $imageurl;
15220:                 }
15221:             } else {
15222:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15223:             }
15224:         } else {
15225:             $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);
15226:         }
15227:     } else {
15228:         $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);
15229:     }
15230:     return ($url,$error);
15231: }
15232: 
15233: sub get_ltitools_id {
15234:     my ($cdom,$title) = @_;
15235:     # get lock on ltitools db
15236:     my $lockhash = {
15237:                       lock => $env{'user.name'}.
15238:                               ':'.$env{'user.domain'},
15239:                    };
15240:     my $tries = 0;
15241:     my $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15242:     my ($id,$error);
15243:  
15244:     while (($gotlock ne 'ok') && ($tries<10)) {
15245:         $tries ++;
15246:         sleep (0.1);
15247:         $gotlock = &Apache::lonnet::newput_dom('ltitools',$lockhash,$cdom);
15248:     }
15249:     if ($gotlock eq 'ok') {
15250:         my %currids = &Apache::lonnet::dump_dom('ltitools',$cdom);
15251:         if ($currids{'lock'}) {
15252:             delete($currids{'lock'});
15253:             if (keys(%currids)) {
15254:                 my @curr = sort { $a <=> $b } keys(%currids);
15255:                 if ($curr[-1] =~ /^\d+$/) {
15256:                     $id = 1 + $curr[-1];
15257:                 }
15258:             } else {
15259:                 $id = 1;
15260:             }
15261:             if ($id) {
15262:                 unless (&Apache::lonnet::newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
15263:                     $error = 'nostore';
15264:                 }
15265:             } else {
15266:                 $error = 'nonumber';
15267:             }
15268:         }
15269:         my $dellockoutcome = &Apache::lonnet::del_dom('ltitools',['lock'],$cdom);
15270:     } else {
15271:         $error = 'nolock';
15272:     }
15273:     return ($id,$error);
15274: }
15275: 
15276: sub modify_proctoring {
15277:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15278:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15279:     my (@allpos,%changes,%confhash,%encconfhash,$errors,$resulttext,%imgdeletions);
15280:     my $confname = $dom.'-domainconfig';
15281:     my $servadm = $r->dir_config('lonAdmEMail');
15282:     my ($configuserok,$author_ok,$switchserver) = &config_check($dom,$confname,$servadm);
15283:     my %providernames = &proctoring_providernames();
15284:     my $maxnum = scalar(keys(%providernames));
15285: 
15286:     my (%requserfields,%optuserfields,%defaults,%extended,%crsconf,@courseroles,@ltiroles);
15287:     my ($requref,$opturef,$defref,$extref,$crsref,$rolesref,$ltiref) = &proctoring_data();
15288:     if (ref($requref) eq 'HASH') {
15289:         %requserfields = %{$requref};
15290:     }
15291:     if (ref($opturef) eq 'HASH') {
15292:         %optuserfields = %{$opturef};
15293:     }
15294:     if (ref($defref) eq 'HASH') {
15295:         %defaults = %{$defref};
15296:     }
15297:     if (ref($extref) eq 'HASH') {
15298:         %extended = %{$extref};
15299:     }
15300:     if (ref($crsref) eq 'HASH') {
15301:         %crsconf = %{$crsref};
15302:     }
15303:     if (ref($rolesref) eq 'ARRAY') {
15304:         @courseroles = @{$rolesref};
15305:     }
15306:     if (ref($ltiref) eq 'ARRAY') {
15307:         @ltiroles = @{$ltiref};
15308:     }
15309: 
15310:     if (ref($domconfig{$action}) eq 'HASH') {
15311:         my @todeleteimages = &Apache::loncommon::get_env_multiple('form.proctoring_image_del');
15312:         if (@todeleteimages) {
15313:             map { $imgdeletions{$_} = 1; } @todeleteimages;
15314:         }
15315:     }
15316:     my %customadds;
15317:     my @newcustom = &Apache::loncommon::get_env_multiple('form.proctoring_customadd');
15318:     if (@newcustom) {
15319:         map { $customadds{$_} = 1; } @newcustom;
15320:     }
15321:     foreach my $provider (sort(keys(%providernames))) {
15322:         $confhash{$provider} = {};
15323:         my $pos = $env{'form.proctoring_pos_'.$provider};
15324:         $pos =~ s/\D+//g;
15325:         $allpos[$pos] = $provider;
15326:         my (%current,%currentenc);
15327:         my $showroles = 0;
15328:         if (ref($domconfig{$action}) eq 'HASH') {
15329:             if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15330:                 %current = %{$domconfig{$action}{$provider}};
15331:                 foreach my $item ('key','secret') { 
15332:                     $currentenc{$item} = $current{$item};
15333:                     delete($current{$item});
15334:                 }
15335:             }
15336:         }
15337:         if ($env{'form.proctoring_available_'.$provider}) {
15338:             $confhash{$provider}{'available'} = 1;
15339:             unless ($current{'available'}) {
15340:                 $changes{$provider} = 1;
15341:             }
15342:         } else {
15343:             %{$confhash{$provider}} = %current;
15344:             %{$encconfhash{$provider}} = %currentenc;
15345:             $confhash{$provider}{'available'} = 0;
15346:             if ($current{'available'}) {
15347:                 $changes{$provider} = 1;
15348:             }
15349:         }
15350:         if ($confhash{$provider}{'available'}) {
15351:             foreach my $field ('lifetime','version','sigmethod','url','key','secret') {
15352:                 my $possval = $env{'form.proctoring_'.$provider.'_'.$field};
15353:                 if ($field eq 'lifetime') {
15354:                     if ($possval =~ /^\d+$/) {
15355:                         $confhash{$provider}{$field} = $possval;
15356:                     }
15357:                 } elsif ($field eq 'version') {
15358:                     if ($possval =~ /^\d+\.\d+$/) {
15359:                         $confhash{$provider}{$field} = $possval;
15360:                     }
15361:                 } elsif ($field eq 'sigmethod') {
15362:                     if ($possval =~ /^\QHMAC-SHA\E(1|256)$/) {
15363:                         $confhash{$provider}{$field} = $possval;
15364:                     }
15365:                 } elsif ($field eq 'url') {
15366:                     $confhash{$provider}{$field} = $possval;
15367:                 } elsif (($field eq 'key') || ($field eq 'secret')) {
15368:                     $encconfhash{$provider}{$field} = $possval;
15369:                     unless ($currentenc{$field} eq $possval) {
15370:                         $changes{$provider} = 1;
15371:                     }
15372:                 }
15373:                 unless (($field eq 'key') || ($field eq 'secret')) {
15374:                     unless ($current{$field} eq $confhash{$provider}{$field}) {
15375:                         $changes{$provider} = 1;
15376:                     }
15377:                 }
15378:             }
15379:             if ($imgdeletions{$provider}) {
15380:                 $changes{$provider} = 1;
15381:             } elsif ($env{'form.proctoring_image_'.$provider.'.filename'} ne '') {
15382:                 my ($imageurl,$error) =
15383:                     &process_proctoring_image($r,$dom,$confname,'proctoring_image_'.$provider,$provider,
15384:                                               $configuserok,$switchserver,$author_ok);
15385:                 if ($imageurl) {
15386:                     $confhash{$provider}{'image'} = $imageurl;
15387:                     $changes{$provider} = 1; 
15388:                 }
15389:                 if ($error) {
15390:                     &Apache::lonnet::logthis($error);
15391:                     $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15392:                 }
15393:             } elsif (exists($current{'image'})) {
15394:                 $confhash{$provider}{'image'} = $current{'image'};
15395:             }
15396:             if (ref($requserfields{$provider}) eq 'ARRAY') {
15397:                 if (@{$requserfields{$provider}} > 0) {
15398:                     if (grep(/^user$/,@{$requserfields{$provider}})) {
15399:                         if ($env{'form.proctoring_userincdom_'.$provider}) {
15400:                             $confhash{$provider}{'incdom'} = 1;
15401:                         }
15402:                         unless ($current{'incdom'} eq $confhash{$provider}{'incdom'}) {
15403:                             $changes{$provider} = 1;
15404:                         }
15405:                     }
15406:                     if (grep(/^roles$/,@{$requserfields{$provider}})) {
15407:                         $showroles = 1;
15408:                     }
15409:                 }
15410:             }
15411:             $confhash{$provider}{'fields'} = [];
15412:             if (ref($optuserfields{$provider}) eq 'ARRAY') {
15413:                 if (@{$optuserfields{$provider}} > 0) {
15414:                     my @optfields = &Apache::loncommon::get_env_multiple('form.proctoring_optional_'.$provider);
15415:                     foreach my $field (@{$optuserfields{$provider}}) {
15416:                         if (grep(/^\Q$field\E$/,@optfields)) {
15417:                             push(@{$confhash{$provider}{'fields'}},$field);
15418:                         }
15419:                     }
15420:                 }
15421:                 if (ref($current{'fields'}) eq 'ARRAY') {
15422:                     unless ($changes{$provider}) {
15423:                         my @new = sort(@{$confhash{$provider}{'fields'}});
15424:                         my @old = sort(@{$current{'fields'}}); 
15425:                         my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15426:                         if (@diffs) {
15427:                             $changes{$provider} = 1;
15428:                         }
15429:                     }
15430:                 } elsif (@{$confhash{$provider}{'fields'}}) {
15431:                     $changes{$provider} = 1;
15432:                 }
15433:             }
15434:             if (ref($defaults{$provider}) eq 'ARRAY') {  
15435:                 if (@{$defaults{$provider}} > 0) {
15436:                     my %options;
15437:                     if (ref($extended{$provider}) eq 'HASH') {
15438:                         %options = %{$extended{$provider}};
15439:                     }
15440:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_defaults_'.$provider);
15441:                     foreach my $field (@{$defaults{$provider}}) {
15442:                         if ((exists($options{$field})) && (ref($options{$field}) eq 'ARRAY')) {
15443:                             my $poss = $env{'form.proctoring_defaults_'.$field.'_'.$provider};
15444:                             if (grep(/^\Q$poss\E$/,@{$options{$field}})) {
15445:                                 push(@{$confhash{$provider}{'defaults'}},$poss); 
15446:                             }
15447:                         } elsif ((exists($options{$field})) && (ref($options{$field}) eq 'HASH')) {
15448:                             foreach my $inner (keys(%{$options{$field}})) {
15449:                                 if (ref($options{$field}{$inner}) eq 'ARRAY') {
15450:                                     my $poss = $env{'form.proctoring_'.$inner.'_'.$provider};
15451:                                     if (grep(/^\Q$poss\E$/,@{$options{$field}{$inner}})) {
15452:                                         $confhash{$provider}{'defaults'}{$inner} = $poss;
15453:                                     }
15454:                                 } else {
15455:                                     $confhash{$provider}{'defaults'}{$inner} = $env{'form.proctoring_'.$inner.'_'.$provider};
15456:                                 }
15457:                             }
15458:                         } else {
15459:                             if (grep(/^\Q$field\E$/,@checked)) {
15460:                                 push(@{$confhash{$provider}{'defaults'}},$field);
15461:                             }
15462:                         }
15463:                     }
15464:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15465:                         if (ref($current{'defaults'}) eq 'ARRAY') {
15466:                             unless ($changes{$provider}) {
15467:                                 my @new = sort(@{$confhash{$provider}{'defaults'}});
15468:                                 my @old = sort(@{$current{'defaults'}});
15469:                                 my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15470:                                 if (@diffs) {
15471:                                     $changes{$provider} = 1; 
15472:                                 }
15473:                             }
15474:                         } elsif (ref($current{'defaults'}) eq 'ARRAY') {
15475:                             if (@{$current{'defaults'}}) {
15476:                                 $changes{$provider} = 1;
15477:                             }
15478:                         }
15479:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15480:                         if (ref($current{'defaults'}) eq 'HASH') {
15481:                             unless ($changes{$provider}) {
15482:                                 foreach my $key (keys(%{$confhash{$provider}{'defaults'}})) {
15483:                                     unless ($confhash{$provider}{'defaults'}{$key} eq $current{'defaults'}{$key}) {
15484:                                         $changes{$provider} = 1;
15485:                                         last;
15486:                                     }
15487:                                 }
15488:                             }
15489:                             unless ($changes{$provider}) {
15490:                                 foreach my $key (keys(%{$current{'defaults'}})) {
15491:                                     unless ($current{'defaults'}{$key} eq $confhash{$provider}{'defaults'}{$key}) {
15492:                                         $changes{$provider} = 1;
15493:                                         last;
15494:                                     }
15495:                                 }
15496:                             }
15497:                         } elsif (keys(%{$confhash{$provider}{'defaults'}})) {
15498:                             $changes{$provider} = 1;
15499:                         }
15500:                     }
15501:                 }
15502:             }
15503:             if (ref($crsconf{$provider}) eq 'ARRAY') {
15504:                 if (@{$crsconf{$provider}} > 0) {
15505:                     $confhash{$provider}{'crsconf'} = [];
15506:                     my @checked = &Apache::loncommon::get_env_multiple('form.proctoring_crsconf_'.$provider);
15507:                     foreach my $crsfield (@{$crsconf{$provider}}) {
15508:                         if (grep(/^\Q$crsfield\E$/,@checked)) {
15509:                             push(@{$confhash{$provider}{'crsconf'}},$crsfield);
15510:                         }
15511:                     }
15512:                     if (ref($current{'crsconf'}) eq 'ARRAY') {
15513:                         unless ($changes{$provider}) {  
15514:                             my @new = sort(@{$confhash{$provider}{'crsconf'}});
15515:                             my @old = sort(@{$current{'crsconf'}});
15516:                             my @diffs = &Apache::loncommon::compare_arrays(\@new,\@old);
15517:                             if (@diffs) {
15518:                                 $changes{$provider} = 1;
15519:                             }
15520:                         }
15521:                     } elsif (@{$confhash{$provider}{'crsconf'}}) {
15522:                         $changes{$provider} = 1;
15523:                     }
15524:                 }
15525:             }
15526:             if ($showroles) {
15527:                 $confhash{$provider}{'roles'} = {};
15528:                 foreach my $role (@courseroles) {
15529:                     my $poss = $env{'form.proctoring_roles_'.$role.'_'.$provider};
15530:                     if (grep(/^\Q$poss\E$/,@ltiroles)) {
15531:                         $confhash{$provider}{'roles'}{$role} = $poss;
15532:                     }
15533:                 }
15534:                 unless ($changes{$provider}) {
15535:                     if (ref($current{'roles'}) eq 'HASH') {
15536:                         foreach my $role (keys(%{$current{'roles'}})) {
15537:                             unless ($current{'roles'}{$role} eq $confhash{$provider}{'roles'}{$role}) {
15538:                                 $changes{$provider} = 1;
15539:                                 last
15540:                             }
15541:                         }
15542:                         unless ($changes{$provider}) {
15543:                             foreach my $role (keys(%{$confhash{$provider}{'roles'}})) {
15544:                                 unless ($confhash{$provider}{'roles'}{$role} eq $current{'roles'}{$role}) {
15545:                                     $changes{$provider} = 1;
15546:                                     last;
15547:                                 }
15548:                             }
15549:                         }
15550:                     } elsif (keys(%{$confhash{$provider}{'roles'}})) {
15551:                         $changes{$provider} = 1;
15552:                     }
15553:                 }
15554:             }
15555:             if (ref($current{'custom'}) eq 'HASH') {
15556:                 my @customdels = &Apache::loncommon::get_env_multiple('form.proctoring_customdel_'.$provider);
15557:                 foreach my $key (keys(%{$current{'custom'}})) {
15558:                     if (grep(/^\Q$key\E$/,@customdels)) {
15559:                         $changes{$provider} = 1;
15560:                     } else {
15561:                         $confhash{$provider}{'custom'}{$key} = $env{'form.proctoring_customval_'.$key.'_'.$provider};
15562:                         if ($confhash{$provider}{'custom'}{$key} ne $current{'custom'}{$key}) {
15563:                             $changes{$provider} = 1;
15564:                         }
15565:                     }
15566:                 }
15567:             }
15568:             if ($customadds{$provider}) {
15569:                 my $name = $env{'form.proctoring_custom_name_'.$provider};
15570:                 $name =~ s/(`)/'/g;
15571:                 $name =~ s/^\s+//;
15572:                 $name =~ s/\s+$//;
15573:                 my $value = $env{'form.proctoring_custom_value_'.$provider};
15574:                 $value =~ s/(`)/'/g;
15575:                 $value =~ s/^\s+//;
15576:                 $value =~ s/\s+$//;
15577:                 if ($name ne '') {
15578:                     $confhash{$provider}{'custom'}{$name} = $value;
15579:                     $changes{$provider} = 1;
15580:                 }
15581:             }
15582:         }
15583:     }
15584:     if (@allpos > 0) {
15585:         my $idx = 0;
15586:         foreach my $provider (@allpos) {
15587:             if ($provider ne '') {
15588:                 $confhash{$provider}{'order'} = $idx;
15589:                 unless ($changes{$provider}) {
15590:                     if (ref($domconfig{$action}) eq 'HASH') {
15591:                         if (ref($domconfig{$action}{$provider}) eq 'HASH') {
15592:                             if ($domconfig{$action}{$provider}{'order'} ne $idx) {
15593:                                 $changes{$provider} = 1;
15594:                             }
15595:                         }
15596:                     }
15597:                 }
15598:                 $idx ++;
15599:             }
15600:         }
15601:     }
15602:     my %proc_hash = (
15603:                           $action => { %confhash }
15604:                        );
15605:     my $putresult = &Apache::lonnet::put_dom('configuration',\%proc_hash,
15606:                                              $dom);
15607:     if ($putresult eq 'ok') {
15608:         my %proc_enchash = (
15609:                              $action => { %encconfhash }
15610:                          );
15611:         &Apache::lonnet::put_dom('encconfig',\%proc_enchash,$dom,undef,1);
15612:         if (keys(%changes) > 0) {
15613:             my $cachetime = 24*60*60;
15614:             my %procall = %confhash;
15615:             foreach my $provider (keys(%procall)) {
15616:                 if (ref($encconfhash{$provider}) eq 'HASH') {
15617:                     foreach my $key ('key','secret') {
15618:                         $procall{$provider}{$key} = $encconfhash{$provider}{$key};
15619:                     }
15620:                 }
15621:             }
15622:             &Apache::lonnet::do_cache_new('proctoring',$dom,\%procall,$cachetime);
15623:             if (ref($lastactref) eq 'HASH') {
15624:                 $lastactref->{'proctoring'} = 1;
15625:             }
15626:             $resulttext = &mt('Configuration for Provider(s) with changes:').'<ul>';
15627:             my %bynum;
15628:             foreach my $provider (sort(keys(%changes))) {
15629:                 my $position = $confhash{$provider}{'order'};
15630:                 $bynum{$position} = $provider;
15631:             }
15632:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
15633:                 my $provider = $bynum{$pos};
15634:                 my %lt = &proctoring_titles($provider);
15635:                 my %fieldtitles = &proctoring_fieldtitles($provider);
15636:                 if (!$confhash{$provider}{'available'}) {
15637:                     $resulttext .= '<li>'.&mt('Proctoring integration unavailable for: [_1]','<b>'.$providernames{$provider}.'</b>').'</li>';
15638:                 } else {
15639:                     $resulttext .= '<li>'.&mt('Proctoring integration available for: [_1]','<b>'.$providernames{$provider}.'</b>');
15640:                     if ($confhash{$provider}{'image'}) {
15641:                         $resulttext .= '&nbsp;'.
15642:                                        '<img src="'.$confhash{$provider}{'image'}.'"'.
15643:                                        ' alt="'.&mt('Proctoring icon').'" />';
15644:                     }
15645:                     $resulttext .= '<ul>';
15646:                     my $position = $pos + 1;
15647:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
15648:                     foreach my $key ('version','sigmethod','url','lifetime') {
15649:                         if ($confhash{$provider}{$key} ne '') {
15650:                             $resulttext .= '<li>'.$lt{$key}.':&nbsp;'.$confhash{$provider}{$key}.'</li>';
15651:                         }
15652:                     }
15653:                     if ($encconfhash{$provider}{'key'} ne '') {
15654:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfhash{$provider}{'key'}.'</li>';
15655:                     }
15656:                     if ($encconfhash{$provider}{'secret'} ne '') {
15657:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
15658:                         my $num = length($encconfhash{$provider}{'secret'});
15659:                         $resulttext .= ('*'x$num).'</li>';
15660:                     }
15661:                     my (@fields,$showroles);
15662:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15663:                         push(@fields,@{$requserfields{$provider}});
15664:                     }
15665:                     if (ref($confhash{$provider}{'fields'}) eq 'ARRAY') {
15666:                         push(@fields,@{$confhash{$provider}{'fields'}});
15667:                     } elsif (ref($confhash{$provider}{'fields'}) eq 'HASH') {
15668:                         push(@fields,(keys(%{$confhash{$provider}{'fields'}})));
15669:                     }
15670:                     if (@fields) {
15671:                         if (grep(/^roles$/,@fields)) {
15672:                             $showroles = 1;
15673:                         }
15674:                         $resulttext .= '<li>'.$lt{'udsl'}.':&nbsp;"'.
15675:                                        join('", "', map { $lt{$_}; } @fields).'"</li>';
15676:                     }
15677:                     if (ref($requserfields{$provider}) eq 'ARRAY') {
15678:                         if (grep(/^user$/,@{$requserfields{$provider}})) {
15679:                             if ($confhash{$provider}{'incdom'}) {
15680:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'uname:dom'}).'</li>';
15681:                             } else { 
15682:                                 $resulttext .= '<li>'.&mt('[_1] sent as [_2]',$lt{'user'},$lt{'username'}).'</li>';
15683:                             }
15684:                         }
15685:                     }
15686:                     if (ref($confhash{$provider}{'defaults'}) eq 'ARRAY') {
15687:                         if (@{$confhash{$provider}{'defaults'}} > 0) {
15688:                             $resulttext .= '<li>'.$lt{'defa'};
15689:                             foreach my $field (@{$confhash{$provider}{'defaults'}}) {
15690:                                 $resulttext .= ' "'.$fieldtitles{$field}.'",';
15691:                             }
15692:                             $resulttext =~ s/,$//;
15693:                             $resulttext .= '</li>';
15694:                         }
15695:                     } elsif (ref($confhash{$provider}{'defaults'}) eq 'HASH') {
15696:                         if (keys(%{$confhash{$provider}{'defaults'}})) {
15697:                             $resulttext .= '<li>'.$lt{'defa'}.':&nbsp;<ul>';
15698:                             foreach my $key (sort(keys(%{$confhash{$provider}{'defaults'}}))) {
15699:                                 if ($confhash{$provider}{'defaults'}{$key} ne '') {
15700:                                     $resulttext .= '<li>'.$fieldtitles{$key}.' = '.$confhash{$provider}{'defaults'}{$key}.'</li>';
15701:                                 }
15702:                             }
15703:                             $resulttext .= '</ul></li>';
15704:                         }
15705:                     }
15706:                     if (ref($crsconf{$provider}) eq 'ARRAY') {
15707:                         if (@{$crsconf{$provider}} > 0) {
15708:                             $resulttext .= '<li>'.&mt('Configurable in course:');
15709:                             my $numconfig = 0;
15710:                             if (ref($confhash{$provider}{'crsconf'}) eq 'ARRAY') {
15711:                                 if (@{$confhash{$provider}{'crsconf'}} > 0) {
15712:                                     foreach my $field (@{$confhash{$provider}{'crsconf'}}) {
15713:                                         $numconfig ++;
15714:                                         if ($provider eq 'examity') {
15715:                                             $resulttext .= ' "'.$lt{'crs'.$field}.'",';
15716:                                         } else {
15717:                                             $resulttext .= ' "'.$fieldtitles{$field}.'",';
15718:                                         }
15719:                                     }
15720:                                     $resulttext =~ s/,$//;
15721:                                 }
15722:                             }
15723:                             if (!$numconfig) {
15724:                                 $resulttext .= '&nbsp;'.&mt('None');
15725:                             }
15726:                             $resulttext .= '</li>';
15727:                         }
15728:                     }
15729:                     if ($showroles) {
15730:                         if (ref($confhash{$provider}{'roles'}) eq 'HASH') {
15731:                             my $rolemaps;
15732:                             foreach my $role (@courseroles) {
15733:                                 if ($confhash{$provider}{'roles'}{$role}) {
15734:                                     $rolemaps .= ('&nbsp;'x2).&Apache::lonnet::plaintext($role,'Course').'='.
15735:                                                  $confhash{$provider}{'roles'}{$role}.',';
15736:                                 }
15737:                             }
15738:                             if ($rolemaps) {
15739:                                 $rolemaps =~ s/,$//;
15740:                                 $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
15741:                             }
15742:                         }
15743:                     }
15744:                     if (ref($confhash{$provider}{'custom'}) eq 'HASH') {
15745:                         my $customlist;
15746:                         if (keys(%{$confhash{$provider}{'custom'}})) {
15747:                             foreach my $key (sort(keys(%{$confhash{$provider}{'custom'}}))) {
15748:                                 $customlist .= $key.'='.$confhash{$provider}{'custom'}{$key}.', ';
15749:                             }
15750:                             $customlist =~ s/,$//;
15751:                         }
15752:                         if ($customlist) {
15753:                             $resulttext .= '<li>'.&mt('Custom items').': '.$customlist.'</li>';
15754:                         }
15755:                     } 
15756:                     $resulttext .= '</ul></li>';
15757:                 }
15758:             }
15759:             $resulttext .= '</ul>';
15760:         } else {
15761:             $resulttext = &mt('No changes made.');
15762:         }
15763:     } else {
15764:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
15765:     }
15766:     if ($errors) {
15767:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
15768:                        $errors.'</ul>';
15769:     }
15770:     return $resulttext;
15771: }
15772: 
15773: sub process_proctoring_image {
15774:     my ($r,$dom,$confname,$caller,$provider,$configuserok,$switchserver,$author_ok) = @_;
15775:     my $filename = $env{'form.'.$caller.'.filename'};
15776:     my ($error,$url);
15777:     my ($width,$height) = (21,21);
15778:     if ($configuserok eq 'ok') {
15779:         if ($switchserver) {
15780:             $error = &mt('Upload of Remote Proctoring Provider icon is not permitted to this server: [_1]',
15781:                          $switchserver);
15782:         } elsif ($author_ok eq 'ok') {
15783:             my ($result,$imageurl,$madethumb) =
15784:                 &publishlogo($r,'upload',$caller,$dom,$confname,
15785:                              "proctoring/$provider/icon",$width,$height);
15786:             if ($result eq 'ok') {
15787:                 if ($madethumb) {
15788:                     my ($path,$imagefile) = ($imageurl =~ m{^(.+)/([^/]+)$});
15789:                     my $imagethumb = "$path/tn-".$imagefile;
15790:                     $url = $imagethumb;
15791:                 } else {
15792:                     $url = $imageurl;
15793:                 }
15794:             } else {
15795:                 $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$filename,$result);
15796:             }
15797:         } else {
15798:             $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);
15799:         }
15800:     } else {
15801:         $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);
15802:     }
15803:     return ($url,$error);
15804: }
15805: 
15806: sub modify_lti {
15807:     my ($r,$dom,$action,$lastactref,%domconfig) = @_;
15808:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
15809:     my ($newid,@allpos,%changes,%confhash,%encconfig,$errors,$resulttext);
15810:     my (%posslti,%posslticrs,%posscrstype);
15811:     my @courseroles = ('cc','in','ta','ep','st');
15812:     my @ltiroles = qw(Learner Instructor ContentDeveloper TeachingAssistant Mentor Member Manager Administrator);
15813:     my @lticourseroles = qw(Instructor TeachingAssistant Mentor Learner);
15814:     my @coursetypes = ('official','unofficial','community','textbook','placement','lti');
15815:     my %coursetypetitles = &Apache::lonlocal::texthash (
15816:                                official   => 'Official',
15817:                                unofficial => 'Unofficial',
15818:                                community  => 'Community',
15819:                                textbook   => 'Textbook',
15820:                                placement  => 'Placement Test',
15821:                                lti        => 'LTI Provider',
15822:     );
15823:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
15824:     my %lt = &lti_names();
15825:     map { $posslti{$_} = 1; } @ltiroles;
15826:     map { $posslticrs{$_} = 1; } @lticourseroles;
15827:     map { $posscrstype{$_} = 1; } @coursetypes;
15828: 
15829:     my %menutitles = &ltimenu_titles();
15830: 
15831:     my (%currltisec,%secchanges,%newltisec,%keyset,%newkeyset);
15832:     $newltisec{'private'}{'keys'} = [];
15833:     $newltisec{'encrypt'} = {};
15834:     $newltisec{'rules'} = {};
15835:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
15836:         %currltisec = %{$domconfig{'ltisec'}};
15837:         if (ref($currltisec{'private'}) eq 'HASH') {
15838:             if (ref($currltisec{'private'}{'keys'}) eq 'ARRAY') {
15839:                 $newltisec{'private'}{'keys'} = $currltisec{'private'}{'keys'};
15840:                 map { $keyset{$_} = 1; } @{$currltisec{'private'}{'keys'}};
15841:             }
15842:         }
15843:     }
15844:     foreach my $item ('crs','dom','consumers') {
15845:         my $formelement;
15846:         if ($item eq 'consumers') { 
15847:             $formelement = 'form.ltisec_'.$item;
15848:         } else {
15849:             $formelement = 'form.ltisec_'.$item.'linkprot';
15850:         }
15851:         if ($env{$formelement}) {
15852:             $newltisec{'encrypt'}{$item} = 1;
15853:             if (ref($currltisec{'encrypt'}) eq 'HASH') {
15854:                 unless ($currltisec{'encrypt'}{$item}) {
15855:                     $secchanges{'encrypt'} = 1;
15856:                 }
15857:             } else {
15858:                 $secchanges{'encrypt'} = 1;
15859:             }
15860:         } elsif (ref($currltisec{'encrypt'}) eq 'HASH') {
15861:             if ($currltisec{'encrypt'}{$item}) {
15862:                 $secchanges{'encrypt'} = 1;
15863:             }
15864:         }
15865:     }
15866:     unless (exists($currltisec{'rules'})) {
15867:         $currltisec{'rules'} = {};
15868:     }
15869:     &password_rule_changes('secrets',$newltisec{'rules'},$currltisec{'rules'},\%secchanges);
15870: 
15871:     my @ids=&Apache::lonnet::current_machine_ids();
15872:     my %servers = &Apache::lonnet::get_servers($dom,'library');
15873:    
15874:     foreach my $hostid (keys(%servers)) {
15875:         if (($hostid ne '') && (grep(/^\Q$hostid\E$/,@ids))) {
15876:             my $newkey;
15877:             my $keyitem = 'form.ltisec_privkey_'.$hostid;
15878:             if (exists($env{$keyitem})) {
15879:                 $env{$keyitem} =~ s/(`)/'/g;
15880:                 if ($keyset{$hostid}) {
15881:                     if ($env{'form.ltisec_changeprivkey_'.$hostid}) {
15882:                         if ($env{$keyitem} ne '') {
15883:                             $secchanges{'private'} = 1;
15884:                             $newkeyset{$hostid} = $env{$keyitem};
15885:                         }
15886:                     }
15887:                 } elsif ($env{$keyitem} ne '') {
15888:                     unless (grep(/^\Q$hostid\E$/,@{$newltisec{'private'}{'keys'}})) { 
15889:                         push(@{$newltisec{'private'}{'keys'}},$hostid);
15890:                     }
15891:                     $secchanges{'private'} = 1;
15892:                     $newkeyset{$hostid} = $env{$keyitem};
15893:                 }
15894:             }
15895:         }
15896:     }
15897: 
15898:     my (@items,%deletions,%itemids);
15899:     if ($env{'form.lti_add'}) {
15900:         my $consumer = $env{'form.lti_consumer_add'};
15901:         $consumer =~ s/(`)/'/g;
15902:         ($newid,my $error) = &get_lti_id($dom,$consumer);
15903:         if ($newid) {
15904:             $itemids{'add'} = $newid;
15905:             push(@items,'add');
15906:             $changes{$newid} = 1;
15907:         } else {
15908:             my $error = &mt('Failed to acquire unique ID for new LTI configuration');
15909:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
15910:         }
15911:     }
15912:     if (ref($domconfig{$action}) eq 'HASH') {
15913:         my @todelete = &Apache::loncommon::get_env_multiple('form.lti_del');
15914:         if (@todelete) {
15915:             map { $deletions{$_} = 1; } @todelete;
15916:         }
15917:         my $maxnum = $env{'form.lti_maxnum'};
15918:         for (my $i=0; $i<$maxnum; $i++) {
15919:             my $itemid = $env{'form.lti_id_'.$i};
15920:             $itemid =~ s/\D+//g;
15921:             if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
15922:                 if ($deletions{$itemid}) {
15923:                     $changes{$itemid} = $domconfig{$action}{$itemid}{'consumer'};
15924:                 } else {
15925:                     push(@items,$i);
15926:                     $itemids{$i} = $itemid;
15927:                 }
15928:             }
15929:         }
15930:     }
15931:     foreach my $idx (@items) {
15932:         my $itemid = $itemids{$idx};
15933:         next unless ($itemid);
15934:         my $position = $env{'form.lti_pos_'.$itemid};
15935:         $position =~ s/\D+//g;
15936:         if ($position ne '') {
15937:             $allpos[$position] = $itemid;
15938:         }
15939:         foreach my $item ('consumer','key','secret','lifetime','requser','crsinc') {
15940:             my $formitem = 'form.lti_'.$item.'_'.$idx;
15941:             $env{$formitem} =~ s/(`)/'/g;
15942:             if ($item eq 'lifetime') {
15943:                 $env{$formitem} =~ s/[^\d.]//g;
15944:             }
15945:             if ($env{$formitem} ne '') {
15946:                 if (($item eq 'key') || ($item eq 'secret')) {
15947:                     $encconfig{$itemid}{$item} = $env{$formitem};
15948:                 } else {
15949:                     $confhash{$itemid}{$item} = $env{$formitem};
15950:                     unless (($idx eq 'add') || ($changes{$itemid})) {
15951:                         if ($domconfig{$action}{$itemid}{$item} ne $confhash{$itemid}{$item}) {
15952:                             $changes{$itemid} = 1;
15953:                         }
15954:                     }
15955:                 }
15956:             }
15957:         }
15958:         if ($env{'form.lti_version_'.$idx} eq 'LTI-1p0') {
15959:             $confhash{$itemid}{'version'} = $env{'form.lti_version_'.$idx};
15960:         }
15961:         if ($confhash{$itemid}{'requser'}) {
15962:             if ($env{'form.lti_mapuser_'.$idx} eq 'sourcedid') {
15963:                 $confhash{$itemid}{'mapuser'} = 'lis_person_sourcedid';
15964:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'email') {
15965:                 $confhash{$itemid}{'mapuser'} = 'lis_person_contact_email_primary';
15966:             } elsif ($env{'form.lti_mapuser_'.$idx} eq 'other') {
15967:                 my $mapuser = $env{'form.lti_customuser_'.$idx};
15968:                 $mapuser =~ s/(`)/'/g;
15969:                 $mapuser =~ s/^\s+|\s+$//g;
15970:                 $confhash{$itemid}{'mapuser'} = $mapuser;
15971:             }
15972:             my @possmakeuser = &Apache::loncommon::get_env_multiple('form.lti_makeuser_'.$idx);
15973:             my @makeuser;
15974:             foreach my $ltirole (sort(@possmakeuser)) {
15975:                 if ($posslti{$ltirole}) {
15976:                     push(@makeuser,$ltirole);
15977:                 }
15978:             }
15979:             $confhash{$itemid}{'makeuser'} = \@makeuser;
15980:             if (@makeuser) {
15981:                 my $lcauth = $env{'form.lti_lcauth_'.$idx};
15982:                 if ($lcauth =~ /^(internal|krb4|krb5|localauth)$/) {
15983:                     $confhash{$itemid}{'lcauth'} = $lcauth;
15984:                     if ($lcauth ne 'internal') {
15985:                         my $lcauthparm = $env{'form.lti_lcauthparm_'.$idx};
15986:                         $lcauthparm =~ s/^(\s+|\s+)$//g;
15987:                         $lcauthparm =~ s/`//g;
15988:                         if ($lcauthparm ne '') {
15989:                             $confhash{$itemid}{'lcauthparm'} = $lcauthparm;
15990:                         }
15991:                     }
15992:                 } else {
15993:                     $confhash{$itemid}{'lcauth'} = 'lti';
15994:                 }
15995:             }
15996:             my @possinstdata =  &Apache::loncommon::get_env_multiple('form.lti_instdata_'.$idx);
15997:             if (@possinstdata) {
15998:                 foreach my $field (@possinstdata) {
15999:                     if (exists($fieldtitles{$field})) {
16000:                         push(@{$confhash{$itemid}{'instdata'}});
16001:                     }
16002:                 }
16003:             }
16004:             if ($env{'form.lti_callback_'.$idx}) {
16005:                 if ($env{'form.lti_callbackparam_'.$idx}) {
16006:                     my $callback = $env{'form.lti_callbackparam_'.$idx};
16007:                     $callback =~ s/^\s+|\s+$//g;
16008:                     $confhash{$itemid}{'callback'} = $callback;
16009:                 }
16010:             }
16011:             foreach my $field ('topmenu','inlinemenu') {
16012:                 if ($env{'form.lti_'.$field.'_'.$idx}) {
16013:                     $confhash{$itemid}{$field} = 1;
16014:                 }
16015:             }
16016:             if ($env{'form.lti_topmenu_'.$idx} || $env{'form.lti_inlinemenu_'.$idx}) {
16017:                 $confhash{$itemid}{lcmenu} = [];
16018:                 my @possmenu = &Apache::loncommon::get_env_multiple('form.lti_menuitem_'.$idx);
16019:                 foreach my $field (@possmenu) {
16020:                     if (exists($menutitles{$field})) {
16021:                         if ($field eq 'grades') {
16022:                             next unless ($env{'form.lti_inlinemenu_'.$idx});
16023:                         }
16024:                         push(@{$confhash{$itemid}{lcmenu}},$field);
16025:                     }
16026:                 }
16027:             }
16028:             if ($confhash{$itemid}{'crsinc'}) {
16029:                 if (($env{'form.lti_mapcrs_'.$idx} eq 'course_offering_sourcedid') ||
16030:                     ($env{'form.lti_mapcrs_'.$idx} eq 'context_id'))  {
16031:                     $confhash{$itemid}{'mapcrs'} = $env{'form.lti_mapcrs_'.$idx};
16032:                 } elsif ($env{'form.lti_mapcrs_'.$idx} eq 'other') {
16033:                     my $mapcrs = $env{'form.lti_mapcrsfield_'.$idx}; 
16034:                     $mapcrs =~ s/(`)/'/g;
16035:                     $mapcrs =~ s/^\s+|\s+$//g;
16036:                     $confhash{$itemid}{'mapcrs'} = $mapcrs;
16037:                 }
16038:                 my @posstypes = &Apache::loncommon::get_env_multiple('form.lti_mapcrstype_'.$idx);
16039:                 my @crstypes;
16040:                 foreach my $type (sort(@posstypes)) {
16041:                     if ($posscrstype{$type}) {
16042:                         push(@crstypes,$type);
16043:                     }
16044:                 }
16045:                 $confhash{$itemid}{'mapcrstype'} = \@crstypes;
16046:                 if ($env{'form.lti_storecrs_'.$idx}) {
16047:                     $confhash{$itemid}{'storecrs'} = 1;
16048:                 }       
16049:                 if ($env{'form.lti_makecrs_'.$idx}) {
16050:                     $confhash{$itemid}{'makecrs'} = 1;
16051:                 }
16052:                 foreach my $ltirole (@lticourseroles) {
16053:                     my $possrole = $env{'form.lti_maprole_'.$ltirole.'_'.$idx};
16054:                     if (grep(/^\Q$possrole\E$/,@courseroles)) {
16055:                         $confhash{$itemid}{'maproles'}{$ltirole} = $possrole;
16056:                     }
16057:                 }
16058:                 my @possenroll = &Apache::loncommon::get_env_multiple('form.lti_selfenroll_'.$idx);
16059:                 my @selfenroll;
16060:                 foreach my $type (sort(@possenroll)) {
16061:                     if ($posslticrs{$type}) {
16062:                         push(@selfenroll,$type);
16063:                     }
16064:                 }
16065:                 $confhash{$itemid}{'selfenroll'} = \@selfenroll;
16066:                 if ($env{'form.lti_crssec_'.$idx}) {
16067:                     if ($env{'form.lti_crssecsrc_'.$idx} eq 'course_section_sourcedid') {
16068:                         $confhash{$itemid}{'section'} = $env{'form.lti_crssecsrc_'.$idx};
16069:                     } elsif ($env{'form.lti_crssecsrc_'.$idx} eq 'other') {
16070:                         my $section = $env{'form.lti_customsection_'.$idx};
16071:                         $section =~ s/(`)/'/g;
16072:                         $section =~ s/^\s+|\s+$//g;
16073:                         if ($section ne '') {
16074:                             $confhash{$itemid}{'section'} = $section;
16075:                         }
16076:                     }
16077:                 }
16078:                 foreach my $field ('passback','roster') {
16079:                     if ($env{'form.lti_'.$field.'_'.$idx}) {
16080:                         $confhash{$itemid}{$field} = 1;
16081:                     }
16082:                 }
16083:                 if ($env{'form.lti_passback_'.$idx}) {
16084:                     if ($env{'form.lti_passbackformat_'.$idx} eq '1.0') {
16085:                         $confhash{$itemid}{'passbackformat'} = '1.0';
16086:                     } else {
16087:                         $confhash{$itemid}{'passbackformat'} = '1.1';
16088:                     }
16089:                 }
16090:             }
16091:             unless (($idx eq 'add') || ($changes{$itemid})) {
16092:                 if ($confhash{$itemid}{'crsinc'}) {
16093:                     foreach my $field ('mapcrs','storecrs','makecrs','section','passback','roster') {
16094:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16095:                             $changes{$itemid} = 1;
16096:                         }
16097:                     }
16098:                     unless ($changes{$itemid}) {
16099:                         if ($domconfig{$action}{$itemid}{'passback'} eq $confhash{$itemid}{'passback'}) {
16100:                             if ($domconfig{$action}{$itemid}{'passbackformat'} ne $confhash{$itemid}{'passbackformat'}) {
16101:                                 $changes{$itemid} = 1;
16102:                             }
16103:                         }
16104:                     }
16105:                     foreach my $field ('mapcrstype','selfenroll') {
16106:                         unless ($changes{$itemid}) {
16107:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16108:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16109:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16110:                                                                                    $confhash{$itemid}{$field});
16111:                                     if (@diffs) {
16112:                                         $changes{$itemid} = 1;
16113:                                     }
16114:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16115:                                     $changes{$itemid} = 1;
16116:                                 }
16117:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16118:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16119:                                     $changes{$itemid} = 1;
16120:                                 }
16121:                             }
16122:                         }
16123:                     }
16124:                     unless ($changes{$itemid}) {
16125:                         if (ref($domconfig{$action}{$itemid}{'maproles'}) eq 'HASH') {
16126:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16127:                                 foreach my $ltirole (keys(%{$domconfig{$action}{$itemid}{'maproles'}})) {
16128:                                     if ($domconfig{$action}{$itemid}{'maproles'}{$ltirole} ne 
16129:                                         $confhash{$itemid}{'maproles'}{$ltirole}) {
16130:                                         $changes{$itemid} = 1;
16131:                                         last;
16132:                                     }
16133:                                 }
16134:                                 unless ($changes{$itemid}) {
16135:                                     foreach my $ltirole (keys(%{$confhash{$itemid}{'maproles'}})) {
16136:                                         if ($confhash{$itemid}{'maproles'}{$ltirole} ne 
16137:                                             $domconfig{$action}{$itemid}{'maproles'}{$ltirole}) {
16138:                                             $changes{$itemid} = 1;
16139:                                             last;
16140:                                         }
16141:                                     }
16142:                                 }
16143:                             } elsif (keys(%{$domconfig{$action}{$itemid}{'maproles'}}) > 0) {
16144:                                 $changes{$itemid} = 1;
16145:                             }
16146:                         } elsif (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16147:                             unless ($changes{$itemid}) {
16148:                                 if (keys(%{$confhash{$itemid}{'maproles'}}) > 0) {
16149:                                     $changes{$itemid} = 1;
16150:                                 }
16151:                             }
16152:                         }
16153:                     }
16154:                 }
16155:                 unless ($changes{$itemid}) {
16156:                     foreach my $field ('mapuser','lcauth','lcauthparm','topmenu','inlinemenu','callback') {
16157:                         if ($domconfig{$action}{$itemid}{$field} ne $confhash{$itemid}{$field}) {
16158:                             $changes{$itemid} = 1;
16159:                         }
16160:                     }
16161:                     unless ($changes{$itemid}) {
16162:                         foreach my $field ('makeuser','lcmenu') {
16163:                             if (ref($domconfig{$action}{$itemid}{$field}) eq 'ARRAY') {
16164:                                 if (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16165:                                     my @diffs = &Apache::loncommon::compare_arrays($domconfig{$action}{$itemid}{$field},
16166:                                                                                    $confhash{$itemid}{$field});
16167:                                     if (@diffs) {
16168:                                         $changes{$itemid} = 1;
16169:                                     }
16170:                                 } elsif (@{$domconfig{$action}{$itemid}{$field}} > 0) {
16171:                                     $changes{$itemid} = 1;
16172:                                 }
16173:                             } elsif (ref($confhash{$itemid}{$field}) eq 'ARRAY') {
16174:                                 if (@{$confhash{$itemid}{$field}} > 0) {
16175:                                     $changes{$itemid} = 1;
16176:                                 }
16177:                             }
16178:                         }
16179:                     }
16180:                 }
16181:             }
16182:         }
16183:     }
16184:     if (@allpos > 0) {
16185:         my $idx = 0;
16186:         foreach my $itemid (@allpos) {
16187:             if ($itemid ne '') {
16188:                 $confhash{$itemid}{'order'} = $idx;
16189:                 if (ref($domconfig{$action}) eq 'HASH') {
16190:                     if (ref($domconfig{$action}{$itemid}) eq 'HASH') {
16191:                         if ($domconfig{$action}{$itemid}{'order'} ne $idx) {
16192:                             $changes{$itemid} = 1;
16193:                         }
16194:                     }
16195:                 }
16196:                 $idx ++;
16197:             }
16198:         }
16199:     }
16200:     my %ltihash = (
16201:                       $action => { %confhash }
16202:                   );
16203:     if (keys(%secchanges)) {
16204:         $ltihash{'ltisec'} = \%newltisec;
16205:     }
16206:     my $putresult = &Apache::lonnet::put_dom('configuration',\%ltihash,$dom);
16207:     if ($putresult eq 'ok') {
16208:         my %keystore;
16209:         if (keys(%secchanges)) {
16210:             if ($secchanges{'private'}) {
16211:                 my $who = &escape($env{'user.name'}.':'.$env{'user.domain'});
16212:                 foreach my $hostid (keys(%newkeyset)) {
16213:                     my $storehash = {
16214:                                        key => $newkeyset{$hostid},
16215:                                        who => $env{'user.name'}.':'.$env{'user.domain'},
16216:                                     };
16217:                     $keystore{$hostid} = &Apache::lonnet::store_dom($storehash,'lti','private',
16218:                                                                     $dom,$hostid);
16219:                 }
16220:             }
16221:         }
16222:         my %ltienchash = (
16223:                              $action => { %encconfig }
16224:                          );
16225:         &Apache::lonnet::put_dom('encconfig',\%ltienchash,$dom,undef,1);
16226:         if ((keys(%changes) == 0) && (keys(%secchanges) == 0)) {
16227:             return &mt('No changes made.');
16228:         }
16229:         $resulttext = &mt('Changes made:').'<ul>';
16230:         if (keys(%secchanges) > 0) {
16231:             foreach my $item (keys(%secchanges)) {
16232:                 if ($item eq 'encrypt') {
16233:                     my %encrypted = (
16234:                               crs  => {
16235:                                         on => &mt('Encryption of stored link protection secrets defined in courses enabled'),
16236:                                         off => &mt('Encryption of stored link protection secrets defined in courses disabled'),
16237:                                       },
16238:                               dom => {
16239:                                        on => &mt('Encryption of stored link protection secrets defined in domain enabled'),
16240:                                        off => &mt('Encryption of stored link protection secrets defined in domain disabled'),
16241:                                      },
16242:                               consumers => {
16243:                                              on => &mt('Encryption of stored consumer secrets defined in domain enabled'),
16244:                                              off => &mt('Encryption of stored consumer secrets defined in domain disabled'),
16245:                                            },
16246:                             );
16247:                     foreach my $type ('crs','dom','consumers') {
16248:                         my $shown = $encrypted{$type}{'off'};
16249:                         if (ref($newltisec{$item}) eq 'HASH') {
16250:                             if ($newltisec{$item}{$type}) {
16251:                                 $shown = $encrypted{$type}{'on'}; 
16252:                             }
16253:                         }
16254:                         $resulttext .= '<li>'.$shown.'</li>';
16255:                     } 
16256:                 } elsif ($item eq 'rules') {
16257:                      my %titles = &Apache::lonlocal::texthash(
16258:                                       min   => 'Minimum password length',
16259:                                       max   => 'Maximum password length',
16260:                                       chars => 'Required characters',
16261:                      );
16262:                      foreach my $rule ('min','max') {
16263:                          if ($newltisec{rules}{$rule} eq '') {
16264:                              if ($rule eq 'min') {
16265:                                  $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
16266:                                                 ' '.&mt('Default of [_1] will be used',
16267:                                                             $Apache::lonnet::passwdmin).'</li>';
16268:                              } else {
16269:                                  $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
16270:                              }
16271:                          } else {
16272:                              $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$newltisec{rules}{$rule}).'</li>';
16273:                          }
16274:                      }
16275:                      if (ref($newltisec{'rules'}{'chars'}) eq 'ARRAY') {
16276:                          if (@{$newltisec{'rules'}{'chars'}} > 0) {
16277:                              my %rulenames = &Apache::lonlocal::texthash(
16278:                                                  uc => 'At least one upper case letter',
16279:                                                  lc => 'At least one lower case letter',
16280:                                                  num => 'At least one number',
16281:                                                  spec => 'At least one non-alphanumeric',
16282:                                              );
16283:                              my $needed = '<ul><li>'.
16284:                                           join('</li><li>',map {$rulenames{$_} } @{$newltisec{'rules'}{'chars'}}).
16285:                                           '</li></ul>';
16286:                              $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
16287:                          } else {
16288:                              $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16289:                          }
16290:                      } else {
16291:                          $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
16292:                      }
16293:                 } elsif ($item eq 'private') {
16294:                     if (keys(%newkeyset)) {
16295:                         foreach my $hostid (sort(keys(%newkeyset))) {
16296:                             if ($keystore{$hostid} eq 'ok') {
16297:                                 $resulttext .= '<li>'.&mt('Encryption key for storage of shared secrets saved for [_1]',$hostid).'</li>';
16298:                             }
16299:                         }
16300:                     }
16301:                 }
16302:             }
16303:         }
16304:         if (keys(%changes) > 0) {
16305:             my $cachetime = 24*60*60;
16306:             my %ltiall = %confhash;
16307:             foreach my $id (keys(%ltiall)) {
16308:                 if (ref($encconfig{$id}) eq 'HASH') {
16309:                     foreach my $item ('key','secret') {
16310:                         $ltiall{$id}{$item} = $encconfig{$id}{$item};
16311:                     }
16312:                 }
16313:             }
16314:             &Apache::lonnet::do_cache_new('lti',$dom,\%ltiall,$cachetime);
16315:             if (ref($lastactref) eq 'HASH') {
16316:                 $lastactref->{'lti'} = 1;
16317:             }
16318:             my %bynum;
16319:             foreach my $itemid (sort(keys(%changes))) {
16320:                 my $position = $confhash{$itemid}{'order'};
16321:                 $bynum{$position} = $itemid;
16322:             }
16323:             foreach my $pos (sort { $a <=> $b } keys(%bynum)) {
16324:                 my $itemid = $bynum{$pos};
16325:                 if (ref($confhash{$itemid}) ne 'HASH') {
16326:                     $resulttext .= '<li>'.&mt('Deleted: [_1]',$changes{$itemid}).'</li>';
16327:                 } else {
16328:                     $resulttext .= '<li><b>'.$confhash{$itemid}{'consumer'}.'</b><ul>';
16329:                     my $position = $pos + 1;
16330:                     $resulttext .= '<li>'.&mt('Order: [_1]',$position).'</li>';
16331:                     foreach my $item ('version','lifetime') {
16332:                         if ($confhash{$itemid}{$item} ne '') {
16333:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;'.$confhash{$itemid}{$item}.'</li>';
16334:                         }
16335:                     }
16336:                     if ($encconfig{$itemid}{'key'} ne '') {
16337:                         $resulttext .= '<li>'.$lt{'key'}.':&nbsp;'.$encconfig{$itemid}{'key'}.'</li>';
16338:                     }
16339:                     if ($encconfig{$itemid}{'secret'} ne '') {
16340:                         $resulttext .= '<li>'.$lt{'secret'}.':&nbsp;';
16341:                         my $num = length($encconfig{$itemid}{'secret'});
16342:                         $resulttext .= ('*'x$num).'</li>';
16343:                     }
16344:                     if ($confhash{$itemid}{'requser'}) {
16345:                         if ($confhash{$itemid}{'callback'}) {
16346:                             $resulttext .= '<li>'.&mt('Callback setting').': '.$confhash{$itemid}{'callback'}.'</li>';
16347:                         } else {
16348:                             $resulttext .= '<li>'.&mt('Callback to logout LON-CAPA on log out from Consumer').'</li>';
16349:                         }
16350:                         if ($confhash{$itemid}{'mapuser'}) {
16351:                             my $shownmapuser;
16352:                             if ($confhash{$itemid}{'mapuser'} eq 'lis_person_sourcedid') {
16353:                                 $shownmapuser = $lt{'sourcedid'}.' (lis_person_sourcedid)';
16354:                             } elsif ($confhash{$itemid}{'mapuser'} eq 'lis_person_contact_email_primary') {
16355:                                 $shownmapuser = $lt{'email'}.' (lis_person_contact_email_primary)';
16356:                             } else {
16357:                                 $shownmapuser = &mt('Other').' ('.$confhash{$itemid}{'mapuser'}.')';
16358:                             }
16359:                             $resulttext .= '<li>'.&mt('LON-CAPA username').': '.$shownmapuser.'</li>';
16360:                         }
16361:                         if (ref($confhash{$itemid}{'makeuser'}) eq 'ARRAY') {
16362:                             if (@{$confhash{$itemid}{'makeuser'}} > 0) { 
16363:                                 $resulttext .= '<li>'.&mt('Following roles may create user accounts: [_1]',
16364:                                                           join(', ',@{$confhash{$itemid}{'makeuser'}})).'<br />';
16365:                                 if ($confhash{$itemid}{'lcauth'} eq 'lti') {
16366:                                     $resulttext .= &mt('New users will only be able to authenticate via LTI').'</li>';
16367:                                 } else {
16368:                                     $resulttext .= &mt('New users will be assigned LON-CAPA authentication: [_1]',
16369:                                                        $confhash{$itemid}{'lcauth'});
16370:                                     if ($confhash{$itemid}{'lcauth'} eq 'internal') {
16371:                                         $resulttext .= '; '.&mt('a randomly generated password will be created');
16372:                                     } elsif ($confhash{$itemid}{'lcauth'} eq 'localauth') {
16373:                                         if ($confhash{$itemid}{'lcauthparm'} ne '') {
16374:                                             $resulttext .= ' '.&mt('with argument: [_1]',$confhash{$itemid}{'lcauthparm'});
16375:                                         }
16376:                                     } else {
16377:                                         $resulttext .= '; '.&mt('Kerberos domain: [_1]',$confhash{$itemid}{'lcauthparm'});
16378:                                     }
16379:                                 }
16380:                                 $resulttext .= '</li>';
16381:                             } else {
16382:                                 $resulttext .= '<li>'.&mt('User account creation not permitted.').'</li>';
16383:                             }
16384:                         }
16385:                         if (ref($confhash{$itemid}{'instdata'}) eq 'ARRAY') {
16386:                             if (@{$confhash{$itemid}{'instdata'}} > 0) {
16387:                                 $resulttext .= '<li>'.&mt('Institutional data will be used when creating a new user for: [_1]',
16388:                                                           join(', ',map { $fieldtitles{$_}; } @{$confhash{$itemid}{'instdata'}})).'</li>';
16389:                             } else {
16390:                                 $resulttext .= '<li>'.&mt('No institutional data used when creating a new user.').'</li>';
16391:                             }
16392:                         }
16393:                         foreach my $item ('topmenu','inlinemenu') {
16394:                             $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16395:                             if ($confhash{$itemid}{$item}) {
16396:                                 $resulttext .= &mt('Yes');
16397:                             } else {
16398:                                 $resulttext .= &mt('No');
16399:                             }
16400:                             $resulttext .= '</li>';
16401:                         }
16402:                         if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16403:                             if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16404:                                 $resulttext .= '<li>'.&mt('Menu items:').' '.
16405:                                                join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>';
16406:                             } else {
16407:                                 $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>';
16408:                             }
16409:                         }
16410:                         if ($confhash{$itemid}{'crsinc'}) {
16411:                             if (ref($confhash{$itemid}{'maproles'}) eq 'HASH') {
16412:                                 my $rolemaps;
16413:                                 foreach my $role (@ltiroles) {
16414:                                     if ($confhash{$itemid}{'maproles'}{$role}) {
16415:                                         $rolemaps .= ('&nbsp;'x2).$role.'='.
16416:                                                      &Apache::lonnet::plaintext($confhash{$itemid}{'maproles'}{$role},
16417:                                                                                 'Course').',';
16418:                                     }
16419:                                 }
16420:                                 if ($rolemaps) {
16421:                                     $rolemaps =~ s/,$//;
16422:                                     $resulttext .= '<li>'.&mt('Role mapping:').$rolemaps.'</li>';
16423:                                 }
16424:                             }
16425:                             if ($confhash{$itemid}{'mapcrs'}) {
16426:                                 $resulttext .= '<li>'.&mt('Unique course identifier').': '.$confhash{$itemid}{'mapcrs'}.'</li>';
16427:                             }
16428:                             if (ref($confhash{$itemid}{'mapcrstype'}) eq 'ARRAY') {
16429:                                 if (@{$confhash{$itemid}{'mapcrstype'}} > 0) {
16430:                                     $resulttext .= '<li>'.&mt('Mapping for the following LON-CAPA course types: [_1]',
16431:                                                    join(', ',map { $coursetypetitles{$_}; } @coursetypes)).
16432:                                                    '</li>';
16433:                                 } else {
16434:                                     $resulttext .= '<li>'.&mt('No mapping to LON-CAPA courses').'</li>';
16435:                                 }
16436:                             }
16437:                             if ($confhash{$itemid}{'storecrs'}) {
16438:                                 $resulttext .= '<li>'.&mt('Store mapping of course identifier to LON-CAPA CourseID').': '.$confhash{$itemid}{'storecrs'}.'</li>';
16439:                             }
16440:                             if ($confhash{$itemid}{'makecrs'}) {
16441:                                 $resulttext .= '<li>'.&mt('Instructor may create course (if absent).').'</li>';
16442:                             } else {
16443:                                 $resulttext .= '<li>'.&mt('Instructor may not create course (if absent).').'</li>';
16444:                             }
16445:                             if (ref($confhash{$itemid}{'selfenroll'}) eq 'ARRAY') {
16446:                                 if (@{$confhash{$itemid}{'selfenroll'}} > 0) {
16447:                                     $resulttext .= '<li>'.&mt('Self-enrollment for following roles: [_1]',
16448:                                                               join(', ',@{$confhash{$itemid}{'selfenroll'}})).
16449:                                                    '</li>';
16450:                                 } else {
16451:                                     $resulttext .= '<li>'.&mt('Self-enrollment not permitted').'</li>';
16452:                                 }
16453:                             }
16454:                             if ($confhash{$itemid}{'section'}) {
16455:                                 if ($confhash{$itemid}{'section'} eq 'course_section_sourcedid') {
16456:                                     $resulttext .= '<li>'.&mt('User section from standard field:').
16457:                                                          ' (course_section_sourcedid)'.'</li>';  
16458:                                 } else {
16459:                                     $resulttext .= '<li>'.&mt('User section from:').' '.
16460:                                                           $confhash{$itemid}{'section'}.'</li>';
16461:                                 }
16462:                             } else {
16463:                                 $resulttext .= '<li>'.&mt('No section assignment').'</li>';
16464:                             }
16465:                             foreach my $item ('passback','roster','topmenu','inlinemenu') {
16466:                                 $resulttext .= '<li>'.$lt{$item}.':&nbsp;';
16467:                                 if ($confhash{$itemid}{$item}) {
16468:                                     $resulttext .= &mt('Yes');
16469:                                     if ($item eq 'passback') {
16470:                                         if ($confhash{$itemid}{'passbackformat'} eq '1.0') {
16471:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Extension (1.0)').')';
16472:                                         } elsif ($confhash{$itemid}{'passbackformat'} eq '1.1') {
16473:                                             $resulttext .= '&nbsp;('.&mt('Outcomes Service (1.1)').')';
16474:                                         }
16475:                                     }
16476:                                 } else {
16477:                                     $resulttext .= &mt('No');
16478:                                 }
16479:                                 $resulttext .= '</li>';
16480:                             }
16481:                             if (ref($confhash{$itemid}{'lcmenu'}) eq 'ARRAY') {
16482:                                 if (@{$confhash{$itemid}{'lcmenu'}} > 0) {
16483:                                     $resulttext .= '<li>'.&mt('Menu items:').' '.
16484:                                                    join(', ', map { $menutitles{$_}; } (@{$confhash{$itemid}{'lcmenu'}})).'</li>'; 
16485:                                 } else {
16486:                                     $resulttext .= '<li>'.&mt('No menu items displayed in header or online menu').'</li>'; 
16487:                                 }
16488:                             }
16489:                         }
16490:                     }
16491:                     $resulttext .= '</ul></li>';
16492:                 }
16493:             }
16494:         }
16495:         $resulttext .= '</ul>';
16496:     } else {
16497:         $errors .= '<li><span class="LC_error">'.&mt('Failed to save changes').'</span></li>';
16498:     }
16499:     if ($errors) {
16500:         $resulttext .= &mt('The following errors occurred: ').'<ul>'.
16501:                        $errors.'</ul>';
16502:     }
16503:     return $resulttext;
16504: }
16505: 
16506: sub get_lti_id {
16507:     my ($domain,$consumer) = @_;
16508:     # get lock on lti db
16509:     my $lockhash = {
16510:                       lock => $env{'user.name'}.
16511:                               ':'.$env{'user.domain'},
16512:                    };
16513:     my $tries = 0;
16514:     my $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16515:     my ($id,$error);
16516: 
16517:     while (($gotlock ne 'ok') && ($tries<10)) {
16518:         $tries ++;
16519:         sleep (0.1);
16520:         $gotlock = &Apache::lonnet::newput_dom('lti',$lockhash,$domain);
16521:     }
16522:     if ($gotlock eq 'ok') {
16523:         my %currids = &Apache::lonnet::dump_dom('lti',$domain);
16524:         if ($currids{'lock'}) {
16525:             delete($currids{'lock'});
16526:             if (keys(%currids)) {
16527:                 my @curr = sort { $a <=> $b } keys(%currids);
16528:                 if ($curr[-1] =~ /^\d+$/) {
16529:                     $id = 1 + $curr[-1];
16530:                 }
16531:             } else {
16532:                 $id = 1;
16533:             }
16534:             if ($id) {
16535:                 unless (&Apache::lonnet::newput_dom('lti',{ $id => $consumer },$domain) eq 'ok') {
16536:                     $error = 'nostore';
16537:                 }
16538:             } else {
16539:                 $error = 'nonumber';
16540:             }
16541:         }
16542:         my $dellockoutcome = &Apache::lonnet::del_dom('lti',['lock'],$domain);
16543:     } else {
16544:         $error = 'nolock';
16545:     }
16546:     return ($id,$error);
16547: }
16548: 
16549: sub modify_autoenroll {
16550:     my ($dom,$lastactref,%domconfig) = @_;
16551:     my ($resulttext,%changes);
16552:     my %currautoenroll;
16553:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
16554:         foreach my $key (keys(%{$domconfig{'autoenroll'}})) {
16555:             $currautoenroll{$key} = $domconfig{'autoenroll'}{$key};
16556:         }
16557:     }
16558:     my $autorun = &Apache::lonnet::auto_run(undef,$dom),
16559:     my %title = ( run => 'Auto-enrollment active',
16560:                   sender => 'Sender for notification messages',
16561:                   coowners => 'Automatic assignment of co-ownership to instructors of record (institutional data)',
16562:                   autofailsafe => 'Failsafe for no drops if institutional data missing for a section');
16563:     my @offon = ('off','on');
16564:     my $sender_uname = $env{'form.sender_uname'};
16565:     my $sender_domain = $env{'form.sender_domain'};
16566:     if ($sender_domain eq '') {
16567:         $sender_uname = '';
16568:     } elsif ($sender_uname eq '') {
16569:         $sender_domain = '';
16570:     }
16571:     my $coowners = $env{'form.autoassign_coowners'};
16572:     my $autofailsafe = $env{'form.autoenroll_autofailsafe'};
16573:     $autofailsafe =~ s{^\s+|\s+$}{}g;
16574:     if ($autofailsafe =~ /\D/) {
16575:         undef($autofailsafe);
16576:     }
16577:     my $failsafe = $env{'form.autoenroll_failsafe'};
16578:     unless (($failsafe eq 'zero') || ($failsafe eq 'any')) {
16579:         $failsafe = 'off';
16580:         undef($autofailsafe);
16581:     }
16582:     my %autoenrollhash =  (
16583:                        autoenroll => { 'run' => $env{'form.autoenroll_run'},
16584:                                        'sender_uname' => $sender_uname,
16585:                                        'sender_domain' => $sender_domain,
16586:                                        'co-owners' => $coowners,
16587:                                        'autofailsafe' => $autofailsafe,
16588:                                        'failsafe' => $failsafe,
16589:                                 }
16590:                      );
16591:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autoenrollhash,
16592:                                              $dom);
16593:     if ($putresult eq 'ok') {
16594:         if (exists($currautoenroll{'run'})) {
16595:              if ($currautoenroll{'run'} ne $env{'form.autoenroll_run'}) {
16596:                  $changes{'run'} = 1;
16597:              }
16598:         } elsif ($autorun) {
16599:             if ($env{'form.autoenroll_run'} ne '1') {
16600:                  $changes{'run'} = 1;
16601:             }
16602:         }
16603:         if ($currautoenroll{'sender_uname'} ne $sender_uname) {
16604:             $changes{'sender'} = 1;
16605:         }
16606:         if ($currautoenroll{'sender_domain'} ne $sender_domain) {
16607:             $changes{'sender'} = 1;
16608:         }
16609:         if ($currautoenroll{'co-owners'} ne '') {
16610:             if ($currautoenroll{'co-owners'} ne $coowners) {
16611:                 $changes{'coowners'} = 1;
16612:             }
16613:         } elsif ($coowners) {
16614:             $changes{'coowners'} = 1;
16615:         }
16616:         if ($currautoenroll{'autofailsafe'} ne $autofailsafe) {
16617:             $changes{'autofailsafe'} = 1;
16618:         }
16619:         if ($currautoenroll{'failsafe'} ne $failsafe) {
16620:             $changes{'failsafe'} = 1;
16621:         }
16622:         if (keys(%changes) > 0) {
16623:             $resulttext = &mt('Changes made:').'<ul>';
16624:             if ($changes{'run'}) {
16625:                 $resulttext .= '<li>'.&mt("$title{'run'} set to $offon[$env{'form.autoenroll_run'}]").'</li>';
16626:             }
16627:             if ($changes{'sender'}) {
16628:                 if ($sender_uname eq '' || $sender_domain eq '') {
16629:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to default (course owner).").'</li>';
16630:                 } else {
16631:                     $resulttext .= '<li>'.&mt("$title{'sender'} set to [_1]",$sender_uname.':'.$sender_domain).'</li>';
16632:                 }
16633:             }
16634:             if ($changes{'coowners'}) {
16635:                 $resulttext .= '<li>'.&mt("$title{'coowners'} set to $offon[$env{'form.autoassign_coowners'}]").'</li>';
16636:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
16637:                 if (ref($lastactref) eq 'HASH') {
16638:                     $lastactref->{'domainconfig'} = 1;
16639:                 }
16640:             }
16641:             if ($changes{'autofailsafe'}) {
16642:                 if ($autofailsafe ne '') {
16643:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section set to: [_1]',$autofailsafe).'</li>';
16644:                 } else {
16645:                     $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16646:                 }
16647:             }
16648:             if ($changes{'failsafe'}) {
16649:                 if ($failsafe eq 'off') {
16650:                     unless ($changes{'autofailsafe'}) {
16651:                         $resulttext .= '<li>'.&mt('Failsafe for no drops if institutional data missing for a section not in use').'</li>';
16652:                     }
16653:                 } elsif ($failsafe eq 'zero') {
16654:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero').'</li>';
16655:                 } else {
16656:                     $resulttext .= '<li>'.&mt('Failsafe applies if retrieved section enrollment is zero or greater').'</li>';
16657:                 }
16658:             }
16659:             if (($changes{'autofailsafe'}) || ($changes{'failsafe'})) {
16660:                 &Apache::lonnet::get_domain_defaults($dom,1);
16661:                 if (ref($lastactref) eq 'HASH') {
16662:                     $lastactref->{'domdefaults'} = 1;
16663:                 }
16664:             }
16665:             $resulttext .= '</ul>';
16666:         } else {
16667:             $resulttext = &mt('No changes made to auto-enrollment settings');
16668:         }
16669:     } else {
16670:         $resulttext = '<span class="LC_error">'.
16671: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16672:     }
16673:     return $resulttext;
16674: }
16675: 
16676: sub modify_autoupdate {
16677:     my ($dom,%domconfig) = @_;
16678:     my ($resulttext,%currautoupdate,%fields,%changes);
16679:     if (ref($domconfig{'autoupdate'}) eq 'HASH') {
16680:         foreach my $key (keys(%{$domconfig{'autoupdate'}})) {
16681:             $currautoupdate{$key} = $domconfig{'autoupdate'}{$key};
16682:         }
16683:     }
16684:     my @offon = ('off','on');
16685:     my %title = &Apache::lonlocal::texthash (
16686:                     run        => 'Auto-update:',
16687:                     classlists => 'Updates to user information in classlists?',
16688:                     unexpired  => 'Skip updates for users without active or future roles?',
16689:                     lastactive => 'Skip updates for inactive users?',
16690:                 );
16691:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16692:     my %fieldtitles = &Apache::lonlocal::texthash (
16693:                         id => 'Student/Employee ID',
16694:                         permanentemail => 'E-mail address',
16695:                         lastname => 'Last Name',
16696:                         firstname => 'First Name',
16697:                         middlename => 'Middle Name',
16698:                         generation => 'Generation',
16699:                       );
16700:     $othertitle = &mt('All users');
16701:     if (keys(%{$usertypes}) >  0) {
16702:         $othertitle = &mt('Other users');
16703:     }
16704:     foreach my $key (keys(%env)) {
16705:         if ($key =~ /^form\.updateable_(.+)_([^_]+)$/) {
16706:             my ($usertype,$item) = ($1,$2);
16707:             if (grep(/^\Q$item\E$/,keys(%fieldtitles))) {
16708:                 if ($usertype eq 'default') {   
16709:                     push(@{$fields{$1}},$2);
16710:                 } elsif (ref($types) eq 'ARRAY') {
16711:                     if (grep(/^\Q$usertype\E$/,@{$types})) {
16712:                         push(@{$fields{$1}},$2);
16713:                     }
16714:                 }
16715:             }
16716:         }
16717:     }
16718:     my @lockablenames = &Apache::loncommon::get_env_multiple('form.lockablenames');
16719:     @lockablenames = sort(@lockablenames);
16720:     if (ref($currautoupdate{'lockablenames'}) eq 'ARRAY') {
16721:         my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16722:         if (@changed) {
16723:             $changes{'lockablenames'} = 1;
16724:         }
16725:     } else {
16726:         if (@lockablenames) {
16727:             $changes{'lockablenames'} = 1;
16728:         }
16729:     }
16730:     my %updatehash = (
16731:                       autoupdate => { run => $env{'form.autoupdate_run'},
16732:                                       classlists => $env{'form.classlists'},
16733:                                       unexpired  => $env{'form.unexpired'},
16734:                                       fields => {%fields},
16735:                                       lockablenames => \@lockablenames,
16736:                                     }
16737:                      );
16738:     my $lastactivedays;
16739:     if ($env{'form.lastactive'}) {
16740:         $lastactivedays = $env{'form.lastactivedays'};
16741:         $lastactivedays =~ s/^\s+|\s+$//g;
16742:         unless ($lastactivedays =~ /^\d+$/) {
16743:             undef($lastactivedays);
16744:             $env{'form.lastactive'} = 0;
16745:         }
16746:     }
16747:     $updatehash{'autoupdate'}{'lastactive'} = $lastactivedays;
16748:     foreach my $key (keys(%currautoupdate)) {
16749:         if (($key eq 'run') || ($key eq 'classlists') || ($key eq 'unexpired') || ($key eq 'lastactive')) {
16750:             if (exists($updatehash{autoupdate}{$key})) {
16751:                 if ($currautoupdate{$key} ne $updatehash{autoupdate}{$key}) {
16752:                     $changes{$key} = 1;
16753:                 }
16754:             }
16755:         } elsif ($key eq 'fields') {
16756:             if (ref($currautoupdate{$key}) eq 'HASH') {
16757:                 foreach my $item (@{$types},'default') {
16758:                     if (ref($currautoupdate{$key}{$item}) eq 'ARRAY') {
16759:                         my $change = 0;
16760:                         foreach my $type (@{$currautoupdate{$key}{$item}}) {
16761:                             if (!exists($fields{$item})) {
16762:                                 $change = 1;
16763:                                 last;
16764:                             } elsif (ref($fields{$item}) eq 'ARRAY') {
16765:                                 if (!grep(/^\Q$type\E$/,@{$fields{$item}})) {
16766:                                     $change = 1;
16767:                                     last;
16768:                                 }
16769:                             }
16770:                         }
16771:                         if ($change) {
16772:                             push(@{$changes{$key}},$item);
16773:                         }
16774:                     } 
16775:                 }
16776:             }
16777:         } elsif ($key eq 'lockablenames') {
16778:             if (ref($currautoupdate{$key}) eq 'ARRAY') {
16779:                 my @changed = &Apache::loncommon::compare_arrays($currautoupdate{'lockablenames'},\@lockablenames);
16780:                 if (@changed) {
16781:                     $changes{'lockablenames'} = 1;
16782:                 }
16783:             } else {
16784:                 if (@lockablenames) {
16785:                     $changes{'lockablenames'} = 1;
16786:                 }
16787:             }
16788:         }
16789:     }
16790:     unless (grep(/^\Qlockablenames\E$/,keys(%currautoupdate))) {
16791:         if (@lockablenames) {
16792:             $changes{'lockablenames'} = 1;
16793:         }
16794:     }
16795:     unless (grep(/^unexpired$/,keys(%currautoupdate))) {
16796:         if ($updatehash{'autoupdate'}{'unexpired'}) {
16797:             $changes{'unexpired'} = 1;
16798:         }
16799:     }
16800:     unless (grep(/^lastactive$/,keys(%currautoupdate))) {
16801:         if ($updatehash{'autoupdate'}{'lastactive'} ne '') {
16802:             $changes{'lastactive'} = 1;
16803:         }
16804:     }
16805:     foreach my $item (@{$types},'default') {
16806:         if (defined($fields{$item})) {
16807:             if (ref($currautoupdate{'fields'}) eq 'HASH') {
16808:                 if (ref($currautoupdate{'fields'}{$item}) eq 'ARRAY') {
16809:                     my $change = 0;
16810:                     if (ref($fields{$item}) eq 'ARRAY') {
16811:                         foreach my $type (@{$fields{$item}}) {
16812:                             if (!grep(/^\Q$type\E$/,@{$currautoupdate{'fields'}{$item}})) {
16813:                                 $change = 1;
16814:                                 last;
16815:                             }
16816:                         }
16817:                     }
16818:                     if ($change) {
16819:                         push(@{$changes{'fields'}},$item);
16820:                     }
16821:                 } else {
16822:                     push(@{$changes{'fields'}},$item);
16823:                 }
16824:             } else {
16825:                 push(@{$changes{'fields'}},$item);
16826:             }
16827:         }
16828:     }
16829:     my $putresult = &Apache::lonnet::put_dom('configuration',\%updatehash,
16830:                                              $dom);
16831:     if ($putresult eq 'ok') {
16832:         if (keys(%changes) > 0) {
16833:             $resulttext = &mt('Changes made:').'<ul>';
16834:             foreach my $key (sort(keys(%changes))) {
16835:                 if ($key eq 'lockablenames') {
16836:                     $resulttext .= '<li>';
16837:                     if (@lockablenames) {
16838:                         $usertypes->{'default'} = $othertitle;
16839:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update), available for the following affiliations:").' '.
16840:                                    join(', ', map { $usertypes->{$_}; } @lockablenames).'</li>';
16841:                     } else {
16842:                         $resulttext .= &mt("User preference to disable replacement of user's name with institutional data (by auto-update) is unavailable.");
16843:                     }
16844:                     $resulttext .= '</li>';
16845:                 } elsif (ref($changes{$key}) eq 'ARRAY') {
16846:                     foreach my $item (@{$changes{$key}}) {
16847:                         my @newvalues;
16848:                         foreach my $type (@{$fields{$item}}) {
16849:                             push(@newvalues,$fieldtitles{$type});
16850:                         }
16851:                         my $newvaluestr;
16852:                         if (@newvalues > 0) {
16853:                             $newvaluestr = join(', ',@newvalues);
16854:                         } else {
16855:                             $newvaluestr = &mt('none');
16856:                         }
16857:                         if ($item eq 'default') {
16858:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$othertitle,$newvaluestr).'</li>';
16859:                         } else {
16860:                             $resulttext .= '<li>'.&mt("Updates for '[_1]' set to: '[_2]'",$usertypes->{$item},$newvaluestr).'</li>';
16861:                         }
16862:                     }
16863:                 } else {
16864:                     my $newvalue;
16865:                     if ($key eq 'run') {
16866:                         $newvalue = $offon[$env{'form.autoupdate_run'}];
16867:                     } elsif ($key eq 'lastactive') {
16868:                         $newvalue = $offon[$env{'form.lastactive'}];
16869:                         unless ($lastactivedays eq '') {
16870:                             $newvalue .= '; '.&mt('inactive = no activity in last [quant,_1,day]',$lastactivedays);
16871:                         }
16872:                     } else {
16873:                         $newvalue = $offon[$env{'form.'.$key}];
16874:                     }
16875:                     $resulttext .= '<li>'.&mt("[_1] set to $newvalue",$title{$key}).'</li>';
16876:                 }
16877:             }
16878:             $resulttext .= '</ul>';
16879:         } else {
16880:             $resulttext = &mt('No changes made to autoupdates');
16881:         }
16882:     } else {
16883:         $resulttext = '<span class="LC_error">'.
16884: 	    &mt('An error occurred: [_1]',$putresult).'</span>';
16885:     }
16886:     return $resulttext;
16887: }
16888: 
16889: sub modify_autocreate {
16890:     my ($dom,%domconfig) = @_;
16891:     my ($resulttext,%changes,%currautocreate,%newvals,%autocreatehash);
16892:     if (ref($domconfig{'autocreate'}) eq 'HASH') {
16893:         foreach my $key (keys(%{$domconfig{'autocreate'}})) {
16894:             $currautocreate{$key} = $domconfig{'autocreate'}{$key};
16895:         }
16896:     }
16897:     my %title= ( xml => 'Auto-creation of courses in XML course description files',
16898:                  req => 'Auto-creation of validated requests for official courses',
16899:                  xmldc => 'Identity of course creator of courses from XML files',
16900:                );
16901:     my @types = ('xml','req');
16902:     foreach my $item (@types) {
16903:         $newvals{$item} = $env{'form.autocreate_'.$item};
16904:         $newvals{$item} =~ s/\D//g;
16905:         $newvals{$item} = 0 if ($newvals{$item} eq '');
16906:     }
16907:     $newvals{'xmldc'} = $env{'form.autocreate_xmldc'};
16908:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
16909:     unless (exists($domcoords{$newvals{'xmldc'}})) {
16910:         $newvals{'xmldc'} = '';
16911:     } 
16912:     %autocreatehash =  (
16913:                         autocreate => { xml => $newvals{'xml'},
16914:                                         req => $newvals{'req'},
16915:                                       }
16916:                        );
16917:     if ($newvals{'xmldc'} ne '') {
16918:         $autocreatehash{'autocreate'}{'xmldc'} = $newvals{'xmldc'};
16919:     }
16920:     my $putresult = &Apache::lonnet::put_dom('configuration',\%autocreatehash,
16921:                                              $dom);
16922:     if ($putresult eq 'ok') {
16923:         my @items = @types;
16924:         if ($newvals{'xml'}) {
16925:             push(@items,'xmldc');
16926:         }
16927:         foreach my $item (@items) {
16928:             if (exists($currautocreate{$item})) {
16929:                 if ($currautocreate{$item} ne $newvals{$item}) {
16930:                     $changes{$item} = 1;
16931:                 }
16932:             } elsif ($newvals{$item}) {
16933:                 $changes{$item} = 1;
16934:             }
16935:         }
16936:         if (keys(%changes) > 0) {
16937:             my @offon = ('off','on'); 
16938:             $resulttext = &mt('Changes made:').'<ul>';
16939:             foreach my $item (@types) {
16940:                 if ($changes{$item}) {
16941:                     my $newtxt = $offon[$newvals{$item}];
16942:                     $resulttext .= '<li>'.
16943:                                    &mt("$title{$item} set to [_1]$newtxt [_2]",
16944:                                        '<b>','</b>').
16945:                                    '</li>';
16946:                 }
16947:             }
16948:             if ($changes{'xmldc'}) {
16949:                 my ($dcname,$dcdom) = split(':',$newvals{'xmldc'});
16950:                 my $newtxt = &Apache::loncommon::plainname($dcname,$dcdom);
16951:                 $resulttext .= '<li>'.&mt("$title{'xmldc'} set to [_1]",'<b>'.$newtxt.'</b>').'</li>'; 
16952:             }
16953:             $resulttext .= '</ul>';
16954:         } else {
16955:             $resulttext = &mt('No changes made to auto-creation settings');
16956:         }
16957:     } else {
16958:         $resulttext = '<span class="LC_error">'.
16959:             &mt('An error occurred: [_1]',$putresult).'</span>';
16960:     }
16961:     return $resulttext;
16962: }
16963: 
16964: sub modify_directorysrch {
16965:     my ($dom,$lastactref,%domconfig) = @_;
16966:     my ($resulttext,%changes);
16967:     my %currdirsrch;
16968:     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
16969:         foreach my $key (keys(%{$domconfig{'directorysrch'}})) {
16970:             $currdirsrch{$key} = $domconfig{'directorysrch'}{$key};
16971:         }
16972:     }
16973:     my %title = ( available => 'Institutional directory search available',
16974:                   localonly => 'Other domains can search institution',
16975:                   lcavailable => 'LON-CAPA directory search available',
16976:                   lclocalonly => 'Other domains can search LON-CAPA domain',
16977:                   searchby => 'Search types',
16978:                   searchtypes => 'Search latitude');
16979:     my @offon = ('off','on');
16980:     my @otherdoms = ('Yes','No');
16981: 
16982:     my @searchtypes = &Apache::loncommon::get_env_multiple('form.searchtypes');  
16983:     my @cansearch = &Apache::loncommon::get_env_multiple('form.cansearch');
16984:     my @searchby = &Apache::loncommon::get_env_multiple('form.searchby');
16985: 
16986:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
16987:     if (keys(%{$usertypes}) == 0) {
16988:         @cansearch = ('default');
16989:     } else {
16990:         if (ref($currdirsrch{'cansearch'}) eq 'ARRAY') {
16991:             foreach my $type (@{$currdirsrch{'cansearch'}}) {
16992:                 if (!grep(/^\Q$type\E$/,@cansearch)) {
16993:                     push(@{$changes{'cansearch'}},$type);
16994:                 }
16995:             }
16996:             foreach my $type (@cansearch) {
16997:                 if (!grep(/^\Q$type\E$/,@{$currdirsrch{'cansearch'}})) {
16998:                     push(@{$changes{'cansearch'}},$type);
16999:                 }
17000:             }
17001:         } else {
17002:             push(@{$changes{'cansearch'}},@cansearch);
17003:         }
17004:     }
17005: 
17006:     if (ref($currdirsrch{'searchby'}) eq 'ARRAY') {
17007:         foreach my $by (@{$currdirsrch{'searchby'}}) {
17008:             if (!grep(/^\Q$by\E$/,@searchby)) {
17009:                 push(@{$changes{'searchby'}},$by);
17010:             }
17011:         }
17012:         foreach my $by (@searchby) {
17013:             if (!grep(/^\Q$by\E$/,@{$currdirsrch{'searchby'}})) {
17014:                 push(@{$changes{'searchby'}},$by);
17015:             }
17016:         }
17017:     } else {
17018:         push(@{$changes{'searchby'}},@searchby);
17019:     }
17020: 
17021:     if (ref($currdirsrch{'searchtypes'}) eq 'ARRAY') {
17022:         foreach my $type (@{$currdirsrch{'searchtypes'}}) {
17023:             if (!grep(/^\Q$type\E$/,@searchtypes)) {
17024:                 push(@{$changes{'searchtypes'}},$type);
17025:             }
17026:         }
17027:         foreach my $type (@searchtypes) {
17028:             if (!grep(/^\Q$type\E$/,@{$currdirsrch{'searchtypes'}})) {
17029:                 push(@{$changes{'searchtypes'}},$type);
17030:             }
17031:         }
17032:     } else {
17033:         if (exists($currdirsrch{'searchtypes'})) {
17034:             foreach my $type (@searchtypes) {  
17035:                 if ($type ne $currdirsrch{'searchtypes'}) { 
17036:                     push(@{$changes{'searchtypes'}},$type);
17037:                 }
17038:             }
17039:             if (!grep(/^\Q$currdirsrch{'searchtypes'}\E/,@searchtypes)) {
17040:                 push(@{$changes{'searchtypes'}},$currdirsrch{'searchtypes'});
17041:             }   
17042:         } else {
17043:             push(@{$changes{'searchtypes'}},@searchtypes); 
17044:         }
17045:     }
17046: 
17047:     my %dirsrch_hash =  (
17048:             directorysrch => { available => $env{'form.dirsrch_available'},
17049:                                cansearch => \@cansearch,
17050:                                localonly => $env{'form.dirsrch_instlocalonly'},
17051:                                lclocalonly => $env{'form.dirsrch_domlocalonly'},
17052:                                lcavailable => $env{'form.dirsrch_domavailable'},
17053:                                searchby => \@searchby,
17054:                                searchtypes => \@searchtypes,
17055:                              }
17056:             );
17057:     my $putresult = &Apache::lonnet::put_dom('configuration',\%dirsrch_hash,
17058:                                              $dom);
17059:     if ($putresult eq 'ok') {
17060:         if (exists($currdirsrch{'available'})) {
17061:              if ($currdirsrch{'available'} ne $env{'form.dirsrch_available'}) {
17062:                  $changes{'available'} = 1;
17063:              }
17064:         } else {
17065:             if ($env{'form.dirsrch_available'} eq '1') {
17066:                 $changes{'available'} = 1;
17067:             }
17068:         }
17069:         if (exists($currdirsrch{'lcavailable'})) {
17070:             if ($currdirsrch{'lcavailable'} ne $env{'form.dirsrch_domavailable'}) {
17071:                 $changes{'lcavailable'} = 1;
17072:             }
17073:         } else {
17074:             if ($env{'form.dirsrch_lcavailable'} eq '1') {
17075:                 $changes{'lcavailable'} = 1;
17076:             }
17077:         }
17078:         if (exists($currdirsrch{'localonly'})) {
17079:             if ($currdirsrch{'localonly'} ne $env{'form.dirsrch_instlocalonly'}) {
17080:                 $changes{'localonly'} = 1;
17081:             }
17082:         } else {
17083:             if ($env{'form.dirsrch_instlocalonly'} eq '1') {
17084:                 $changes{'localonly'} = 1;
17085:             }
17086:         }
17087:         if (exists($currdirsrch{'lclocalonly'})) {
17088:             if ($currdirsrch{'lclocalonly'} ne $env{'form.dirsrch_domlocalonly'}) {
17089:                 $changes{'lclocalonly'} = 1;
17090:             }
17091:         } else {
17092:             if ($env{'form.dirsrch_domlocalonly'} eq '1') {
17093:                 $changes{'lclocalonly'} = 1;
17094:             }
17095:         }
17096:         if (keys(%changes) > 0) {
17097:             $resulttext = &mt('Changes made:').'<ul>';
17098:             if ($changes{'available'}) {
17099:                 $resulttext .= '<li>'.&mt("$title{'available'} set to: $offon[$env{'form.dirsrch_available'}]").'</li>';
17100:             }
17101:             if ($changes{'lcavailable'}) {
17102:                 $resulttext .= '<li>'.&mt("$title{'lcavailable'} set to: $offon[$env{'form.dirsrch_domavailable'}]").'</li>';
17103:             }
17104:             if ($changes{'localonly'}) {
17105:                 $resulttext .= '<li>'.&mt("$title{'localonly'} set to: $otherdoms[$env{'form.dirsrch_instlocalonly'}]").'</li>';
17106:             }
17107:             if ($changes{'lclocalonly'}) {
17108:                 $resulttext .= '<li>'.&mt("$title{'lclocalonly'} set to: $otherdoms[$env{'form.dirsrch_domlocalonly'}]").'</li>';
17109:             }
17110:             if (ref($changes{'cansearch'}) eq 'ARRAY') {
17111:                 my $chgtext;
17112:                 if (ref($usertypes) eq 'HASH') {
17113:                     if (keys(%{$usertypes}) > 0) {
17114:                         foreach my $type (@{$types}) {
17115:                             if (grep(/^\Q$type\E$/,@cansearch)) {
17116:                                 $chgtext .= $usertypes->{$type}.'; ';
17117:                             }
17118:                         }
17119:                         if (grep(/^default$/,@cansearch)) {
17120:                             $chgtext .= $othertitle;
17121:                         } else {
17122:                             $chgtext =~ s/\; $//;
17123:                         }
17124:                         $resulttext .=
17125:                             '<li>'.
17126:                             &mt("Users from domain '[_1]' permitted to search the institutional directory set to: [_2]",
17127:                                 '<span class="LC_cusr_emph">'.$dom.'</span>',$chgtext).
17128:                             '</li>';
17129:                     }
17130:                 }
17131:             }
17132:             if (ref($changes{'searchby'}) eq 'ARRAY') {
17133:                 my ($searchtitles,$titleorder) = &sorted_searchtitles();
17134:                 my $chgtext;
17135:                 foreach my $type (@{$titleorder}) {
17136:                     if (grep(/^\Q$type\E$/,@searchby)) {
17137:                         if (defined($searchtitles->{$type})) {
17138:                             $chgtext .= $searchtitles->{$type}.'; ';
17139:                         }
17140:                     }
17141:                 }
17142:                 $chgtext =~ s/\; $//;
17143:                 $resulttext .= '<li>'.&mt("$title{'searchby'} set to: [_1]",$chgtext).'</li>';
17144:             }
17145:             if (ref($changes{'searchtypes'}) eq 'ARRAY') {
17146:                 my ($srchtypes_desc,$srchtypeorder) = &sorted_searchtypes(); 
17147:                 my $chgtext;
17148:                 foreach my $type (@{$srchtypeorder}) {
17149:                     if (grep(/^\Q$type\E$/,@searchtypes)) {
17150:                         if (defined($srchtypes_desc->{$type})) {
17151:                             $chgtext .= $srchtypes_desc->{$type}.'; ';
17152:                         }
17153:                     }
17154:                 }
17155:                 $chgtext =~ s/\; $//;
17156:                 $resulttext .= '<li>'.&mt($title{'searchtypes'}.' set to: "[_1]"',$chgtext).'</li>';
17157:             }
17158:             $resulttext .= '</ul>';
17159:             &Apache::lonnet::do_cache_new('directorysrch',$dom,$dirsrch_hash{'directorysrch'},3600);
17160:             if (ref($lastactref) eq 'HASH') {
17161:                 $lastactref->{'directorysrch'} = 1;
17162:             }
17163:         } else {
17164:             $resulttext = &mt('No changes made to directory search settings');
17165:         }
17166:     } else {
17167:         $resulttext = '<span class="LC_error">'.
17168:                       &mt('An error occurred: [_1]',$putresult).'</span>';
17169:     }
17170:     return $resulttext;
17171: }
17172: 
17173: sub modify_contacts {
17174:     my ($dom,$lastactref,%domconfig) = @_;
17175:     my ($resulttext,%currsetting,%newsetting,%changes,%contacts_hash);
17176:     if (ref($domconfig{'contacts'}) eq 'HASH') {
17177:         foreach my $key (keys(%{$domconfig{'contacts'}})) {
17178:             $currsetting{$key} = $domconfig{'contacts'}{$key};
17179:         }
17180:     }
17181:     my (%others,%to,%bcc,%includestr,%includeloc);
17182:     my @contacts = ('supportemail','adminemail');
17183:     my @mailings = ('errormail','packagesmail','helpdeskmail','otherdomsmail',
17184:                     'lonstatusmail','requestsmail','updatesmail','idconflictsmail','hostipmail');
17185:     my @toggles = ('reporterrors','reportupdates','reportstatus');
17186:     my @lonstatus = ('threshold','sysmail','weights','excluded');
17187:     my ($fields,$fieldtitles,$fieldoptions,$possoptions) = &helpform_fields();
17188:     foreach my $type (@mailings) {
17189:         @{$newsetting{$type}} = 
17190:             &Apache::loncommon::get_env_multiple('form.'.$type);
17191:         foreach my $item (@contacts) {
17192:             if (grep(/^\Q$item\E$/,@{$newsetting{$type}})) {
17193:                 $contacts_hash{contacts}{$type}{$item} = 1;
17194:             } else {
17195:                 $contacts_hash{contacts}{$type}{$item} = 0;
17196:             }
17197:         }
17198:         $others{$type} = $env{'form.'.$type.'_others'};
17199:         $contacts_hash{contacts}{$type}{'others'} = $others{$type};
17200:         if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17201:             $bcc{$type} = $env{'form.'.$type.'_bcc'};
17202:             $contacts_hash{contacts}{$type}{'bcc'} = $bcc{$type};
17203:             if (($env{'form.'.$type.'_includestr'} ne '') && ($env{'form.'.$type.'_includeloc'} =~ /^s|b$/)) {
17204:                 $includestr{$type} = $env{'form.'.$type.'_includestr'};
17205:                 $includeloc{$type} = $env{'form.'.$type.'_includeloc'};
17206:                 $contacts_hash{contacts}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17207:             }
17208:         }
17209:     }
17210:     foreach my $item (@contacts) {
17211:         $to{$item} = $env{'form.'.$item};
17212:         $contacts_hash{'contacts'}{$item} = $to{$item};
17213:     }
17214:     foreach my $item (@toggles) {
17215:         if ($env{'form.'.$item} =~ /^(0|1)$/) {
17216:             $contacts_hash{'contacts'}{$item} = $env{'form.'.$item};
17217:         }
17218:     }
17219:     my ($lonstatus_defs,$lonstatus_names) = &Apache::loncommon::lon_status_items();
17220:     foreach my $item (@lonstatus) {
17221:         if ($item eq 'excluded') {
17222:             my (%serverhomes,@excluded);
17223:             map { $serverhomes{$_} = 1; } values(%Apache::lonnet::serverhomeIDs);
17224:             my @possexcluded = &Apache::loncommon::get_env_multiple('form.errorexcluded');
17225:             if (@possexcluded) {
17226:                 foreach my $id (sort(@possexcluded)) {
17227:                     if ($serverhomes{$id}) {
17228:                         push(@excluded,$id);
17229:                     }
17230:                 }
17231:             }
17232:             if (@excluded) {
17233:                 $contacts_hash{'contacts'}{'lonstatus'}{$item} = \@excluded;
17234:             }
17235:         } elsif ($item eq 'weights') {
17236:             foreach my $type ('E','W','N','U') {
17237:                 $env{'form.error'.$item.'_'.$type} =~ s/^\s+|\s+$//g;
17238:                 if ($env{'form.error'.$item.'_'.$type} =~ /^\d+$/) {
17239:                     unless ($env{'form.error'.$item.'_'.$type} == $lonstatus_defs->{$type}) {
17240:                         $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type} =
17241:                             $env{'form.error'.$item.'_'.$type};
17242:                     }
17243:                 }
17244:             }
17245:         } elsif (($item eq 'threshold') || ($item eq 'sysmail')) {
17246:             $env{'form.error'.$item} =~ s/^\s+|\s+$//g;
17247:             if ($env{'form.error'.$item} =~ /^\d+$/) {
17248:                 unless ($env{'form.error'.$item} == $lonstatus_defs->{$item}) {
17249:                     $contacts_hash{'contacts'}{'lonstatus'}{$item} = $env{'form.error'.$item};
17250:                 }
17251:             }
17252:         }
17253:     }
17254:     if ((ref($fields) eq 'ARRAY') && (ref($possoptions) eq 'HASH')) {
17255:         foreach my $field (@{$fields}) {
17256:             if (ref($possoptions->{$field}) eq 'ARRAY') {
17257:                 my $value = $env{'form.helpform_'.$field};
17258:                 $value =~ s/^\s+|\s+$//g;
17259:                 if (grep(/^\Q$value\E$/,@{$possoptions->{$field}})) {
17260:                     $contacts_hash{'contacts'}{'helpform'}{$field} = $value;
17261:                     if ($field eq 'screenshot') {
17262:                         $env{'form.helpform_maxsize'} =~ s/^\s+|\s+$//g;
17263:                         if ($env{'form.helpform_maxsize'} =~ /^\d+\.?\d*$/) {
17264:                             $contacts_hash{'contacts'}{'helpform'}{'maxsize'} = $env{'form.helpform_maxsize'};
17265:                         }
17266:                     }
17267:                 }
17268:             }
17269:         }
17270:     }
17271:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17272:     my (@statuses,%usertypeshash,@overrides);
17273:     if ((ref($types) eq 'ARRAY') && (@{$types} > 0)) {
17274:         @statuses = @{$types};
17275:         if (ref($usertypes) eq 'HASH') {
17276:             %usertypeshash = %{$usertypes};
17277:         }
17278:     }
17279:     if (@statuses) {
17280:         my @possoverrides = &Apache::loncommon::get_env_multiple('form.overrides');
17281:         foreach my $type (@possoverrides) {
17282:             if (($type ne '') && (grep(/^\Q$type\E$/,@statuses))) {
17283:                 push(@overrides,$type);
17284:             }
17285:         }
17286:         if (@overrides) {
17287:             foreach my $type (@overrides) {
17288:                 my @standard = &Apache::loncommon::get_env_multiple('form.override_'.$type);
17289:                 foreach my $item (@contacts) {
17290:                     if (grep(/^\Q$item\E$/,@standard)) {
17291:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 1;
17292:                         $newsetting{'override_'.$type}{$item} = 1;
17293:                     } else {
17294:                         $contacts_hash{'contacts'}{'overrides'}{$type}{$item} = 0;
17295:                         $newsetting{'override_'.$type}{$item} = 0;
17296:                     }
17297:                 }
17298:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'others'} = $env{'form.override_'.$type.'_others'};
17299:                 $contacts_hash{'contacts'}{'overrides'}{$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17300:                 $newsetting{'override_'.$type}{'others'} = $env{'form.override_'.$type.'_others'};
17301:                 $newsetting{'override_'.$type}{'bcc'} = $env{'form.override_'.$type.'_bcc'};
17302:                 if (($env{'form.override_'.$type.'_includestr'} ne '') && ($env{'form.override_'.$type.'_includeloc'} =~ /^s|b$/)) {
17303:                     $includestr{$type} = $env{'form.override_'.$type.'_includestr'};
17304:                     $includeloc{$type} = $env{'form.override_'.$type.'_includeloc'};
17305:                     $contacts_hash{'contacts'}{'overrides'}{$type}{'include'} = $includeloc{$type}.':'.&escape($includestr{$type});
17306:                     $newsetting{'override_'.$type}{'include'} = $contacts_hash{'contacts'}{'overrides'}{$type}{'include'};
17307:                 }
17308:             }     
17309:         }
17310:     }
17311:     if (keys(%currsetting) > 0) {
17312:         foreach my $item (@contacts) {
17313:             if ($to{$item} ne $currsetting{$item}) {
17314:                 $changes{$item} = 1;
17315:             }
17316:         }
17317:         foreach my $type (@mailings) {
17318:             foreach my $item (@contacts) {
17319:                 if (ref($currsetting{$type}) eq 'HASH') {
17320:                     if ($currsetting{$type}{$item} ne $contacts_hash{contacts}{$type}{$item}) {
17321:                         push(@{$changes{$type}},$item);
17322:                     }
17323:                 } else {
17324:                     push(@{$changes{$type}},@{$newsetting{$type}});
17325:                 }
17326:             }
17327:             if ($others{$type} ne $currsetting{$type}{'others'}) {
17328:                 push(@{$changes{$type}},'others');
17329:             }
17330:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17331:                 if ($bcc{$type} ne $currsetting{$type}{'bcc'}) {
17332:                     push(@{$changes{$type}},'bcc'); 
17333:                 }
17334:                 my ($currloc,$currstr) = split(/:/,$currsetting{$type}{'include'},2);
17335:                 if (($includeloc{$type} ne $currloc) || (&escape($includestr{$type}) ne $currstr)) {
17336:                     push(@{$changes{$type}},'include');
17337:                 }
17338:             }
17339:         }
17340:         if (ref($fields) eq 'ARRAY') {
17341:             if (ref($currsetting{'helpform'}) eq 'HASH') {
17342:                 foreach my $field (@{$fields}) {
17343:                     if ($currsetting{'helpform'}{$field} ne $contacts_hash{'contacts'}{'helpform'}{$field}) {
17344:                         push(@{$changes{'helpform'}},$field);
17345:                     }
17346:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17347:                         if ($currsetting{'helpform'}{'maxsize'} ne $contacts_hash{'contacts'}{'helpform'}{'maxsize'}) {
17348:                             push(@{$changes{'helpform'}},'maxsize');
17349:                         }
17350:                     }
17351:                 }
17352:             } else {
17353:                 foreach my $field (@{$fields}) {
17354:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17355:                         push(@{$changes{'helpform'}},$field);
17356:                     }
17357:                     if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17358:                         if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17359:                             push(@{$changes{'helpform'}},'maxsize');
17360:                         }
17361:                     }
17362:                 }
17363:             }
17364:         }
17365:         if (@statuses) {
17366:             if (ref($currsetting{'overrides'}) eq 'HASH') { 
17367:                 foreach my $key (keys(%{$currsetting{'overrides'}})) {
17368:                     if (ref($currsetting{'overrides'}{$key}) eq 'HASH') {
17369:                         if (ref($newsetting{'override_'.$key}) eq 'HASH') {
17370:                             foreach my $item (@contacts,'bcc','others','include') {
17371:                                 if ($currsetting{'overrides'}{$key}{$item} ne $newsetting{'override_'.$key}{$item}) { 
17372:                                     push(@{$changes{'overrides'}},$key);
17373:                                     last;
17374:                                 }
17375:                             }
17376:                         } else {
17377:                             push(@{$changes{'overrides'}},$key);
17378:                         }
17379:                     }
17380:                 }
17381:                 foreach my $key (@overrides) {
17382:                     unless (exists($currsetting{'overrides'}{$key})) {
17383:                         push(@{$changes{'overrides'}},$key);
17384:                     }
17385:                 }
17386:             } else {
17387:                 foreach my $key (@overrides) {
17388:                     push(@{$changes{'overrides'}},$key); 
17389:                 }
17390:             }
17391:         }
17392:         if (ref($currsetting{'lonstatus'}) eq 'HASH') {
17393:             foreach my $key ('excluded','weights','threshold','sysmail') {
17394:                 if ($key eq 'excluded') {
17395:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17396:                         (ref($contacts_hash{contacts}{lonstatus}{excluded}) eq 'ARRAY')) {
17397:                         if ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17398:                             (@{$currsetting{'lonstatus'}{$key}})) {
17399:                             my @diffs =
17400:                                 &Apache::loncommon::compare_arrays($contacts_hash{contacts}{lonstatus}{excluded},
17401:                                                                    $currsetting{'lonstatus'}{$key});
17402:                             if (@diffs) {
17403:                                 push(@{$changes{'lonstatus'}},$key);
17404:                             }
17405:                         } elsif (@{$contacts_hash{contacts}{lonstatus}{excluded}}) {
17406:                             push(@{$changes{'lonstatus'}},$key);
17407:                         }
17408:                     } elsif ((ref($currsetting{'lonstatus'}{$key}) eq 'ARRAY') &&
17409:                              (@{$currsetting{'lonstatus'}{$key}})) {
17410:                         push(@{$changes{'lonstatus'}},$key);
17411:                     }
17412:                 } elsif ($key eq 'weights') {
17413:                     if ((ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') &&
17414:                         (ref($contacts_hash{contacts}{lonstatus}{$key}) eq 'HASH')) {
17415:                         if (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17416:                             foreach my $type ('E','W','N','U') {
17417:                                 unless ($contacts_hash{contacts}{lonstatus}{$key}{$type} eq
17418:                                         $currsetting{'lonstatus'}{$key}{$type}) {
17419:                                     push(@{$changes{'lonstatus'}},$key);
17420:                                     last;
17421:                                 }
17422:                             }
17423:                         } else {
17424:                             foreach my $type ('E','W','N','U') {
17425:                                 if ($contacts_hash{contacts}{lonstatus}{$key}{$type} ne '') {
17426:                                     push(@{$changes{'lonstatus'}},$key);
17427:                                     last;
17428:                                 }
17429:                             }
17430:                         }
17431:                     } elsif (ref($currsetting{'lonstatus'}{$key}) eq 'HASH') {
17432:                         foreach my $type ('E','W','N','U') {
17433:                             if ($currsetting{'lonstatus'}{$key}{$type} ne '') {
17434:                                 push(@{$changes{'lonstatus'}},$key);
17435:                                 last;
17436:                             }
17437:                         }
17438:                     }
17439:                 } elsif (($key eq 'threshold') || ($key eq 'sysmail')) {
17440:                     if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17441:                         if ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17442:                             if ($currsetting{'lonstatus'}{$key} != $contacts_hash{contacts}{lonstatus}{$key}) {
17443:                                 push(@{$changes{'lonstatus'}},$key);
17444:                             }
17445:                         } elsif ($contacts_hash{contacts}{lonstatus}{$key} =~ /^\d+$/) {
17446:                             push(@{$changes{'lonstatus'}},$key);
17447:                         }
17448:                     } elsif ($currsetting{'lonstatus'}{$key} =~ /^\d+$/) {
17449:                         push(@{$changes{'lonstatus'}},$key);
17450:                     }
17451:                 }
17452:             }
17453:         } else {
17454:             if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17455:                 foreach my $key ('excluded','weights','threshold','sysmail') {
17456:                     if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17457:                         push(@{$changes{'lonstatus'}},$key);
17458:                     }
17459:                 }
17460:             }
17461:         }
17462:     } else {
17463:         my %default;
17464:         $default{'supportemail'} = $Apache::lonnet::perlvar{'lonSupportEMail'};
17465:         $default{'adminemail'} = $Apache::lonnet::perlvar{'lonAdmEMail'};
17466:         $default{'errormail'} = 'adminemail';
17467:         $default{'packagesmail'} = 'adminemail';
17468:         $default{'helpdeskmail'} = 'supportemail';
17469:         $default{'otherdomsmail'} = 'supportemail';
17470:         $default{'lonstatusmail'} = 'adminemail';
17471:         $default{'requestsmail'} = 'adminemail';
17472:         $default{'updatesmail'} = 'adminemail';
17473:         $default{'hostipmail'} = 'adminemail';
17474:         foreach my $item (@contacts) {
17475:            if ($to{$item} ne $default{$item}) {
17476:                $changes{$item} = 1;
17477:            }
17478:         }
17479:         foreach my $type (@mailings) {
17480:             if ((@{$newsetting{$type}} != 1) || ($newsetting{$type}[0] ne $default{$type})) {
17481:                 push(@{$changes{$type}},@{$newsetting{$type}});
17482:             }
17483:             if ($others{$type} ne '') {
17484:                 push(@{$changes{$type}},'others');
17485:             }
17486:             if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17487:                 if ($bcc{$type} ne '') {
17488:                     push(@{$changes{$type}},'bcc');
17489:                 }
17490:                 if (($includeloc{$type} =~ /^b|s$/) && ($includestr{$type} ne '')) {
17491:                     push(@{$changes{$type}},'include');
17492:                 }
17493:             }
17494:         }
17495:         if (ref($fields) eq 'ARRAY') {
17496:             foreach my $field (@{$fields}) {
17497:                 if ($contacts_hash{'contacts'}{'helpform'}{$field} ne 'yes') {
17498:                     push(@{$changes{'helpform'}},$field);
17499:                 }
17500:                 if (($field eq 'screenshot') && ($contacts_hash{'contacts'}{'helpform'}{'screenshot'} ne 'no')) {
17501:                     if ($contacts_hash{'contacts'}{'helpform'}{'maxsize'} != 1) {
17502:                         push(@{$changes{'helpform'}},'maxsize');
17503:                     }
17504:                 }
17505:             }
17506:         }
17507:         if (ref($contacts_hash{contacts}{lonstatus}) eq 'HASH') {
17508:             foreach my $key ('excluded','weights','threshold','sysmail') {
17509:                 if (exists($contacts_hash{contacts}{lonstatus}{$key})) {
17510:                     push(@{$changes{'lonstatus'}},$key);
17511:                 }
17512:             }
17513:         }
17514:     }
17515:     foreach my $item (@toggles) {
17516:         if (($env{'form.'.$item} == 1) && ($currsetting{$item} == 0)) {
17517:             $changes{$item} = 1;
17518:         } elsif ((!$env{'form.'.$item}) &&
17519:                  (($currsetting{$item} eq '') || ($currsetting{$item} == 1))) {
17520:             $changes{$item} = 1;
17521:         }
17522:     }
17523:     my $putresult = &Apache::lonnet::put_dom('configuration',\%contacts_hash,
17524:                                              $dom);
17525:     if ($putresult eq 'ok') {
17526:         if (keys(%changes) > 0) {
17527:             &Apache::loncommon::devalidate_domconfig_cache($dom);
17528:             if (ref($lastactref) eq 'HASH') {
17529:                 $lastactref->{'domainconfig'} = 1;
17530:             }
17531:             my ($titles,$short_titles)  = &contact_titles();
17532:             $resulttext = &mt('Changes made:').'<ul>';
17533:             foreach my $item (@contacts) {
17534:                 if ($changes{$item}) {
17535:                     $resulttext .= '<li>'.$titles->{$item}.
17536:                                     &mt(' set to: ').
17537:                                     '<span class="LC_cusr_emph">'.
17538:                                     $to{$item}.'</span></li>';
17539:                 }
17540:             }
17541:             foreach my $type (@mailings) {
17542:                 if (ref($changes{$type}) eq 'ARRAY') {
17543:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17544:                         $resulttext .= '<li>'.$titles->{$type}.' -- '.&mt('sent to').': ';
17545:                     } else {
17546:                         $resulttext .= '<li>'.$titles->{$type}.': ';
17547:                     }
17548:                     my @text;
17549:                     foreach my $item (@{$newsetting{$type}}) {
17550:                         push(@text,$short_titles->{$item});
17551:                     }
17552:                     if ($others{$type} ne '') {
17553:                         push(@text,$others{$type});
17554:                     }
17555:                     if (@text) {
17556:                         $resulttext .= '<span class="LC_cusr_emph">'.
17557:                                        join(', ',@text).'</span>';
17558:                     }
17559:                     if (($type eq 'helpdeskmail') || ($type eq 'otherdomsmail')) {
17560:                         if ($bcc{$type} ne '') {
17561:                             my $bcctext;
17562:                             if (@text) {
17563:                                 $bcctext = '&nbsp;'.&mt('with Bcc to');
17564:                             } else {
17565:                                 $bcctext = '(Bcc)';
17566:                             }
17567:                             $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$bcc{$type}.'</span>';
17568:                         } elsif (!@text) {
17569:                             $resulttext .= &mt('No one');
17570:                         }   
17571:                         if ($includestr{$type} ne '') {
17572:                             if ($includeloc{$type} eq 'b') {
17573:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail body:').' '.$includestr{$type};
17574:                             } elsif ($includeloc{$type} eq 's') {
17575:                                 $resulttext .= '<br />'.&mt('Text automatically added to e-mail subject:').' '.$includestr{$type};
17576:                             }
17577:                         }
17578:                     } elsif (!@text) {
17579:                         $resulttext .= &mt('No recipients');
17580:                     }
17581:                     $resulttext .= '</li>';
17582:                 }
17583:             }
17584:             if (ref($changes{'overrides'}) eq 'ARRAY') {
17585:                 my @deletions;
17586:                 foreach my $type (@{$changes{'overrides'}}) {
17587:                     if ($usertypeshash{$type}) {
17588:                         if (grep(/^\Q$type\E/,@overrides)) {
17589:                             $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation set for [_1]",
17590:                                                       $usertypeshash{$type}).'<ul><li>';
17591:                             if (ref($newsetting{'override_'.$type}) eq 'HASH') {
17592:                                 my @text;
17593:                                 foreach my $item (@contacts) {
17594:                                     if ($newsetting{'override_'.$type}{$item}) { 
17595:                                         push(@text,$short_titles->{$item});
17596:                                     }
17597:                                 }
17598:                                 if ($newsetting{'override_'.$type}{'others'} ne '') {
17599:                                     push(@text,$newsetting{'override_'.$type}{'others'});
17600:                                 }
17601:   
17602:                                 if (@text) {
17603:                                     $resulttext .= &mt('Helpdesk e-mail sent to: [_1]',
17604:                                                        '<span class="LC_cusr_emph">'.join(', ',@text).'</span>');
17605:                                 }
17606:                                 if ($newsetting{'override_'.$type}{'bcc'} ne '') {
17607:                                     my $bcctext;
17608:                                     if (@text) {
17609:                                         $bcctext = '&nbsp;'.&mt('with Bcc to');
17610:                                     } else {
17611:                                         $bcctext = '(Bcc)';
17612:                                     }
17613:                                     $resulttext .= $bcctext.': <span class="LC_cusr_emph">'.$newsetting{'override_'.$type}{'bcc'}.'</span>';
17614:                                 } elsif (!@text) {
17615:                                      $resulttext .= &mt('Helpdesk e-mail sent to no one');
17616:                                 }
17617:                                 $resulttext .= '</li>';
17618:                                 if ($newsetting{'override_'.$type}{'include'} ne '') {
17619:                                     my ($loc,$str) = split(/:/,$newsetting{'override_'.$type}{'include'});
17620:                                     if ($loc eq 'b') {
17621:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail body:').' '.&unescape($str).'</li>';
17622:                                     } elsif ($loc eq 's') {
17623:                                         $resulttext .= '<li>'.&mt('Text automatically added to e-mail subject:').' '.&unescape($str).'</li>';
17624:                                     }
17625:                                 }
17626:                             }
17627:                             $resulttext .= '</li></ul></li>';
17628:                         } else {
17629:                             push(@deletions,$usertypeshash{$type});
17630:                         }
17631:                     }
17632:                 }
17633:                 if (@deletions) {
17634:                     $resulttext .= '<li>'.&mt("Overrides based on requester's affiliation discontinued for: [_1]",
17635:                                               join(', ',@deletions)).'</li>';
17636:                 }
17637:             }
17638:             my @offon = ('off','on');
17639:             my $corelink = &core_link_msu();
17640:             if ($changes{'reporterrors'}) {
17641:                 $resulttext .= '<li>'.
17642:                                &mt('E-mail error reports to [_1] set to "'.
17643:                                    $offon[$env{'form.reporterrors'}].'".',
17644:                                    $corelink).
17645:                                '</li>';
17646:             }
17647:             if ($changes{'reportupdates'}) {
17648:                 $resulttext .= '<li>'.
17649:                                 &mt('E-mail record of completed LON-CAPA updates to [_1] set to "'.
17650:                                     $offon[$env{'form.reportupdates'}].'".',
17651:                                     $corelink).
17652:                                 '</li>';
17653:             }
17654:             if ($changes{'reportstatus'}) {
17655:                 $resulttext .= '<li>'.
17656:                                 &mt('E-mail status if errors above threshold to [_1] set to "'.
17657:                                     $offon[$env{'form.reportstatus'}].'".',
17658:                                     $corelink).
17659:                                 '</li>';
17660:             }
17661:             if (ref($changes{'lonstatus'}) eq 'ARRAY') {
17662:                 $resulttext .= '<li>'.
17663:                                &mt('Nightly status check e-mail settings').':<ul>';
17664:                 my (%defval,%use_def,%shown);
17665:                 $defval{'threshold'} = $lonstatus_defs->{'threshold'};
17666:                 $defval{'sysmail'} = $lonstatus_defs->{'sysmail'};
17667:                 $defval{'weights'} =
17668:                     join(', ',map { $lonstatus_names->{$_}.'='.$lonstatus_defs->{$_}; } ('E','W','N','U'));
17669:                 $defval{'excluded'} = &mt('None');
17670:                 if (ref($contacts_hash{'contacts'}{'lonstatus'}) eq 'HASH') {
17671:                     foreach my $item ('threshold','sysmail','weights','excluded') {
17672:                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item})) {
17673:                             if (($item eq 'threshold') || ($item eq 'sysmail')) {
17674:                                 $shown{$item} = $contacts_hash{'contacts'}{'lonstatus'}{$item};
17675:                             } elsif ($item eq 'weights') {
17676:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'HASH') {
17677:                                     foreach my $type ('E','W','N','U') {
17678:                                         $shown{$item} .= $lonstatus_names->{$type}.'=';
17679:                                         if (exists($contacts_hash{'contacts'}{'lonstatus'}{$item}{$type})) {
17680:                                             $shown{$item} .= $contacts_hash{'contacts'}{'lonstatus'}{$item}{$type};
17681:                                         } else {
17682:                                             $shown{$item} .= $lonstatus_defs->{$type};
17683:                                         }
17684:                                         $shown{$item} .= ', ';
17685:                                     }
17686:                                     $shown{$item} =~ s/, $//;
17687:                                 } else {
17688:                                     $shown{$item} = $defval{$item};
17689:                                 }
17690:                             } elsif ($item eq 'excluded') {
17691:                                 if (ref($contacts_hash{'contacts'}{'lonstatus'}{$item}) eq 'ARRAY') {
17692:                                     $shown{$item} = join(', ',@{$contacts_hash{'contacts'}{'lonstatus'}{$item}});
17693:                                 } else {
17694:                                     $shown{$item} = $defval{$item};
17695:                                 }
17696:                             }
17697:                         } else {
17698:                             $shown{$item} = $defval{$item};
17699:                         }
17700:                     }
17701:                 } else {
17702:                     foreach my $item ('threshold','weights','excluded','sysmail') {
17703:                         $shown{$item} = $defval{$item};
17704:                     }
17705:                 }
17706:                 foreach my $item ('threshold','weights','excluded','sysmail') {
17707:                     $resulttext .= '<li>'.&mt($titles->{'error'.$item}.' -- [_1]',
17708:                                           $shown{$item}).'</li>';
17709:                 }
17710:                 $resulttext .= '</ul></li>';
17711:             }
17712:             if ((ref($changes{'helpform'}) eq 'ARRAY') && (ref($fields) eq 'ARRAY')) {
17713:                 my (@optional,@required,@unused,$maxsizechg);
17714:                 foreach my $field (@{$changes{'helpform'}}) {
17715:                     if ($field eq 'maxsize') {
17716:                         $maxsizechg = 1;
17717:                         next;
17718:                     }
17719:                     if ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'yes') {
17720:                         push(@optional,$field);
17721:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'no') {
17722:                         push(@unused,$field);
17723:                     } elsif ($contacts_hash{'contacts'}{'helpform'}{$field} eq 'req') {
17724:                         push(@required,$field);
17725:                     }
17726:                 }
17727:                 if (@optional) {
17728:                     $resulttext .= '<li>'.
17729:                                    &mt('Help form fields changed to "Optional": [_1].',
17730:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @optional)).'</span>'.
17731:                                    '</li>';
17732:                 }
17733:                 if (@required) {
17734:                     $resulttext .= '<li>'.
17735:                                    &mt('Help form fields changed to "Required": [_1].',
17736:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @required)).'</span>'.
17737:                                    '</li>';
17738:                 }
17739:                 if (@unused) {
17740:                     $resulttext .= '<li>'.
17741:                                    &mt('Help form fields changed to "Not shown": [_1].',
17742:                                        '<span class="LC_cusr_emph">'.join(', ',map { $fieldtitles->{$_}; } @unused)).'</span>'.
17743:                                    '</li>';
17744:                 }
17745:                 if ($maxsizechg) {
17746:                     $resulttext .= '<li>'.
17747:                                    &mt('Max size for file uploaded to help form by logged-in user set to [_1] MB.',
17748:                                        $contacts_hash{'contacts'}{'helpform'}{'maxsize'}).
17749:                                    '</li>';
17750:                 }
17751:             }
17752:             $resulttext .= '</ul>';
17753:         } else {
17754:             $resulttext = &mt('No changes made to contacts and form settings');
17755:         }
17756:     } else {
17757:         $resulttext = '<span class="LC_error">'.
17758:             &mt('An error occurred: [_1].',$putresult).'</span>';
17759:     }
17760:     return $resulttext;
17761: }
17762: 
17763: sub modify_privacy {
17764:     my ($dom,%domconfig) = @_;
17765:     my ($resulttext,%current,%changes);
17766:     if (ref($domconfig{'privacy'}) eq 'HASH') {
17767:         %current = %{$domconfig{'privacy'}};
17768:     }
17769:     my @fields = ('lastname','firstname','middlename','generation','permanentemail','id');
17770:     my @items = ('domain','author','course','community');
17771:     my %names = &Apache::lonlocal::texthash (
17772:                    domain => 'Assigned domain role(s)',
17773:                    author => 'Assigned co-author role(s)',
17774:                    course => 'Assigned course role(s)',
17775:                    community => 'Assigned community role',
17776:                 );
17777:     my %roles = &Apache::lonlocal::texthash (
17778:                    domain => 'Domain role',
17779:                    author => 'Co-author role',
17780:                    course => 'Course role',
17781:                    community => 'Community role',
17782:                 );
17783:     my %titles = &Apache::lonlocal::texthash (
17784:                   approval => 'Approval for role in different domain',
17785:                   othdom   => 'User information available in other domain',
17786:                   priv     => 'Information viewable by privileged user in same domain',
17787:                   unpriv   => 'Information viewable by unprivileged user in same domain',
17788:                   instdom  => 'Other domain shares institution/provider',
17789:                   extdom   => 'Other domain has different institution/provider',
17790:                   none     => 'Not allowed',
17791:                   user     => 'User authorizes',
17792:                   domain   => 'Domain Coordinator authorizes',
17793:                   auto     => 'Unrestricted',
17794:     );
17795:     my %fieldnames = &Apache::lonlocal::texthash (
17796:                         id => 'Student/Employee ID',
17797:                         permanentemail => 'E-mail address',
17798:                         lastname => 'Last Name',
17799:                         firstname => 'First Name',
17800:                         middlename => 'Middle Name',
17801:                         generation => 'Generation',
17802:     );
17803:     my ($othertitle,$usertypes,$types) =
17804:         &Apache::loncommon::sorted_inst_types($dom);
17805:     my (%by_ip,%by_location,@intdoms,@instdoms);
17806:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
17807: 
17808:     my %privacyhash = (
17809:                        'approval' => {
17810:                                        instdom => {},
17811:                                        extdom  => {},
17812:                                      },
17813:                        'othdom'   => {},
17814:                        'priv'     => {},
17815:                        'unpriv'   => {},
17816:                       );
17817:     foreach my $item (@items) {
17818:         if (@instdoms > 1) {
17819:             if ($env{'form.privacy_approval_instdom'.$item} =~ /^(none|user|domain|auto)$/) {
17820:                 $privacyhash{'approval'}{'instdom'}{$item} = $env{'form.privacy_approval_instdom_'.$item};
17821:             }
17822:             if (ref($current{'approval'}) eq 'HASH') {
17823:                 if (ref($current{'approval'}{'instdom'}) eq 'HASH') {
17824:                     unless ($privacyhash{'approval'}{'instdom'}{$item} eq $current{'approval'}{'instdom'}{$item}) {
17825:                         $changes{'approval'} = 1;
17826:                     }
17827:                 }
17828:             } elsif ($privacyhash{'approval'}{'instdom'}{$item} ne 'auto') {
17829:                 $changes{'approval'} = 1;
17830:             }
17831:         }
17832:         if (keys(%by_location) > 0) {
17833:             if ($env{'form.privacy_approval_extdom_'.$item} =~ /^(none|user|domain|auto)$/) {
17834:                 $privacyhash{'approval'}{'extdom'}{$item} = $env{'form.privacy_approval_extdom_'.$item};
17835:             }
17836:             if (ref($current{'approval'}) eq 'HASH') {
17837:                 if (ref($current{'approval'}{'extdom'}) eq 'HASH') {
17838:                     unless ($privacyhash{'approval'}{'extdom'}{$item} eq $current{'approval'}{'extdom'}{$item}) {
17839:                         $changes{'approval'} = 1;
17840:                     }
17841:                 }
17842:             } elsif ($privacyhash{'approval'}{'extdom'}{$item} ne 'auto') {
17843:                 $changes{'approval'} = 1;
17844:             }
17845:         }
17846:         foreach my $status ('priv','unpriv') {
17847:             my @possibles = sort(&Apache::loncommon::get_env_multiple('form.privacy_'.$status.'_'.$item));
17848:             my @newvalues;
17849:             foreach my $field (@possibles) {
17850:                 if (grep(/^\Q$field\E$/,@fields)) {
17851:                     $privacyhash{$status}{$item}{$field} = 1;
17852:                     push(@newvalues,$field);
17853:                 }
17854:             }
17855:             @newvalues = sort(@newvalues);
17856:             if (ref($current{$status}) eq 'HASH') {
17857:                 if (ref($current{$status}{$item}) eq 'HASH') {
17858:                     my @currvalues = sort(keys(%{$current{$status}{$item}}));
17859:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17860:                     if (@diffs > 0) {
17861:                         $changes{$status} = 1;
17862:                     }
17863:                 }
17864:             } else {
17865:                 my @stdfields;
17866:                 foreach my $field (@fields) {
17867:                     if ($field eq 'id') {
17868:                         next if ($status eq 'unpriv');
17869:                         next if (($status eq 'priv') && ($item eq 'community'));
17870:                     }
17871:                     push(@stdfields,$field);
17872:                 }
17873:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
17874:                 if (@diffs > 0) {
17875:                     $changes{$status} = 1;
17876:                 }
17877:             }
17878:         }
17879:     }
17880:     if ((@instdoms > 1) || (keys(%by_location) > 0)) {
17881:         my @statuses;
17882:         if (ref($types) eq 'ARRAY') {
17883:             @statuses = @{$types};
17884:         }
17885:         foreach my $type (@statuses,'default') {
17886:             my @possfields = &Apache::loncommon::get_env_multiple('form.privacy_othdom_'.$type);
17887:             my @newvalues;
17888:             foreach my $field (sort(@possfields)) {
17889:                 if (grep(/^\Q$field\E$/,@fields)) {
17890:                     $privacyhash{'othdom'}{$type}{$field} = 1;
17891:                     push(@newvalues,$field);
17892:                 }
17893:             }
17894:             @newvalues = sort(@newvalues);
17895:             if (ref($current{'othdom'}) eq 'HASH') {
17896:                 if (ref($current{'othdom'}{$type}) eq 'HASH') {
17897:                     my @currvalues = sort(keys(%{$current{'othdom'}{$type}}));
17898:                     my @diffs = &Apache::loncommon::compare_arrays(\@currvalues,\@newvalues);
17899:                     if (@diffs > 0) {
17900:                         $changes{'othdom'} = 1;
17901:                     }
17902:                 }
17903:             } else {
17904:                 my @stdfields = ('lastname','firstname','middlename','generation','permanentemail');
17905:                 my @diffs = &Apache::loncommon::compare_arrays(\@stdfields,\@newvalues);
17906:                 if (@diffs > 0) {
17907:                     $changes{'othdom'} = 1;
17908:                 }
17909:             }
17910:         }
17911:     }
17912:     my %confighash = (
17913:                         privacy => \%privacyhash,
17914:                      );
17915:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
17916:     if ($putresult eq 'ok') {
17917:         if (keys(%changes) > 0) {
17918:             $resulttext = &mt('Changes made: ').'<ul>';
17919:             foreach my $key ('approval','othdom','priv','unpriv') {
17920:                 if ($changes{$key}) {
17921:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
17922:                     if ($key eq 'approval') {
17923:                         if (keys(%{$privacyhash{$key}{instdom}})) {
17924:                             $resulttext .= '<li>'.$titles{'instdom'}.'<ul>';
17925:                             foreach my $item (@items) {
17926:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{instdom}{$item}}.'</li>';
17927:                             }
17928:                             $resulttext .= '</ul></li>';
17929:                         }
17930:                         if (keys(%{$privacyhash{$key}{extdom}})) {
17931:                             $resulttext .= '<li>'.$titles{'extdom'}.'<ul>';
17932:                             foreach my $item (@items) {
17933:                                 $resulttext .=  '<li>'.$roles{$item}.': '.$titles{$privacyhash{$key}{extdom}{$item}}.'</li>';
17934:                             }
17935:                             $resulttext .= '</ul></li>';
17936:                         }
17937:                     } elsif ($key eq 'othdom') {
17938:                         my @statuses;
17939:                         if (ref($types) eq 'ARRAY') {
17940:                             @statuses = @{$types};
17941:                         }
17942:                         if (ref($privacyhash{$key}) eq 'HASH') {
17943:                             foreach my $status (@statuses,'default') {
17944:                                 if ($status eq 'default') {
17945:                                     $resulttext .= '<li>'.$othertitle.': ';
17946:                                 } elsif (ref($usertypes) eq 'HASH') {
17947:                                     $resulttext .= '<li>'.$usertypes->{$status}.': ';
17948:                                 } else {
17949:                                     next;
17950:                                 }
17951:                                 if (ref($privacyhash{$key}{$status}) eq 'HASH') {
17952:                                     if (keys(%{$privacyhash{$key}{$status}})) {
17953:                                         $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$status}}))));
17954:                                     } else {
17955:                                         $resulttext .= &mt('none');
17956:                                     }
17957:                                 }
17958:                                 $resulttext .= '</li>';
17959:                             }
17960:                         }
17961:                     } else {
17962:                         foreach my $item (@items) {
17963:                             if (ref($privacyhash{$key}{$item}) eq 'HASH') {
17964:                                 $resulttext .= '<li>'.$names{$item}.': ';
17965:                                 if (keys(%{$privacyhash{$key}{$item}})) {
17966:                                     $resulttext .= join(', ', map { $fieldnames{$_}; } (sort(keys(%{$privacyhash{$key}{$item}}))));
17967:                                 } else {
17968:                                     $resulttext .= &mt('none');
17969:                                 }
17970:                                 $resulttext .= '</li>';
17971:                             }
17972:                         }
17973:                     }
17974:                     $resulttext .= '</ul></li>';
17975:                 }
17976:             }
17977:         } else {
17978:             $resulttext = &mt('No changes made to user information settings');
17979:         }
17980:     } else {
17981:         $resulttext = '<span class="LC_error">'.
17982:             &mt('An error occurred: [_1]',$putresult).'</span>';
17983:     }
17984:     return $resulttext;
17985: }
17986: 
17987: sub modify_passwords {
17988:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
17989:     my ($resulttext,%current,%changes,%newvalues,@oktypes,$errors,
17990:         $updatedefaults,$updateconf);
17991:     my $customfn = 'resetpw.html';
17992:     if (ref($domconfig{'passwords'}) eq 'HASH') {
17993:         %current = %{$domconfig{'passwords'}};
17994:     }
17995:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
17996:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
17997:     if (ref($types) eq 'ARRAY') {
17998:         @oktypes = @{$types};
17999:     }
18000:     push(@oktypes,'default');
18001: 
18002:     my %titles = &Apache::lonlocal::texthash (
18003:         intauth_cost   => 'Encryption cost for bcrypt (positive integer)',
18004:         intauth_check  => 'Check bcrypt cost if authenticated',
18005:         intauth_switch => 'Existing crypt-based switched to bcrypt on authentication',
18006:         permanent      => 'Permanent e-mail address',
18007:         critical       => 'Critical notification address',
18008:         notify         => 'Notification address',
18009:         min            => 'Minimum password length',
18010:         max            => 'Maximum password length',
18011:         chars          => 'Required characters',
18012:         expire         => 'Password expiration (days)',
18013:         numsaved       => 'Number of previous passwords to save',
18014:         reset          => 'Resetting Forgotten Password',
18015:         intauth        => 'Encryption of Stored Passwords (Internal Auth)',
18016:         rules          => 'Rules for LON-CAPA Passwords',
18017:         crsownerchg    => 'Course Owner Changing Student Passwords',
18018:         username       => 'Username',
18019:         email          => 'E-mail address',
18020:     );
18021: 
18022: #
18023: # Retrieve current domain configuration for internal authentication from $domconfig{'defaults'}.
18024: #
18025:     my (%curr_defaults,%save_defaults);
18026:     if (ref($domconfig{'defaults'}) eq 'HASH') {
18027:         foreach my $key (keys(%{$domconfig{'defaults'}})) {
18028:             if ($key =~ /^intauth_(cost|check|switch)$/) {
18029:                 $curr_defaults{$key} = $domconfig{'defaults'}{$key};
18030:             } else {
18031:                 $save_defaults{$key} = $domconfig{'defaults'}{$key};
18032:             }
18033:         }
18034:     }
18035:     my %staticdefaults = (
18036:         'resetlink'      => 2,
18037:         'resetcase'      => \@oktypes,
18038:         'resetprelink'   => 'both',
18039:         'resetemail'     => ['critical','notify','permanent'],
18040:         'intauth_cost'   => 10,
18041:         'intauth_check'  => 0,
18042:         'intauth_switch' => 0,
18043:     );
18044:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18045:     foreach my $type (@oktypes) {
18046:         $staticdefaults{'resetpostlink'}{$type} = ['email','username'];
18047:     }
18048:     my $linklife = $env{'form.passwords_link'};
18049:     $linklife =~ s/^\s+|\s+$//g;
18050:     if (($linklife =~ /^\d+(|\.\d*)$/) && ($linklife > 0)) {
18051:         $newvalues{'resetlink'} = $linklife;
18052:         if ($current{'resetlink'}) {
18053:             if ($current{'resetlink'} ne $linklife) {
18054:                 $changes{'reset'} = 1;
18055:             }
18056:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18057:             if ($staticdefaults{'resetlink'} ne $linklife) {
18058:                 $changes{'reset'} = 1;
18059:             }
18060:         }
18061:     } elsif ($current{'resetlink'}) {
18062:         $changes{'reset'} = 1;
18063:     }
18064:     my @casesens;
18065:     my @posscase = &Apache::loncommon::get_env_multiple('form.passwords_case_sensitive');
18066:     foreach my $case (sort(@posscase)) {
18067:         if (grep(/^\Q$case\E$/,@oktypes)) {
18068:             push(@casesens,$case);
18069:         }
18070:     }
18071:     $newvalues{'resetcase'} = \@casesens;
18072:     if (ref($current{'resetcase'}) eq 'ARRAY') {
18073:         my @diffs = &Apache::loncommon::compare_arrays($current{'resetcase'},\@casesens);
18074:         if (@diffs > 0) {
18075:             $changes{'reset'} = 1;
18076:         }
18077:     } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18078:         my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetcase'},\@casesens);
18079:         if (@diffs > 0) {
18080:             $changes{'reset'} = 1;
18081:         }
18082:     }
18083:     if ($env{'form.passwords_prelink'} =~ /^(both|either)$/) {
18084:         $newvalues{'resetprelink'} = $env{'form.passwords_prelink'};
18085:         if (exists($current{'resetprelink'})) {
18086:             if ($current{'resetprelink'} ne $newvalues{'resetprelink'}) {
18087:                 $changes{'reset'} = 1;
18088:             }
18089:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18090:             if ($staticdefaults{'resetprelink'} ne $newvalues{'resetprelink'}) {
18091:                 $changes{'reset'} = 1;
18092:             }
18093:         }
18094:     } elsif ($current{'resetprelink'}) {
18095:         $changes{'reset'} = 1;
18096:     }
18097:     foreach my $type (@oktypes) {
18098:         my @possplink = &Apache::loncommon::get_env_multiple('form.passwords_postlink_'.$type);
18099:         my @postlink;
18100:         foreach my $item (sort(@possplink)) {
18101:             if ($item =~ /^(email|username)$/) {
18102:                 push(@postlink,$item);
18103:             }
18104:         }
18105:         $newvalues{'resetpostlink'}{$type} = \@postlink;
18106:         unless ($changes{'reset'}) {
18107:             if (ref($current{'resetpostlink'}) eq 'HASH') {
18108:                 if (ref($current{'resetpostlink'}{$type}) eq 'ARRAY') {
18109:                     my @diffs = &Apache::loncommon::compare_arrays($current{'resetpostlink'}{$type},\@postlink);
18110:                     if (@diffs > 0) {
18111:                         $changes{'reset'} = 1;
18112:                     }
18113:                 } else {
18114:                     $changes{'reset'} = 1;
18115:                 }
18116:             } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18117:                 my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetpostlink'}{$type},\@postlink);
18118:                 if (@diffs > 0) {
18119:                     $changes{'reset'} = 1;
18120:                 }
18121:             }
18122:         }
18123:     }
18124:     my @possemailsrc = &Apache::loncommon::get_env_multiple('form.passwords_emailsrc');
18125:     my @resetemail;
18126:     foreach my $item (sort(@possemailsrc)) {
18127:         if ($item =~ /^(permanent|critical|notify)$/) {
18128:             push(@resetemail,$item);
18129:         }
18130:     }
18131:     $newvalues{'resetemail'} = \@resetemail;
18132:     unless ($changes{'reset'}) {
18133:         if (ref($current{'resetemail'}) eq 'ARRAY') {
18134:             my @diffs = &Apache::loncommon::compare_arrays($current{'resetemail'},\@resetemail);
18135:             if (@diffs > 0) {
18136:                 $changes{'reset'} = 1;
18137:             }
18138:         } elsif (!ref($domconfig{passwords}) eq 'HASH') {
18139:             my @diffs = &Apache::loncommon::compare_arrays($staticdefaults{'resetemail'},\@resetemail);
18140:             if (@diffs > 0) {
18141:                 $changes{'reset'} = 1;
18142:             }
18143:         }
18144:     }
18145:     if ($env{'form.passwords_stdtext'} == 0) {
18146:         $newvalues{'resetremove'} = 1;
18147:         unless ($current{'resetremove'}) {
18148:             $changes{'reset'} = 1;
18149:         }
18150:     } elsif ($current{'resetremove'}) {
18151:         $changes{'reset'} = 1;
18152:     }
18153:     if ($env{'form.passwords_customfile.filename'} ne '') {
18154:         my $servadm = $r->dir_config('lonAdmEMail');
18155:         my ($configuserok,$author_ok,$switchserver) =
18156:             &config_check($dom,$confname,$servadm);
18157:         my $error;
18158:         if ($configuserok eq 'ok') {
18159:             if ($switchserver) {
18160:                 $error = &mt("Upload of file containing domain-specific text is not permitted to this server: [_1]",$switchserver);
18161:             } else {
18162:                 if ($author_ok eq 'ok') {
18163:                     my ($result,$customurl) =
18164:                         &publishlogo($r,'upload','passwords_customfile',$dom,
18165:                                      $confname,'customtext/resetpw','','',$customfn);
18166:                     if ($result eq 'ok') {
18167:                         $newvalues{'resetcustom'} = $customurl;
18168:                         $changes{'reset'} = 1;
18169:                     } else {
18170:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$customfn,$result);
18171:                     }
18172:                 } else {
18173:                     $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);
18174:                 }
18175:             }
18176:         } else {
18177:             $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);
18178:         }
18179:         if ($error) {
18180:             &Apache::lonnet::logthis($error);
18181:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
18182:         }
18183:     } elsif ($current{'resetcustom'}) {
18184:         if ($env{'form.passwords_custom_del'}) {
18185:             $changes{'reset'} = 1;
18186:         } else {
18187:             $newvalues{'resetcustom'} = $current{'resetcustom'};
18188:         }
18189:     }
18190:     $env{'form.intauth_cost'} =~ s/^\s+|\s+$//g;
18191:     if (($env{'form.intauth_cost'} ne '') && ($env{'form.intauth_cost'} =~ /^\d+$/)) {
18192:         $save_defaults{'intauth_cost'} = $env{'form.intauth_cost'};
18193:         if ($save_defaults{'intauth_cost'} ne $curr_defaults{'intauth_cost'}) {
18194:             $changes{'intauth'} = 1;
18195:         }
18196:     } else {
18197:         $save_defaults{'intauth_cost'} = $curr_defaults{'intauth_cost'};
18198:     }
18199:     if ($env{'form.intauth_check'} =~ /^(0|1|2)$/) {
18200:         $save_defaults{'intauth_check'} = $env{'form.intauth_check'};
18201:         if ($save_defaults{'intauth_check'} ne $curr_defaults{'intauth_check'}) {
18202:             $changes{'intauth'} = 1;
18203:         }
18204:     } else {
18205:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18206:     }
18207:     if ($env{'form.intauth_switch'} =~ /^(0|1|2)$/) {
18208:         $save_defaults{'intauth_switch'} = $env{'form.intauth_switch'};
18209:         if ($save_defaults{'intauth_switch'} ne $curr_defaults{'intauth_switch'}) {
18210:             $changes{'intauth'} = 1;
18211:         }
18212:     } else {
18213:         $save_defaults{'intauth_check'} = $curr_defaults{'intauth_check'};
18214:     }
18215:     foreach my $item ('cost','check','switch') {
18216:         if ($save_defaults{'intauth_'.$item} ne $domdefaults{'intauth_'.$item}) {
18217:             $domdefaults{'intauth_'.$item} = $save_defaults{'intauth_'.$item};
18218:             $updatedefaults = 1;
18219:         }
18220:     }
18221:     &password_rule_changes('passwords',\%newvalues,\%current,\%changes);
18222:     my %crsownerchg = (
18223:                         by => [],
18224:                         for => [],
18225:                       );
18226:     foreach my $item ('by','for') {
18227:         my @posstypes = &Apache::loncommon::get_env_multiple('form.passwords_crsowner_'.$item);
18228:         foreach my $type (sort(@posstypes)) {
18229:             if (grep(/^\Q$type\E$/,@oktypes)) {
18230:                 push(@{$crsownerchg{$item}},$type);
18231:             }
18232:         }
18233:     }
18234:     $newvalues{'crsownerchg'} = \%crsownerchg;
18235:     if (ref($current{'crsownerchg'}) eq 'HASH') {
18236:         foreach my $item ('by','for') {
18237:             if (ref($current{'crsownerchg'}{$item}) eq 'ARRAY') {
18238:                 my @diffs = &Apache::loncommon::compare_arrays($current{'crsownerchg'}{$item},$crsownerchg{$item});
18239:                 if (@diffs > 0) {
18240:                     $changes{'crsownerchg'} = 1;
18241:                     last;
18242:                 }
18243:             }
18244:         }
18245:     } elsif (!(ref($domconfig{passwords}) eq 'HASH')) {
18246:         foreach my $item ('by','for') {
18247:             if (@{$crsownerchg{$item}} > 0) {
18248:                 $changes{'crsownerchg'} = 1;
18249:                 last;
18250:             }
18251:         }
18252:     }
18253: 
18254:     my %confighash = (
18255:                         defaults  => \%save_defaults,
18256:                         passwords => \%newvalues,
18257:                      );
18258:     &process_captcha('passwords',\%changes,$confighash{'passwords'},$domconfig{'passwords'});
18259: 
18260:     my $putresult = &Apache::lonnet::put_dom('configuration',\%confighash,$dom);
18261:     if ($putresult eq 'ok') {
18262:         if (keys(%changes) > 0) {
18263:             $resulttext = &mt('Changes made: ').'<ul>';
18264:             foreach my $key ('reset','intauth','rules','crsownerchg') {
18265:                 if ($changes{$key}) {
18266:                     unless ($key eq 'intauth') {
18267:                         $updateconf = 1;
18268:                     }
18269:                     $resulttext .= '<li>'.$titles{$key}.':<ul>';
18270:                     if ($key eq 'reset') {
18271:                         if ($confighash{'passwords'}{'captcha'} eq 'original') {
18272:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: original CAPTCHA').'</li>';
18273:                         } elsif ($confighash{'passwords'}{'captcha'} eq 'recaptcha') {
18274:                             $resulttext .= '<li>'.&mt('CAPTCHA validation set to use: reCAPTCHA').' '.
18275:                                            &mt('version: [_1]',$confighash{'passwords'}{'recaptchaversion'}).'<br />';
18276:                             if (ref($confighash{'passwords'}{'recaptchakeys'}) eq 'HASH') {
18277:                                 $resulttext .= &mt('Public key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'public'}).'</br>'.
18278:                                                &mt('Private key: [_1]',$confighash{'passwords'}{'recaptchakeys'}{'private'}).'</li>';
18279:                             }
18280:                         } else {
18281:                             $resulttext .= '<li>'.&mt('No CAPTCHA validation').'</li>';
18282:                         }
18283:                         if ($confighash{'passwords'}{'resetlink'}) {
18284:                             $resulttext .= '<li>'.&mt('Reset link expiration set to [quant,_1,hour]',$confighash{'passwords'}{'resetlink'}).'</li>';
18285:                         } else {
18286:                             $resulttext .= '<li>'.&mt('No reset link expiration set.').' '.
18287:                                                   &mt('Will default to 2 hours').'</li>';
18288:                         }
18289:                         if (ref($confighash{'passwords'}{'resetcase'}) eq 'ARRAY') {
18290:                             if (@{$confighash{'passwords'}{'resetcase'}} == 0) {
18291:                                 $resulttext .= '<li>'.&mt('User input for username and/or e-mail address not case sensitive for "Forgot Password" web form').'</li>';
18292:                             } else {
18293:                                 my $casesens;
18294:                                 foreach my $type (@{$confighash{'passwords'}{'resetcase'}}) {
18295:                                     if ($type eq 'default') {
18296:                                         $casesens .= $othertitle.', ';
18297:                                     } elsif ($usertypes->{$type} ne '') {
18298:                                         $casesens .= $usertypes->{$type}.', ';
18299:                                     }
18300:                                 }
18301:                                 $casesens =~ s/\Q, \E$//;
18302:                                 $resulttext .= '<li>'.&mt('"Forgot Password" web form input for username and/or e-mail address is case-sensitive for: [_1]',$casesens).'</li>';
18303:                             }
18304:                         } else {
18305:                             $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>';
18306:                         }
18307:                         if ($confighash{'passwords'}{'resetprelink'} eq 'either') {
18308:                             $resulttext .= '<li>'.&mt('Users can enter either a username or an e-mail address in "Forgot Password" web form').'</li>';
18309:                         } else {
18310:                             $resulttext .= '<li>'.&mt('Users can enter both a username and an e-mail address in "Forgot Password" web form').'</li>';
18311:                         }
18312:                         if (ref($confighash{'passwords'}{'resetpostlink'}) eq 'HASH') {
18313:                             my $output;
18314:                             if (ref($types) eq 'ARRAY') {
18315:                                 foreach my $type (@{$types}) {
18316:                                     if (ref($confighash{'passwords'}{'resetpostlink'}{$type}) eq 'ARRAY') {
18317:                                         if (@{$confighash{'passwords'}{'resetpostlink'}{$type}} == 0) {
18318:                                             $output .= $usertypes->{$type}.' -- '.&mt('none');
18319:                                         } else {
18320:                                             $output .= $usertypes->{$type}.' -- '.
18321:                                                        join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{$type}})).'; ';
18322:                                         }
18323:                                     }
18324:                                 }
18325:                             }
18326:                             if (ref($confighash{'passwords'}{'resetpostlink'}{'default'}) eq 'ARRAY') {
18327:                                 if (@{$confighash{'passwords'}{'resetpostlink'}{'default'}} == 0) {
18328:                                     $output .= $othertitle.' -- '.&mt('none');
18329:                                 } else {
18330:                                     $output .= $othertitle.' -- '.
18331:                                                join(', ',map { $titles{$_}; } (@{$confighash{'passwords'}{'resetpostlink'}{'default'}}));
18332:                                 }
18333:                             }
18334:                             if ($output) {
18335:                                 $resulttext .= '<li>'.&mt('Information required for new password form (by user type) set to: [_1]',$output).'</li>';
18336:                             } else {
18337:                                 $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>';
18338:                             }
18339:                         } else {
18340:                             $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>';
18341:                         }
18342:                         if (ref($confighash{'passwords'}{'resetemail'}) eq 'ARRAY') {
18343:                             if (@{$confighash{'passwords'}{'resetemail'}} > 0) {
18344:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$confighash{'passwords'}{'resetemail'}})).'</li>';
18345:                             } else {
18346:                                 $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18347:                             }
18348:                         } else {
18349:                             $resulttext .= '<li>'.&mt('E-mail address(es) in LON-CAPA used for verification will include: [_1]',join(', ',map { $titles{$_}; } @{$staticdefaults{'resetemail'}})).'</li>';
18350:                         }
18351:                         if ($confighash{'passwords'}{'resetremove'}) {
18352:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form not shown').'</li>';
18353:                         } else {
18354:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" web form is shown').'</li>';
18355:                         }
18356:                         if ($confighash{'passwords'}{'resetcustom'}) {
18357:                             my $customlink = &Apache::loncommon::modal_link($confighash{'passwords'}{'resetcustom'},
18358:                                                                             &mt('custom text'),600,500,undef,undef,
18359:                                                                             undef,undef,'background-color:#ffffff');
18360:                             $resulttext .= '<li>'.&mt('Preamble to "Forgot Password" form includes: [_1]',$customlink).'</li>';
18361:                         } else {
18362:                             $resulttext .= '<li>'.&mt('No custom text included in preamble to "Forgot Password" form').'</li>';
18363:                         }
18364:                     } elsif ($key eq 'intauth') {
18365:                         foreach my $item ('cost','switch','check') {
18366:                             my $value = $save_defaults{$key.'_'.$item};
18367:                             if ($item eq 'switch') {
18368:                                 my %optiondesc = &Apache::lonlocal::texthash (
18369:                                                      0 => 'No',
18370:                                                      1 => 'Yes',
18371:                                                      2 => 'Yes, and copy existing passwd file to passwd.bak file',
18372:                                                  );
18373:                                 if ($value =~ /^(0|1|2)$/) {
18374:                                     $value = $optiondesc{$value};
18375:                                 } else {
18376:                                     $value = &mt('none -- defaults to No');
18377:                                 }
18378:                             } elsif ($item eq 'check') {
18379:                                 my %optiondesc = &Apache::lonlocal::texthash (
18380:                                                      0 => 'No',
18381:                                                      1 => 'Yes, allow login then update passwd file using default cost (if higher)',
18382:                                                      2 => 'Yes, disallow login if stored cost is less than domain default',
18383:                                                  );
18384:                                 if ($value =~ /^(0|1|2)$/) {
18385:                                     $value = $optiondesc{$value};
18386:                                 } else {
18387:                                     $value = &mt('none -- defaults to No');
18388:                                 }
18389:                             }
18390:                             $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$titles{$key.'_'.$item},$value).'</li>';
18391:                         }
18392:                     } elsif ($key eq 'rules') {
18393:                         foreach my $rule ('min','max','expire','numsaved') {
18394:                             if ($confighash{'passwords'}{$rule} eq '') {
18395:                                 if ($rule eq 'min') {
18396:                                     $resulttext .= '<li>'.&mt('[_1] not set.',$titles{$rule});
18397:                                                    ' '.&mt('Default of [_1] will be used',
18398:                                                            $Apache::lonnet::passwdmin).'</li>';
18399:                                 } else {
18400:                                     $resulttext .= '<li>'.&mt('[_1] set to none',$titles{$rule}).'</li>';
18401:                                 }
18402:                             } else {
18403:                                 $resulttext .= '<li>'.&mt('[_1] set to [_2]',$titles{$rule},$confighash{'passwords'}{$rule}).'</li>';
18404:                             }
18405:                         }
18406:                         if (ref($confighash{'passwords'}{'chars'}) eq 'ARRAY') {
18407:                             if (@{$confighash{'passwords'}{'chars'}} > 0) {
18408:                                 my %rulenames = &Apache::lonlocal::texthash(
18409:                                                      uc => 'At least one upper case letter',
18410:                                                      lc => 'At least one lower case letter',
18411:                                                      num => 'At least one number',
18412:                                                      spec => 'At least one non-alphanumeric',
18413:                                                    );
18414:                                 my $needed = '<ul><li>'.
18415:                                              join('</li><li>',map {$rulenames{$_} } @{$confighash{'passwords'}{'chars'}}).
18416:                                              '</li></ul>'; 
18417:                                 $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$titles{'chars'},$needed).'</li>';
18418:                             } else {
18419:                                 $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18420:                             }
18421:                         } else {
18422:                             $resulttext .= '<li>'.&mt('[_1] set to none',$titles{'chars'}).'</li>';
18423:                         }
18424:                     } elsif ($key eq 'crsownerchg') {
18425:                         if (ref($confighash{'passwords'}{'crsownerchg'}) eq 'HASH') {
18426:                             if ((@{$confighash{'passwords'}{'crsownerchg'}{'by'}} == 0) ||
18427:                                 (@{$confighash{'passwords'}{'crsownerchg'}{'for'}} == 0)) {
18428:                                 $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18429:                             } else {
18430:                                 my %crsownerstr;
18431:                                 foreach my $item ('by','for') {
18432:                                     if (ref($confighash{'passwords'}{'crsownerchg'}{$item}) eq 'ARRAY') {
18433:                                         foreach my $type (@{$confighash{'passwords'}{'crsownerchg'}{$item}}) {
18434:                                             if ($type eq 'default') {
18435:                                                 $crsownerstr{$item} .= $othertitle.', ';
18436:                                             } elsif ($usertypes->{$type} ne '') {
18437:                                                 $crsownerstr{$item} .= $usertypes->{$type}.', ';
18438:                                             }
18439:                                         }
18440:                                         $crsownerstr{$item} =~ s/\Q, \E$//;
18441:                                     }
18442:                                 }
18443:                                 $resulttext .= '<li>'.&mt('Course owner (with status: [_1]) may change passwords for students (with status: [_2]).',
18444:                                            $crsownerstr{'by'},$crsownerstr{'for'}).'</li>';
18445:                             }
18446:                         } else {
18447:                             $resulttext .= '<li>'.&mt('Course owner may not change student passwords.').'</li>';
18448:                         }
18449:                     }
18450:                     $resulttext .= '</ul></li>';
18451:                 }
18452:             }
18453:             $resulttext .= '</ul>';
18454:         } else {
18455:             $resulttext = &mt('No changes made to password settings');
18456:         }
18457:         my $cachetime = 24*60*60;
18458:         if ($updatedefaults) {
18459:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
18460:             if (ref($lastactref) eq 'HASH') {
18461:                 $lastactref->{'domdefaults'} = 1;
18462:             }
18463:         }
18464:         if ($updateconf) {
18465:             &Apache::lonnet::do_cache_new('passwdconf',$dom,$confighash{'passwords'},$cachetime);
18466:             if (ref($lastactref) eq 'HASH') {
18467:                 $lastactref->{'passwdconf'} = 1;
18468:             }
18469:         }
18470:     } else {
18471:         $resulttext = '<span class="LC_error">'.
18472:             &mt('An error occurred: [_1]',$putresult).'</span>';
18473:     }
18474:     if ($errors) {
18475:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
18476:                        $errors.'</ul></p>';
18477:     }
18478:     return $resulttext;
18479: }
18480: 
18481: sub password_rule_changes {
18482:     my ($prefix,$newvalues,$current,$changes) = @_;
18483:     return unless ((ref($newvalues) eq 'HASH') &&
18484:                    (ref($current) eq 'HASH') &&
18485:                    (ref($changes) eq 'HASH'));
18486:     my (@rules,%staticdefaults);
18487:     if ($prefix eq 'passwords') {
18488:         @rules = ('min','max','expire','numsaved');
18489:     } elsif ($prefix eq 'secrets') {
18490:         @rules = ('min','max');
18491:     }
18492:     $staticdefaults{'min'} = $Apache::lonnet::passwdmin;
18493:     foreach my $rule (@rules) {
18494:         $env{'form.'.$prefix.'_'.$rule} =~ s/^\s+|\s+$//g;
18495:         my $ruleok;
18496:         if ($rule eq 'expire') {
18497:             if (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+(|\.\d*)$/) &&
18498:                 ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18499:                 $ruleok = 1;
18500:             }
18501:         } elsif ($rule eq 'min') {
18502:             if ($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) {
18503:                 if ($env{'form.'.$prefix.'_'.$rule} >= $staticdefaults{$rule}) {
18504:                     $ruleok = 1;
18505:                 }
18506:             }
18507:         } elsif (($env{'form.'.$prefix.'_'.$rule} =~ /^\d+$/) &&
18508:                  ($env{'form.'.$prefix.'_'.$rule} ne '0')) {
18509:             $ruleok = 1;
18510:         }
18511:         if ($ruleok) {
18512:             $newvalues->{$rule} = $env{'form.'.$prefix.'_'.$rule};
18513:             if (exists($current->{$rule})) {
18514:                 if ($newvalues->{$rule} ne $current->{$rule}) {
18515:                     $changes->{'rules'} = 1;
18516:                 }
18517:             } elsif ($rule eq 'min') {
18518:                 if ($staticdefaults{$rule} ne $newvalues->{$rule}) {
18519:                     $changes->{'rules'} = 1;
18520:                 }
18521:             } else {
18522:                 $changes->{'rules'} = 1;
18523:             }
18524:         } elsif (exists($current->{$rule})) {
18525:             $changes->{'rules'} = 1;
18526:         }
18527:     }
18528:     my @posschars = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_chars');
18529:     my @chars;
18530:     foreach my $item (sort(@posschars)) {
18531:         if ($item =~ /^(uc|lc|num|spec)$/) {
18532:             push(@chars,$item);
18533:         }
18534:     }
18535:     $newvalues->{'chars'} = \@chars;
18536:     unless ($changes->{'rules'}) {
18537:         if (ref($current->{'chars'}) eq 'ARRAY') {
18538:             my @diffs = &Apache::loncommon::compare_arrays($current->{'chars'},\@chars);
18539:             if (@diffs > 0) {
18540:                 $changes->{'rules'} = 1;
18541:             }
18542:         } else {
18543:             if (@chars > 0) {
18544:                 $changes->{'rules'} = 1;
18545:             }
18546:         }
18547:     }
18548:     return;
18549: }
18550: 
18551: sub modify_usercreation {
18552:     my ($dom,%domconfig) = @_;
18553:     my ($resulttext,%curr_usercreation,%changes,%authallowed,%cancreate,%save_usercreate);
18554:     my $warningmsg;
18555:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18556:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18557:             if ($key eq 'cancreate') {
18558:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18559:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18560:                         if (($item eq 'requestcrs') || ($item eq 'course') || ($item eq 'author')) {
18561:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18562:                         } else {
18563:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18564:                         }
18565:                     }
18566:                 }
18567:             } elsif ($key eq 'email_rule') {
18568:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18569:             } else {
18570:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18571:             }
18572:         }
18573:     }
18574:     my @username_rule = &Apache::loncommon::get_env_multiple('form.username_rule');
18575:     my @id_rule = &Apache::loncommon::get_env_multiple('form.id_rule');
18576:     my @contexts = ('author','course','requestcrs');
18577:     foreach my $item(@contexts) {
18578:         $cancreate{$item} = $env{'form.can_createuser_'.$item};
18579:     }
18580:     if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
18581:         foreach my $item (@contexts) {
18582:             if ($curr_usercreation{'cancreate'}{$item} ne $cancreate{$item}) {
18583:                 push(@{$changes{'cancreate'}},$item);
18584:             }
18585:         }
18586:     } elsif (ref($curr_usercreation{'cancreate'}) eq 'ARRAY') {
18587:         foreach my $item (@contexts) {
18588:             if (!grep(/^\Q$item\E$/,@{$curr_usercreation{'cancreate'}})) {
18589:                 if ($cancreate{$item} ne 'any') {
18590:                     push(@{$changes{'cancreate'}},$item);
18591:                 }
18592:             } else {
18593:                 if ($cancreate{$item} ne 'none') {
18594:                     push(@{$changes{'cancreate'}},$item);
18595:                 }
18596:             }
18597:         }
18598:     } else {
18599:         foreach my $item (@contexts)  {
18600:             push(@{$changes{'cancreate'}},$item);
18601:         }
18602:     }
18603: 
18604:     if (ref($curr_usercreation{'username_rule'}) eq 'ARRAY') {
18605:         foreach my $type (@{$curr_usercreation{'username_rule'}}) {
18606:             if (!grep(/^\Q$type\E$/,@username_rule)) {
18607:                 push(@{$changes{'username_rule'}},$type);
18608:             }
18609:         }
18610:         foreach my $type (@username_rule) {
18611:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'username_rule'}})) {
18612:                 push(@{$changes{'username_rule'}},$type);
18613:             }
18614:         }
18615:     } else {
18616:         push(@{$changes{'username_rule'}},@username_rule);
18617:     }
18618: 
18619:     if (ref($curr_usercreation{'id_rule'}) eq 'ARRAY') {
18620:         foreach my $type (@{$curr_usercreation{'id_rule'}}) {
18621:             if (!grep(/^\Q$type\E$/,@id_rule)) {
18622:                 push(@{$changes{'id_rule'}},$type);
18623:             }
18624:         }
18625:         foreach my $type (@id_rule) {
18626:             if (!grep(/^\Q$type\E$/,@{$curr_usercreation{'id_rule'}})) {
18627:                 push(@{$changes{'id_rule'}},$type);
18628:             }
18629:         }
18630:     } else {
18631:         push(@{$changes{'id_rule'}},@id_rule);
18632:     }
18633: 
18634:     my @authen_contexts = ('author','course','domain');
18635:     my @authtypes = ('int','krb4','krb5','loc','lti');
18636:     my %authhash;
18637:     foreach my $item (@authen_contexts) {
18638:         my @authallowed =  &Apache::loncommon::get_env_multiple('form.'.$item.'_auth');
18639:         foreach my $auth (@authtypes) {
18640:             if (grep(/^\Q$auth\E$/,@authallowed)) {
18641:                 $authhash{$item}{$auth} = 1;
18642:             } else {
18643:                 $authhash{$item}{$auth} = 0;
18644:             }
18645:         }
18646:     }
18647:     if (ref($curr_usercreation{'authtypes'}) eq 'HASH') {
18648:         foreach my $item (@authen_contexts) {
18649:             if (ref($curr_usercreation{'authtypes'}{$item}) eq 'HASH') {
18650:                 foreach my $auth (@authtypes) {
18651:                     if ($authhash{$item}{$auth} ne $curr_usercreation{'authtypes'}{$item}{$auth}) {
18652:                         push(@{$changes{'authtypes'}},$item);
18653:                         last;
18654:                     }
18655:                 }
18656:             }
18657:         }
18658:     } else {
18659:         foreach my $item (@authen_contexts) {
18660:             push(@{$changes{'authtypes'}},$item);
18661:         }
18662:     }
18663: 
18664:     $save_usercreate{'cancreate'}{'course'} = $cancreate{'course'}; 
18665:     $save_usercreate{'cancreate'}{'author'} = $cancreate{'author'};
18666:     $save_usercreate{'cancreate'}{'requestcrs'} = $cancreate{'requestcrs'};
18667:     $save_usercreate{'id_rule'} = \@id_rule;
18668:     $save_usercreate{'username_rule'} = \@username_rule,
18669:     $save_usercreate{'authtypes'} = \%authhash;
18670: 
18671:     my %usercreation_hash =  (
18672:         usercreation     => \%save_usercreate,
18673:     );
18674: 
18675:     my $putresult = &Apache::lonnet::put_dom('configuration',\%usercreation_hash,
18676:                                              $dom);
18677: 
18678:     if ($putresult eq 'ok') {
18679:         if (keys(%changes) > 0) {
18680:             $resulttext = &mt('Changes made:').'<ul>';
18681:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
18682:                 my %lt = &usercreation_types();
18683:                 foreach my $type (@{$changes{'cancreate'}}) {
18684:                     my $chgtext = $lt{$type}.', ';
18685:                     if ($cancreate{$type} eq 'none') {
18686:                         $chgtext .= &mt('creation of new users is not permitted, except by a Domain Coordinator.');
18687:                     } elsif ($cancreate{$type} eq 'any') {
18688:                         $chgtext .= &mt('creation of new users is permitted for both institutional and non-institutional usernames.');
18689:                     } elsif ($cancreate{$type} eq 'official') {
18690:                         $chgtext .= &mt('creation of new users is only permitted for institutional usernames.');
18691:                     } elsif ($cancreate{$type} eq 'unofficial') {
18692:                         $chgtext .= &mt('creation of new users is only permitted for non-institutional usernames.');
18693:                     }
18694:                     $resulttext .= '<li>'.$chgtext.'</li>';
18695:                 }
18696:             }
18697:             if (ref($changes{'username_rule'}) eq 'ARRAY') {
18698:                 my ($rules,$ruleorder) = 
18699:                     &Apache::lonnet::inst_userrules($dom,'username');
18700:                 my $chgtext = '<ul>';
18701:                 foreach my $type (@username_rule) {
18702:                     if (ref($rules->{$type}) eq 'HASH') {
18703:                         $chgtext .= '<li>'.$rules->{$type}{'name'}.'</li>';
18704:                     }
18705:                 }
18706:                 $chgtext .= '</ul>';
18707:                 if (@username_rule > 0) {
18708:                     $resulttext .= '<li>'.&mt('Usernames with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';     
18709:                 } else {
18710:                     $resulttext .= '<li>'.&mt('There are now no username formats restricted to verified users in the institutional directory.').'</li>'; 
18711:                 }
18712:             }
18713:             if (ref($changes{'id_rule'}) eq 'ARRAY') {
18714:                 my ($idrules,$idruleorder) = 
18715:                     &Apache::lonnet::inst_userrules($dom,'id');
18716:                 my $chgtext = '<ul>';
18717:                 foreach my $type (@id_rule) {
18718:                     if (ref($idrules->{$type}) eq 'HASH') {
18719:                         $chgtext .= '<li>'.$idrules->{$type}{'name'}.'</li>';
18720:                     }
18721:                 }
18722:                 $chgtext .= '</ul>';
18723:                 if (@id_rule > 0) {
18724:                     $resulttext .= '<li>'.&mt('IDs with the following formats are restricted to verified users in the institutional directory: ').$chgtext.'</li>';
18725:                 } else {
18726:                     $resulttext .= '<li>'.&mt('There are now no ID formats restricted to verified users in the institutional directory.').'</li>';
18727:                 }
18728:             }
18729:             my %authname = &authtype_names();
18730:             my %context_title = &context_names();
18731:             if (ref($changes{'authtypes'}) eq 'ARRAY') {
18732:                 my $chgtext = '<ul>';
18733:                 foreach my $type (@{$changes{'authtypes'}}) {
18734:                     my @allowed;
18735:                     $chgtext .= '<li><span class="LC_cusr_emph">'.$context_title{$type}.'</span> - '.&mt('assignable authentication types: ');
18736:                     foreach my $auth (@authtypes) {
18737:                         if ($authhash{$type}{$auth}) {
18738:                             push(@allowed,$authname{$auth});
18739:                         }
18740:                     }
18741:                     if (@allowed > 0) {
18742:                         $chgtext .= join(', ',@allowed).'</li>';
18743:                     } else {
18744:                         $chgtext .= &mt('none').'</li>';
18745:                     }
18746:                 }
18747:                 $chgtext .= '</ul>';
18748:                 $resulttext .= '<li>'.&mt('Authentication types available for assignment to new users').'<br />'.$chgtext;
18749:                 $resulttext .= '</li>';
18750:             }
18751:             $resulttext .= '</ul>';
18752:         } else {
18753:             $resulttext = &mt('No changes made to user creation settings');
18754:         }
18755:     } else {
18756:         $resulttext = '<span class="LC_error">'.
18757:             &mt('An error occurred: [_1]',$putresult).'</span>';
18758:     }
18759:     if ($warningmsg ne '') {
18760:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
18761:     }
18762:     return $resulttext;
18763: }
18764: 
18765: sub modify_selfcreation {
18766:     my ($dom,$lastactref,%domconfig) = @_;
18767:     my ($resulttext,$warningmsg,%curr_usercreation,%curr_usermodify,%curr_inststatus,%changes,%cancreate);
18768:     my (%save_usercreate,%save_usermodify,%save_inststatus,@types,%usertypes);
18769:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
18770:     my ($othertitle,$usertypesref,$typesref) = &Apache::loncommon::sorted_inst_types($dom);
18771:     if (ref($typesref) eq 'ARRAY') {
18772:         @types = @{$typesref};
18773:     }
18774:     if (ref($usertypesref) eq 'HASH') {
18775:         %usertypes = %{$usertypesref};
18776:     }
18777:     $usertypes{'default'} = $othertitle;
18778: #
18779: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usercreation'}.
18780: #
18781:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
18782:         foreach my $key (keys(%{$domconfig{'usercreation'}})) {
18783:             if ($key eq 'cancreate') {
18784:                 if (ref($domconfig{'usercreation'}{$key}) eq 'HASH') {
18785:                     foreach my $item (keys(%{$domconfig{'usercreation'}{$key}})) {
18786:                         if (($item eq 'selfcreate') || ($item eq 'statustocreate') ||
18787:                             ($item eq 'captcha') || ($item eq 'recaptchakeys') ||
18788:                             ($item eq 'recaptchaversion') || ($item eq 'notify') ||
18789:                             ($item eq 'emailusername') || ($item eq 'shibenv') ||
18790:                             ($item eq 'selfcreateprocessing') || ($item eq 'emailverified') ||
18791:                             ($item eq 'emailoptions') || ($item eq 'emaildomain')) {
18792:                             $curr_usercreation{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18793:                         } else {
18794:                             $save_usercreate{$key}{$item} = $domconfig{'usercreation'}{$key}{$item};
18795:                         }
18796:                     }
18797:                 }
18798:             } elsif ($key eq 'email_rule') {
18799:                 $curr_usercreation{$key} = $domconfig{'usercreation'}{$key};
18800:             } else {
18801:                 $save_usercreate{$key} = $domconfig{'usercreation'}{$key};
18802:             }
18803:         }
18804:     }
18805: #
18806: # Retrieve current domain configuration for self-creation of usernames from $domconfig{'usermodification'}.
18807: #
18808:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
18809:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
18810:             if ($key eq 'selfcreate') {
18811:                 $curr_usermodify{$key} = $domconfig{'usermodification'}{$key};
18812:             } else {
18813:                 $save_usermodify{$key} = $domconfig{'usermodification'}{$key};
18814:             }
18815:         }
18816:     }
18817: #
18818: # Retrieve current domain configuration for institutional status types from $domconfig{'inststatus'}.
18819: #
18820:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
18821:         foreach my $key (keys(%{$domconfig{'inststatus'}})) {
18822:             if ($key eq 'inststatusguest') {
18823:                 $curr_inststatus{$key} = $domconfig{'inststatus'}{$key};
18824:             } else {
18825:                 $save_inststatus{$key} = $domconfig{'inststatus'}{$key};
18826:             }
18827:         }
18828:     }
18829: 
18830:     my @contexts = ('selfcreate');
18831:     @{$cancreate{'selfcreate'}} = ();
18832:     %{$cancreate{'emailusername'}} = ();
18833:     if (@types) {
18834:         @{$cancreate{'statustocreate'}} = ();
18835:     }
18836:     %{$cancreate{'selfcreateprocessing'}} = ();
18837:     %{$cancreate{'shibenv'}} = ();
18838:     %{$cancreate{'emailverified'}} = ();
18839:     %{$cancreate{'emailoptions'}} = ();
18840:     %{$cancreate{'emaildomain'}} = ();
18841:     my %selfcreatetypes = (
18842:                              sso   => 'users authenticated by institutional single sign on',
18843:                              login => 'users authenticated by institutional log-in',
18844:                              email => 'users verified by e-mail',
18845:                           );
18846: #
18847: # Populate $cancreate{'selfcreate'} array reference with types of user, for which self-creation of user accounts
18848: # is permitted.
18849: #
18850:     my ($emailrules,$emailruleorder) = &Apache::lonnet::inst_userrules($dom,'email');
18851: 
18852:     my (@statuses,%email_rule);
18853:     foreach my $item ('login','sso','email') {
18854:         if ($item eq 'email') {
18855:             if ($env{'form.cancreate_email'}) {
18856:                 if (@types) {
18857:                     my @poss_statuses = &Apache::loncommon::get_env_multiple('form.selfassign');
18858:                     foreach my $status (@poss_statuses) {
18859:                         if (grep(/^\Q$status\E$/,(@types,'default'))) {
18860:                             push(@statuses,$status);
18861:                         }
18862:                     }
18863:                     $save_inststatus{'inststatusguest'} = \@statuses;
18864:                 } else {
18865:                     push(@statuses,'default');
18866:                 }
18867:                 if (@statuses) {
18868:                     my %curr_rule;
18869:                     if (ref($curr_usercreation{'email_rule'}) eq 'ARRAY') {
18870:                         foreach my $type (@statuses) {
18871:                             $curr_rule{$type} = $curr_usercreation{'email_rule'};
18872:                         }
18873:                     } elsif (ref($curr_usercreation{'email_rule'}) eq 'HASH') {
18874:                         foreach my $type (@statuses) {
18875:                             $curr_rule{$type} = $curr_usercreation{'email_rule'}{$type};
18876:                         }
18877:                     }
18878:                     push(@{$cancreate{'selfcreate'}},'email');
18879:                     push(@contexts,('selfcreateprocessing','emailverified','emailoptions'));
18880:                     my %curremaildom;
18881:                     if (ref($curr_usercreation{'cancreate'}{'emaildomain'}) eq 'HASH') {
18882:                         %curremaildom = %{$curr_usercreation{'cancreate'}{'emaildomain'}};
18883:                     }
18884:                     foreach my $type (@statuses) {
18885:                         if ($env{'form.cancreate_emailprocess_'.$type} =~ /^(?:approval|automatic)$/) {
18886:                             $cancreate{'selfcreateprocessing'}{$type} = $env{'form.cancreate_emailprocess_'.$type};
18887:                         }
18888:                         if ($env{'form.cancreate_usernameoptions_'.$type} =~ /^(?:all|first|free)$/) {
18889:                             $cancreate{'emailverified'}{$type} = $env{'form.cancreate_usernameoptions_'.$type};
18890:                         }
18891:                         if ($env{'form.cancreate_emailoptions_'.$type} =~ /^(any|inst|noninst|custom)$/) {
18892: #
18893: # Retrieve rules (if any) governing types of e-mail address which may be used to verify a username.
18894: #
18895:                             my $chosen = $1;
18896:                             if (($chosen eq 'inst') || ($chosen eq 'noninst')) {
18897:                                 my $emaildom;
18898:                                 if ($env{'form.cancreate_emaildomain_'.$chosen.'_'.$type} =~ /^\@[^\@]+$/) {
18899:                                     $emaildom = $env{'form.cancreate_emaildomain_'.$chosen.'_'.$type}; 
18900:                                     $cancreate{'emaildomain'}{$type}{$chosen} = $emaildom;
18901:                                     if (ref($curremaildom{$type}) eq 'HASH') {
18902:                                         if (exists($curremaildom{$type}{$chosen})) {
18903:                                             if ($curremaildom{$type}{$chosen} ne $emaildom) {
18904:                                                 push(@{$changes{'cancreate'}},'emaildomain');
18905:                                             }
18906:                                         } elsif ($emaildom ne '') {
18907:                                             push(@{$changes{'cancreate'}},'emaildomain');
18908:                                         }
18909:                                     } elsif ($emaildom ne '') {
18910:                                         push(@{$changes{'cancreate'}},'emaildomain');
18911:                                     } 
18912:                                 }
18913:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
18914:                             } elsif ($chosen eq 'custom') {
18915:                                 my @possemail_rules = &Apache::loncommon::get_env_multiple('form.email_rule_'.$type);
18916:                                 $email_rule{$type} = [];
18917:                                 if (ref($emailrules) eq 'HASH') {
18918:                                     foreach my $rule (@possemail_rules) {
18919:                                         if (exists($emailrules->{$rule})) {
18920:                                             push(@{$email_rule{$type}},$rule);
18921:                                         }
18922:                                     }
18923:                                 }
18924:                                 if (@{$email_rule{$type}}) {
18925:                                     $cancreate{'emailoptions'}{$type} = 'custom';
18926:                                     if (ref($curr_rule{$type}) eq 'ARRAY') {
18927:                                         if (@{$curr_rule{$type}} > 0) {
18928:                                             foreach my $rule (@{$curr_rule{$type}}) {
18929:                                                 if (!grep(/^\Q$rule\E$/,@{$email_rule{$type}})) {
18930:                                                     push(@{$changes{'email_rule'}},$type);
18931:                                                 }
18932:                                             }
18933:                                         }
18934:                                         foreach my $type (@{$email_rule{$type}}) {
18935:                                             if (!grep(/^\Q$type\E$/,@{$curr_rule{$type}})) {
18936:                                                 push(@{$changes{'email_rule'}},$type);
18937:                                             }
18938:                                         }
18939:                                     } else {
18940:                                         push(@{$changes{'email_rule'}},$type);
18941:                                     }
18942:                                 }
18943:                             } else {
18944:                                 $cancreate{'emailoptions'}{$type} = $env{'form.cancreate_emailoptions_'.$type};
18945:                             }
18946:                         }
18947:                     }
18948:                     if (@types) {
18949:                         if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
18950:                             my @changed = &Apache::loncommon::compare_arrays(\@statuses,$curr_inststatus{'inststatusguest'});
18951:                             if (@changed) {
18952:                                 push(@{$changes{'inststatus'}},'inststatusguest');
18953:                             }
18954:                         } else {
18955:                             push(@{$changes{'inststatus'}},'inststatusguest');
18956:                         }
18957:                     }
18958:                 } else {
18959:                     delete($env{'form.cancreate_email'});
18960:                     if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
18961:                         if (@{$curr_inststatus{'inststatusguest'}} > 0) {
18962:                             push(@{$changes{'inststatus'}},'inststatusguest');
18963:                         }
18964:                     }
18965:                 }
18966:             } else {
18967:                 $save_inststatus{'inststatusguest'} = [];
18968:                 if (ref($curr_inststatus{'inststatusguest'}) eq 'ARRAY') {
18969:                     if (@{$curr_inststatus{'inststatusguest'}} > 0) {
18970:                         push(@{$changes{'inststatus'}},'inststatusguest');
18971:                     }
18972:                 }
18973:             }
18974:         } else {
18975:             if ($env{'form.cancreate_'.$item}) {
18976:                 push(@{$cancreate{'selfcreate'}},$item);
18977:             }
18978:         }
18979:     }
18980:     my (%userinfo,%savecaptcha);
18981:     my ($infofields,$infotitles) = &Apache::loncommon::emailusername_info();
18982: #
18983: # Populate $cancreate{'emailusername'}{$type} hash ref with information fields (if new user will provide data
18984: # value set to one), if self-creation with e-mail address permitted, where $type is user type: faculty, staff, student etc.
18985: #
18986: 
18987:     if ($env{'form.cancreate_email'}) {
18988:         push(@contexts,'emailusername');
18989:         if (@statuses) {
18990:             foreach my $type (@statuses) {
18991:                 if (ref($infofields) eq 'ARRAY') {
18992:                     foreach my $field (@{$infofields}) {
18993:                         if ($env{'form.canmodify_emailusername_'.$type.'_'.$field} =~ /^(required|optional)$/) {
18994:                             $cancreate{'emailusername'}{$type}{$field} = $1;
18995:                         }
18996:                     }
18997:                 }
18998:             }
18999:         }
19000: #
19001: # Populate $cancreate{'notify'} hash ref with names of Domain Coordinators who are to be notified of
19002: # queued requests for self-creation of account verified by e-mail.
19003: #
19004: 
19005:         my @approvalnotify = &Apache::loncommon::get_env_multiple('form.selfcreationnotifyapproval');
19006:         @approvalnotify = sort(@approvalnotify);
19007:         $cancreate{'notify'}{'approval'} = join(',',@approvalnotify);
19008:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19009:             if (ref($curr_usercreation{'cancreate'}{'notify'}) eq 'HASH') {
19010:                 if ($curr_usercreation{'cancreate'}{'notify'}{'approval'} ne $cancreate{'notify'}{'approval'}) {
19011:                     push(@{$changes{'cancreate'}},'notify');
19012:                 }
19013:             } else {
19014:                 if ($cancreate{'notify'}{'approval'}) {
19015:                     push(@{$changes{'cancreate'}},'notify');
19016:                 }
19017:             }
19018:         } elsif ($cancreate{'notify'}{'approval'}) {
19019:             push(@{$changes{'cancreate'}},'notify');
19020:         }
19021: 
19022:         &process_captcha('cancreate',\%changes,\%savecaptcha,$curr_usercreation{'cancreate'});
19023:     }
19024: #  
19025: # Check if domain default is set appropriately, if self-creation of accounts is to be available for
19026: # institutional log-in.
19027: #
19028:     if (grep(/^login$/,@{$cancreate{'selfcreate'}})) {
19029:         if (!((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || 
19030:                ($domdefaults{'auth_def'} eq 'localauth'))) {
19031:             $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.').' '.
19032:                           &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.');
19033:         }
19034:     }
19035:     my @fields = ('lastname','firstname','middlename','generation',
19036:                   'permanentemail','id');
19037:     my @shibfields = (@fields,'inststatus');
19038:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19039: #
19040: # Where usernames may created for institutional log-in and/or institutional single sign on:
19041: # (a) populate $cancreate{'statustocreate'} array reference with institutional status types who
19042: # may self-create accounts 
19043: # (b) populate $save_usermodify{'selfcreate'} hash reference with status types, and information fields
19044: # which the user may supply, if institutional data is unavailable.
19045: #
19046:     if (($env{'form.cancreate_login'}) || ($env{'form.cancreate_sso'})) {
19047:         if (@types) {
19048:             @{$cancreate{'statustocreate'}} = &Apache::loncommon::get_env_multiple('form.statustocreate');
19049:             push(@contexts,'statustocreate');
19050:             foreach my $type (@types) {
19051:                 my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$type);
19052:                 foreach my $field (@fields) {
19053:                     if (grep(/^\Q$field\E$/,@modifiable)) {
19054:                         $save_usermodify{'selfcreate'}{$type}{$field} = 1;
19055:                     } else {
19056:                         $save_usermodify{'selfcreate'}{$type}{$field} = 0;
19057:                     }
19058:                 }
19059:             }
19060:             if (ref($curr_usermodify{'selfcreate'}) eq 'HASH') {
19061:                 foreach my $type (@types) {
19062:                     if (ref($curr_usermodify{'selfcreate'}{$type}) eq 'HASH') {
19063:                         foreach my $field (@fields) {
19064:                             if ($save_usermodify{'selfcreate'}{$type}{$field} ne
19065:                                 $curr_usermodify{'selfcreate'}{$type}{$field}) {
19066:                                 push(@{$changes{'selfcreate'}},$type);
19067:                                 last;
19068:                             }
19069:                         }
19070:                     }
19071:                 }
19072:             } else {
19073:                 foreach my $type (@types) {
19074:                     push(@{$changes{'selfcreate'}},$type);
19075:                 }
19076:             }
19077:         }
19078:         foreach my $field (@shibfields) {
19079:             if ($env{'form.shibenv_'.$field} ne '') {
19080:                 $cancreate{'shibenv'}{$field} = $env{'form.shibenv_'.$field};
19081:             }
19082:         }
19083:         if (ref($curr_usercreation{'cancreate'}) eq 'HASH') {
19084:             if (ref($curr_usercreation{'cancreate'}{'shibenv'}) eq 'HASH') {
19085:                 foreach my $field (@shibfields) {
19086:                     if ($env{'form.shibenv_'.$field} ne $curr_usercreation{'cancreate'}{'shibenv'}{$field}) {
19087:                         push(@{$changes{'cancreate'}},'shibenv');
19088:                     }
19089:                 }
19090:             } else {
19091:                 foreach my $field (@shibfields) {
19092:                     if ($env{'form.shibenv_'.$field}) {
19093:                         push(@{$changes{'cancreate'}},'shibenv');
19094:                         last;
19095:                     }
19096:                 }
19097:             }
19098:         }
19099:     }
19100:     foreach my $item (@contexts) {
19101:         if (ref($curr_usercreation{'cancreate'}{$item}) eq 'ARRAY') {
19102:             foreach my $curr (@{$curr_usercreation{'cancreate'}{$item}}) {
19103:                 if (ref($cancreate{$item}) eq 'ARRAY') {
19104:                     if (!grep(/^$curr$/,@{$cancreate{$item}})) {
19105:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19106:                             push(@{$changes{'cancreate'}},$item);
19107:                         }
19108:                     }
19109:                 }
19110:             }
19111:             if (ref($cancreate{$item}) eq 'ARRAY') {
19112:                 foreach my $type (@{$cancreate{$item}}) {
19113:                     if (!grep(/^$type$/,@{$curr_usercreation{'cancreate'}{$item}})) {
19114:                         if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19115:                             push(@{$changes{'cancreate'}},$item);
19116:                         }
19117:                     }
19118:                 }
19119:             }
19120:         } elsif (ref($curr_usercreation{'cancreate'}{$item}) eq 'HASH') {
19121:             if (ref($cancreate{$item}) eq 'HASH') {
19122:                 foreach my $type (keys(%{$curr_usercreation{'cancreate'}{$item}})) {
19123:                     if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19124:                         foreach my $field (keys(%{$curr_usercreation{'cancreate'}{$item}{$type}})) {
19125:                             unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19126:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19127:                                     push(@{$changes{'cancreate'}},$item);
19128:                                 }
19129:                             }
19130:                         }
19131:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19132:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19133:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19134:                                 push(@{$changes{'cancreate'}},$item);
19135:                             }
19136:                         }
19137:                     }
19138:                 }
19139:                 foreach my $type (keys(%{$cancreate{$item}})) {
19140:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19141:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19142:                             if (ref($curr_usercreation{'cancreate'}{$item}{$type}) eq 'HASH') {
19143:                                 unless ($curr_usercreation{'cancreate'}{$item}{$type}{$field} eq $cancreate{$item}{$type}{$field}) {
19144:                                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19145:                                         push(@{$changes{'cancreate'}},$item);
19146:                                     }
19147:                                 }
19148:                             } else {
19149:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19150:                                     push(@{$changes{'cancreate'}},$item);
19151:                                 }
19152:                             }
19153:                         }
19154:                     } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19155:                         if ($cancreate{$item}{$type} ne $curr_usercreation{'cancreate'}{$item}{$type}) {
19156:                             if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19157:                                 push(@{$changes{'cancreate'}},$item);
19158:                             }
19159:                         }
19160:                     }
19161:                 }
19162:             }
19163:         } elsif ($curr_usercreation{'cancreate'}{$item}) {
19164:             if (ref($cancreate{$item}) eq 'ARRAY') {
19165:                 if (!grep(/^\Q$curr_usercreation{'cancreate'}{$item}\E$/,@{$cancreate{$item}})) {
19166:                     if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19167:                         push(@{$changes{'cancreate'}},$item);
19168:                     }
19169:                 }
19170:             }
19171:         } elsif (($item eq 'selfcreateprocessing') || ($item eq 'emailverified') || ($item eq 'emailoptions')) {
19172:             if (ref($cancreate{$item}) eq 'HASH') {
19173:                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19174:                     push(@{$changes{'cancreate'}},$item);
19175:                 }
19176:             }
19177:         } elsif ($item eq 'emailusername') {
19178:             if (ref($cancreate{$item}) eq 'HASH') {
19179:                 foreach my $type (keys(%{$cancreate{$item}})) {
19180:                     if (ref($cancreate{$item}{$type}) eq 'HASH') {
19181:                         foreach my $field (keys(%{$cancreate{$item}{$type}})) {
19182:                             if ($cancreate{$item}{$type}{$field}) {
19183:                                 if (!grep(/^$item$/,@{$changes{'cancreate'}})) {
19184:                                     push(@{$changes{'cancreate'}},$item);
19185:                                 }
19186:                                 last;
19187:                             }
19188:                         }
19189:                     }
19190:                 }
19191:             }
19192:         }
19193:     }
19194: #
19195: # Populate %save_usercreate hash with updates to self-creation configuration.
19196: #
19197:     $save_usercreate{'cancreate'}{'captcha'} = $savecaptcha{'captcha'};
19198:     $save_usercreate{'cancreate'}{'recaptchakeys'} = $savecaptcha{'recaptchakeys'};
19199:     $save_usercreate{'cancreate'}{'recaptchaversion'} = $savecaptcha{'recaptchaversion'};
19200:     $save_usercreate{'cancreate'}{'selfcreate'} = $cancreate{'selfcreate'};
19201:     if (ref($cancreate{'notify'}) eq 'HASH') {
19202:         $save_usercreate{'cancreate'}{'notify'} = $cancreate{'notify'};
19203:     }
19204:     if (ref($cancreate{'selfcreateprocessing'}) eq 'HASH') {
19205:         $save_usercreate{'cancreate'}{'selfcreateprocessing'} = $cancreate{'selfcreateprocessing'};
19206:     }
19207:     if (ref($cancreate{'emailverified'}) eq 'HASH') {
19208:         $save_usercreate{'cancreate'}{'emailverified'} = $cancreate{'emailverified'};
19209:     }
19210:     if (ref($cancreate{'emailoptions'}) eq 'HASH') {
19211:         $save_usercreate{'cancreate'}{'emailoptions'} = $cancreate{'emailoptions'};
19212:     }
19213:     if (ref($cancreate{'emaildomain'}) eq 'HASH') {
19214:         $save_usercreate{'cancreate'}{'emaildomain'} = $cancreate{'emaildomain'};
19215:     }
19216:     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19217:         $save_usercreate{'cancreate'}{'statustocreate'} = $cancreate{'statustocreate'};
19218:     }
19219:     if (ref($cancreate{'shibenv'}) eq 'HASH') {
19220:         $save_usercreate{'cancreate'}{'shibenv'} = $cancreate{'shibenv'};
19221:     }
19222:     $save_usercreate{'cancreate'}{'emailusername'} = $cancreate{'emailusername'};
19223:     $save_usercreate{'email_rule'} = \%email_rule;
19224: 
19225:     my %userconfig_hash = (
19226:             usercreation     => \%save_usercreate,
19227:             usermodification => \%save_usermodify,
19228:             inststatus       => \%save_inststatus,
19229:     );
19230: 
19231:     my $putresult = &Apache::lonnet::put_dom('configuration',\%userconfig_hash,
19232:                                              $dom);
19233: #
19234: # Accumulate details of changes to domain configuration for self-creation of usernames in $resulttext
19235: #
19236:     if ($putresult eq 'ok') {
19237:         if (keys(%changes) > 0) {
19238:             $resulttext = &mt('Changes made:').'<ul>';
19239:             if (ref($changes{'cancreate'}) eq 'ARRAY') {
19240:                 my %lt = &selfcreation_types();
19241:                 foreach my $type (@{$changes{'cancreate'}}) {
19242:                     my $chgtext = '';
19243:                     if ($type eq 'selfcreate') {
19244:                         if (@{$cancreate{$type}} == 0) {
19245:                             $chgtext .= &mt('Self creation of a new user account is not permitted.');
19246:                         } else {
19247:                             $chgtext .= &mt('Self-creation of a new account is permitted for:').
19248:                                         '<ul>';
19249:                             foreach my $case (@{$cancreate{$type}}) {
19250:                                 $chgtext .= '<li>'.$selfcreatetypes{$case}.'</li>';
19251:                             }
19252:                             $chgtext .= '</ul>';
19253:                             if (ref($cancreate{$type}) eq 'ARRAY') {
19254:                                 if (grep(/^(login|sso)$/,@{$cancreate{$type}})) {
19255:                                     if (ref($cancreate{'statustocreate'}) eq 'ARRAY') {
19256:                                         if (@{$cancreate{'statustocreate'}} == 0) {
19257:                                             $chgtext .= '<span class="LC_warning">'.
19258:                                                         &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts via log-in or single sign-on.").
19259:                                                         '</span><br />';
19260:                                         }
19261:                                     }
19262:                                 }
19263:                                 if (grep(/^email$/,@{$cancreate{$type}})) {
19264:                                     if (!@statuses) {
19265:                                         $chgtext .= '<span class="LC_warning">'.
19266:                                                     &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.").
19267:                                                     '</span><br />';
19268: 
19269:                                     }
19270:                                 }
19271:                             }
19272:                         }
19273:                     } elsif ($type eq 'shibenv') {
19274:                         if (keys(%{$cancreate{$type}}) == 0) {
19275:                             $chgtext .= &mt('Shibboleth-autheticated user does not use environment variables to set user information').'<br />'; 
19276:                         } else {
19277:                             $chgtext .= &mt('Shibboleth-autheticated user information set from environment variables, as follows:').
19278:                                         '<ul>';
19279:                             foreach my $field (@shibfields) {
19280:                                 next if ($cancreate{$type}{$field} eq '');
19281:                                 if ($field eq 'inststatus') {
19282:                                     $chgtext .= '<li>'.&mt('Institutional status').' -- '.$cancreate{$type}{$field}.'</li>';
19283:                                 } else {
19284:                                     $chgtext .= '<li>'.$fieldtitles{$field}.' -- '.$cancreate{$type}{$field}.'</li>';
19285:                                 }
19286:                             }
19287:                             $chgtext .= '</ul>';
19288:                         }
19289:                     } elsif ($type eq 'statustocreate') {
19290:                         if ((ref($cancreate{'selfcreate'}) eq 'ARRAY') &&
19291:                             (ref($cancreate{'statustocreate'}) eq 'ARRAY')) {
19292:                             if (@{$cancreate{'selfcreate'}} > 0) {
19293:                                 if (@{$cancreate{'statustocreate'}} == 0) {
19294:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts set to 'None'.");
19295:                                     if (!grep(/^email$/,@{$cancreate{'selfcreate'}})) {
19296:                                         $chgtext .= '<br />'.
19297:                                                     '<span class="LC_warning">'.
19298:                                                     &mt("However, no institutional affiliations (including 'other') are currently permitted to create accounts.").
19299:                                                     '</span>';
19300:                                     }
19301:                                 } elsif (keys(%usertypes) > 0) {
19302:                                     if (grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19303:                                         $chgtext .= &mt('Creation of a new account for an institutional user is restricted to the following institutional affiliation(s):');
19304:                                     } else {
19305:                                         $chgtext .= &mt('Institutional affiliations permitted to create accounts with institutional authentication were set as follows:');
19306:                                     }
19307:                                     $chgtext .= '<ul>';
19308:                                     foreach my $case (@{$cancreate{$type}}) {
19309:                                         if ($case eq 'default') {
19310:                                             $chgtext .= '<li>'.$othertitle.'</li>';
19311:                                         } else {
19312:                                             $chgtext .= '<li>'.$usertypes{$case}.'</li>';
19313:                                         }
19314:                                     }
19315:                                     $chgtext .= '</ul>';
19316:                                     if (!grep(/^(login|sso)$/,@{$cancreate{'selfcreate'}})) {
19317:                                         $chgtext .= '<span class="LC_warning">'.
19318:                                                     &mt('However, users authenticated by institutional login/single sign on are not currently permitted to create accounts.').
19319:                                                     '</span>';
19320:                                     }
19321:                                 }
19322:                             } else {
19323:                                 if (@{$cancreate{$type}} == 0) {
19324:                                     $chgtext .= &mt("Institutional affiliations permitted to create accounts were set to 'none'.");
19325:                                 } else {
19326:                                     $chgtext .= &mt('Although institutional affiliations permitted to create accounts were changed, self creation of accounts is not currently permitted for any authentication types.');
19327:                                 }
19328:                             }
19329:                             $chgtext .= '<br />';
19330:                         }
19331:                     } elsif ($type eq 'selfcreateprocessing') {
19332:                         my %choices = &Apache::lonlocal::texthash (
19333:                                                                     automatic => 'Automatic approval',
19334:                                                                     approval  => 'Queued for approval',
19335:                                                                   );
19336:                         if (@types) {
19337:                             if (@statuses) {
19338:                                 $chgtext .= &mt('Processing of requests to create account with e-mail verification set as follows:'). 
19339:                                             '<ul>';
19340:                                 foreach my $status (@statuses) {
19341:                                     if ($status eq 'default') {
19342:                                         $chgtext .= '<li>'.$othertitle.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19343:                                     } else {
19344:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$choices{$cancreate{'selfcreateprocessing'}{$status}}.'</li>';
19345:                                     }
19346:                                 }
19347:                                 $chgtext .= '</ul>';
19348:                             }
19349:                         } else {
19350:                             $chgtext .= &mt('Processing of requests to create account with e-mail verification set to: "[_1]"',
19351:                                             $choices{$cancreate{'selfcreateprocessing'}{'default'}});
19352:                         }
19353:                     } elsif ($type eq 'emailverified') {
19354:                         my %options = &Apache::lonlocal::texthash (
19355:                                                                     all   => 'Same as e-mail',
19356:                                                                     first => 'Omit @domain',
19357:                                                                     free  => 'Free to choose',
19358:                                                                   );
19359:                         if (@types) {
19360:                             if (@statuses) {
19361:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, username is set as follows:').
19362:                                             '<ul>';
19363:                                 foreach my $status (@statuses) {
19364:                                     if ($status eq 'default') {
19365:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19366:                                     } else {
19367:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailverified'}{$status}}.'</li>';
19368:                                     }
19369:                                 }
19370:                                 $chgtext .= '</ul>';
19371:                             }
19372:                         } else {
19373:                             $chgtext .= &mt("For self-created accounts verified by e-mail address, user's username is: '[_1]'",
19374:                                             $options{$cancreate{'emailverified'}{'default'}});
19375:                         }
19376:                     } elsif ($type eq 'emailoptions') {
19377:                         my %options = &Apache::lonlocal::texthash (
19378:                                                                     any     => 'Any e-mail',
19379:                                                                     inst    => 'Institutional only',
19380:                                                                     noninst => 'Non-institutional only',
19381:                                                                     custom  => 'Custom restrictions',
19382:                                                                   );
19383:                         if (@types) {
19384:                             if (@statuses) {
19385:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, requirements for e-mail address are as follows:').
19386:                                             '<ul>';
19387:                                 foreach my $status (@statuses) {
19388:                                     if ($type eq 'default') {
19389:                                         $chgtext .= '<li>'.$othertitle.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19390:                                     } else {
19391:                                         $chgtext .= '<li>'.$usertypes{$status}.' -- '.$options{$cancreate{'emailoptions'}{$status}}.'</li>';
19392:                                     }
19393:                                 }
19394:                                 $chgtext .= '</ul>';
19395:                             }
19396:                         } else {
19397:                             if ($cancreate{'emailoptions'}{'default'} eq 'any') {
19398:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, any e-mail may be used');
19399:                             } else {
19400:                                 $chgtext .= &mt('For self-created accounts verified by e-mail address, e-mail restricted to: "[_1]"',
19401:                                                 $options{$cancreate{'emailoptions'}{'default'}});
19402:                             }
19403:                         }
19404:                     } elsif ($type eq 'emaildomain') {
19405:                         my $output;
19406:                         if (@statuses) {
19407:                             foreach my $type (@statuses) {
19408:                                 if (ref($cancreate{'emaildomain'}{$type}) eq 'HASH') {
19409:                                     if ($cancreate{'emailoptions'}{$type} eq 'inst') {
19410:                                         if ($type eq 'default') {
19411:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19412:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19413:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19414:                                             } else {
19415:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address needs to end: [_1]",
19416:                                                                                         $cancreate{'emaildomain'}{$type}{'inst'}).'</li>';
19417:                                             }
19418:                                         } else {
19419:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19420:                                                 ($cancreate{'emaildomain'}{$type}{'inst'} eq '')) {
19421:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19422:                                             } else {
19423:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address needs to end: [_1]",
19424:                                                                                               $cancreate{'emaildomain'}{$type}{'inst'}).'</li>'; 
19425:                                             }
19426:                                         }
19427:                                     } elsif ($cancreate{'emailoptions'}{$type} eq 'noninst') {
19428:                                         if ($type eq 'default') {
19429:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19430:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19431:                                                 $output = '<li>'.$othertitle.' -- '.&mt('No restriction on e-mail domain').'</li>';
19432:                                             } else {
19433:                                                 $output = '<li>'.$othertitle.' -- '.&mt("User's e-mail address must not end: [_1]",
19434:                                                                                         $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';
19435:                                             }
19436:                                         } else {
19437:                                             if ((ref($cancreate{'emaildomain'}{$type}) ne 'HASH') ||
19438:                                                 ($cancreate{'emaildomain'}{$type}{'noninst'} eq '')) {
19439:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt('No restriction on e-mail domain').'</li>';
19440:                                             } else {
19441:                                                 $output = '<li>'.$usertypes{$type}.' -- '.&mt("User's e-mail address must not end: [_1]",
19442:                                                                                                 $cancreate{'emaildomain'}{$type}{'noninst'}).'</li>';   
19443:                                             }
19444:                                         }
19445:                                     }
19446:                                 }
19447:                             }
19448:                         }
19449:                         if ($output ne '') {
19450:                             $chgtext .= &mt('For self-created accounts verified by e-mail address:').
19451:                                         '<ul>'.$output.'</ul>';
19452:                         }
19453:                     } elsif ($type eq 'captcha') {
19454:                         if ($savecaptcha{$type} eq 'notused') {
19455:                             $chgtext .= &mt('No CAPTCHA validation in use for self-creation screen.');
19456:                         } else {
19457:                             my %captchas = &captcha_phrases();
19458:                             if ($captchas{$savecaptcha{$type}}) {
19459:                                 $chgtext .= &mt("Validation for self-creation screen set to $captchas{$savecaptcha{$type}}.");
19460:                             } else {
19461:                                 $chgtext .= &mt('Validation for self-creation screen set to unknown type.');
19462:                             }
19463:                         }
19464:                     } elsif ($type eq 'recaptchakeys') {
19465:                         my ($privkey,$pubkey);
19466:                         if (ref($savecaptcha{$type}) eq 'HASH') {
19467:                             $pubkey = $savecaptcha{$type}{'public'};
19468:                             $privkey = $savecaptcha{$type}{'private'};
19469:                         }
19470:                         $chgtext .= &mt('ReCAPTCHA keys changes').'<ul>';
19471:                         if (!$pubkey) {
19472:                             $chgtext .= '<li>'.&mt('Public key deleted').'</li>';
19473:                         } else {
19474:                             $chgtext .= '<li>'.&mt('Public key set to [_1]',$pubkey).'</li>';
19475:                         }
19476:                         if (!$privkey) {
19477:                             $chgtext .= '<li>'.&mt('Private key deleted').'</li>';
19478:                         } else {
19479:                             $chgtext .= '<li>'.&mt('Private key set to [_1]',$pubkey).'</li>';
19480:                         }
19481:                         $chgtext .= '</ul>';
19482:                     } elsif ($type eq 'recaptchaversion') {
19483:                         if ($savecaptcha{'captcha'} eq 'recaptcha') {
19484:                             $chgtext .= &mt('ReCAPTCHA set to version [_1]',$savecaptcha{$type});
19485:                         }
19486:                     } elsif ($type eq 'emailusername') {
19487:                         if (ref($cancreate{'emailusername'}) eq 'HASH') {
19488:                             if (@statuses) {
19489:                                 foreach my $type (@statuses) {
19490:                                     if (ref($cancreate{'emailusername'}{$type}) eq 'HASH') {
19491:                                         if (keys(%{$cancreate{'emailusername'}{$type}}) > 0) {
19492:                                             $chgtext .= &mt('When self-creating account with e-mail verification, the following information will be provided by [_1]:',"'$usertypes{$type}'").
19493:                                                     '<ul>';
19494:                                             foreach my $field (@{$infofields}) {
19495:                                                 if ($cancreate{'emailusername'}{$type}{$field}) {
19496:                                                     $chgtext .= '<li>'.$infotitles->{$field}.'</li>';
19497:                                                 }
19498:                                             }
19499:                                             $chgtext .= '</ul>';
19500:                                         } else {
19501:                                             $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19502:                                         }
19503:                                     } else {
19504:                                         $chgtext .= &mt('When self creating account with e-mail verification, no information besides e-mail address will be provided by [_1].',"'$usertypes{$type}'").'<br />';
19505:                                     }
19506:                                 }
19507:                             }
19508:                         }
19509:                     } elsif ($type eq 'notify') {
19510:                         my $numapprove = 0;
19511:                         if (ref($changes{'cancreate'}) eq 'ARRAY') {
19512:                             if ((grep(/^notify$/,@{$changes{'cancreate'}})) && (ref($cancreate{'notify'}) eq 'HASH')) {
19513:                                 if ($cancreate{'notify'}{'approval'}) {
19514:                                     $chgtext .= &mt('Notification of username requests requiring approval will be sent to: ').$cancreate{'notify'}{'approval'};
19515:                                     $numapprove ++;
19516:                                 }
19517:                             }
19518:                         }
19519:                         unless ($numapprove) {
19520:                             $chgtext .= &mt('No Domain Coordinators will receive notification of username requests requiring approval.');
19521:                         }
19522:                     }
19523:                     if ($chgtext) {
19524:                         $resulttext .= '<li>'.$chgtext.'</li>';
19525:                     }
19526:                 }
19527:             }
19528:             if ((ref($changes{'email_rule'}) eq 'ARRAY') && (@{$changes{'email_rule'}} > 0)) {
19529:                 my ($emailrules,$emailruleorder) =
19530:                     &Apache::lonnet::inst_userrules($dom,'email');
19531:                 foreach my $type (@{$changes{'email_rule'}}) {
19532:                     if (ref($email_rule{$type}) eq 'ARRAY') {
19533:                         my $chgtext = '<ul>';
19534:                         foreach my $rule (@{$email_rule{$type}}) {
19535:                             if (ref($emailrules->{$rule}) eq 'HASH') {
19536:                                 $chgtext .= '<li>'.$emailrules->{$rule}{'name'}.'</li>';
19537:                             }
19538:                         }
19539:                         $chgtext .= '</ul>';
19540:                         my $typename;
19541:                         if (@types) {
19542:                             if ($type eq 'default') {
19543:                                 $typename = $othertitle;
19544:                             } else {
19545:                                 $typename = $usertypes{$type};
19546:                             } 
19547:                             $chgtext .= &mt('(Affiliation: [_1])',$typename);
19548:                         }
19549:                         if (@{$email_rule{$type}} > 0) {
19550:                             $resulttext .= '<li>'.
19551:                                            &mt('Accounts may not be created by users verified by e-mail, for e-mail addresses of the following types: ',
19552:                                                $usertypes{$type}).
19553:                                            $chgtext.
19554:                                            '</li>';
19555:                         } else {
19556:                             $resulttext .= '<li>'.
19557:                                            &mt('There are now no restrictions on e-mail addresses which may be used for verification when a user requests an account.').
19558:                                            '</li>'.
19559:                                            &mt('(Affiliation: [_1])',$typename);
19560:                         }
19561:                     }
19562:                 }
19563:             }
19564:             if (ref($changes{'inststatus'}) eq 'ARRAY') {
19565:                 if (ref($save_inststatus{'inststatusguest'}) eq 'ARRAY') {
19566:                     if (@{$save_inststatus{'inststatusguest'}} > 0) {
19567:                         my $chgtext = '<ul>';
19568:                         foreach my $type (@{$save_inststatus{'inststatusguest'}}) {
19569:                             $chgtext .= '<li>'.$usertypes{$type}.'</li>';
19570:                         }
19571:                         $chgtext .= '</ul>';
19572:                         $resulttext .= '<li>'.
19573:                                        &mt('A user will self-report one of the following affiliations when requesting an account verified by e-mail: ').
19574:                                           $chgtext.
19575:                                        '</li>';
19576:                     } else {
19577:                         $resulttext .= '<li>'.
19578:                                        &mt('No affiliations available for self-reporting when requesting an account verified by e-mail.').
19579:                                        '</li>';
19580:                     }
19581:                 }
19582:             }
19583:             if (ref($changes{'selfcreate'}) eq 'ARRAY') {
19584:                 $resulttext .= '<li>'.&mt('When self-creating institutional account:').'<ul>';
19585:                 my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19586:                 foreach my $type (@{$changes{'selfcreate'}}) {
19587:                     my $typename = $type;
19588:                     if (keys(%usertypes) > 0) {
19589:                         if ($usertypes{$type} ne '') {
19590:                             $typename = $usertypes{$type};
19591:                         }
19592:                     }
19593:                     my @modifiable;
19594:                     $resulttext .= '<li>'.
19595:                                     &mt('Self-creation of account by users with status: [_1]',
19596:                                         '<span class="LC_cusr_emph">'.$typename.'</span>').
19597:                                     ' - '.&mt('modifiable fields (if institutional data blank): ');
19598:                     foreach my $field (@fields) {
19599:                         if ($save_usermodify{'selfcreate'}{$type}{$field}) {
19600:                             push(@modifiable,'<b>'.$fieldtitles{$field}.'</b>');
19601:                         }
19602:                     }
19603:                     if (@modifiable > 0) {
19604:                         $resulttext .= join(', ',@modifiable);
19605:                     } else {
19606:                         $resulttext .= &mt('none');
19607:                     }
19608:                     $resulttext .= '</li>';
19609:                 }
19610:                 $resulttext .= '</ul></li>';
19611:             }
19612:             $resulttext .= '</ul>';
19613:             my $cachetime = 24*60*60;
19614:             $domdefaults{'inststatusguest'} = $save_inststatus{'inststatusguest'};
19615:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
19616:             if (ref($lastactref) eq 'HASH') {
19617:                 $lastactref->{'domdefaults'} = 1;
19618:             }
19619:         } else {
19620:             $resulttext = &mt('No changes made to self-creation settings');
19621:         }
19622:     } else {
19623:         $resulttext = '<span class="LC_error">'.
19624:             &mt('An error occurred: [_1]',$putresult).'</span>';
19625:     }
19626:     if ($warningmsg ne '') {
19627:         $resulttext .= '<br /><span class="LC_warning">'.$warningmsg.'</span><br />';
19628:     }
19629:     return $resulttext;
19630: }
19631: 
19632: sub process_captcha {
19633:     my ($container,$changes,$newsettings,$currsettings) = @_;
19634:     return unless ((ref($changes) eq 'HASH') && (ref($newsettings) eq 'HASH'));
19635:     $newsettings->{'captcha'} = $env{'form.'.$container.'_captcha'};
19636:     unless ($newsettings->{'captcha'} eq 'recaptcha' || $newsettings->{'captcha'} eq 'notused') {
19637:         $newsettings->{'captcha'} = 'original';
19638:     }
19639:     my %current;
19640:     if (ref($currsettings) eq 'HASH') {
19641:         %current = %{$currsettings};
19642:     }
19643:     if ($current{'captcha'} ne $newsettings->{'captcha'}) {
19644:         if ($container eq 'cancreate') {
19645:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19646:                 push(@{$changes->{'cancreate'}},'captcha');
19647:             } elsif (!defined($changes->{'cancreate'})) {
19648:                 $changes->{'cancreate'} = ['captcha'];
19649:             }
19650:         } elsif ($container eq 'passwords') {
19651:             $changes->{'reset'} = 1;
19652:         } else {
19653:             $changes->{'captcha'} = 1;
19654:         }
19655:     }
19656:     my ($newpub,$newpriv,$currpub,$currpriv,$newversion,$currversion);
19657:     if ($newsettings->{'captcha'} eq 'recaptcha') {
19658:         $newpub = $env{'form.'.$container.'_recaptchapub'};
19659:         $newpriv = $env{'form.'.$container.'_recaptchapriv'};
19660:         $newpub =~ s/[^\w\-]//g;
19661:         $newpriv =~ s/[^\w\-]//g;
19662:         $newsettings->{'recaptchakeys'} = {
19663:                                              public  => $newpub,
19664:                                              private => $newpriv,
19665:                                           };
19666:         $newversion = $env{'form.'.$container.'_recaptchaversion'};
19667:         $newversion =~ s/\D//g;
19668:         if ($newversion ne '2') {
19669:             $newversion = 1;
19670:         }
19671:         $newsettings->{'recaptchaversion'} = $newversion;
19672:     }
19673:     if (ref($current{'recaptchakeys'}) eq 'HASH') {
19674:         $currpub = $current{'recaptchakeys'}{'public'};
19675:         $currpriv = $current{'recaptchakeys'}{'private'};
19676:         unless ($newsettings->{'captcha'} eq 'recaptcha') {
19677:             $newsettings->{'recaptchakeys'} = {
19678:                                                  public  => '',
19679:                                                  private => '',
19680:                                               }
19681:         }
19682:     }
19683:     if ($current{'captcha'} eq 'recaptcha') {
19684:         $currversion = $current{'recaptchaversion'};
19685:         if ($currversion ne '2') {
19686:             $currversion = 1;
19687:         }
19688:     }
19689:     if ($currversion ne $newversion) {
19690:         if ($container eq 'cancreate') {
19691:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19692:                 push(@{$changes->{'cancreate'}},'recaptchaversion');
19693:             } elsif (!defined($changes->{'cancreate'})) {
19694:                 $changes->{'cancreate'} = ['recaptchaversion'];
19695:             }
19696:         } elsif ($container eq 'passwords') {
19697:             $changes->{'reset'} = 1;
19698:         } else {
19699:             $changes->{'recaptchaversion'} = 1;
19700:         }
19701:     }
19702:     if (($newpub ne $currpub) || ($newpriv ne $currpriv)) {
19703:         if ($container eq 'cancreate') {
19704:             if (ref($changes->{'cancreate'}) eq 'ARRAY') {
19705:                 push(@{$changes->{'cancreate'}},'recaptchakeys');
19706:             } elsif (!defined($changes->{'cancreate'})) {
19707:                 $changes->{'cancreate'} = ['recaptchakeys'];
19708:             }
19709:         } elsif ($container eq 'passwords') {
19710:             $changes->{'reset'} = 1;
19711:         } else {
19712:             $changes->{'recaptchakeys'} = 1;
19713:         }
19714:     }
19715:     return;
19716: }
19717: 
19718: sub modify_usermodification {
19719:     my ($dom,%domconfig) = @_;
19720:     my ($resulttext,%curr_usermodification,%changes,%modifyhash);
19721:     if (ref($domconfig{'usermodification'}) eq 'HASH') {
19722:         foreach my $key (keys(%{$domconfig{'usermodification'}})) {
19723:             if ($key eq 'selfcreate') {
19724:                 $modifyhash{$key} = $domconfig{'usermodification'}{$key};
19725:             } else {  
19726:                 $curr_usermodification{$key} = $domconfig{'usermodification'}{$key};
19727:             }
19728:         }
19729:     }
19730:     my @contexts = ('author','course');
19731:     my %context_title = (
19732:                            author => 'In author context',
19733:                            course => 'In course context',
19734:                         );
19735:     my @fields = ('lastname','firstname','middlename','generation',
19736:                   'permanentemail','id');
19737:     my %roles = (
19738:                   author => ['ca','aa'],
19739:                   course => ['st','ep','ta','in','cr'],
19740:                 );
19741:     my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
19742:     foreach my $context (@contexts) {
19743:         foreach my $role (@{$roles{$context}}) {
19744:             my @modifiable =  &Apache::loncommon::get_env_multiple('form.canmodify_'.$role);
19745:             foreach my $item (@fields) {
19746:                 if (grep(/^\Q$item\E$/,@modifiable)) {
19747:                     $modifyhash{$context}{$role}{$item} = 1;
19748:                 } else {
19749:                     $modifyhash{$context}{$role}{$item} = 0;
19750:                 }
19751:             }
19752:         }
19753:         if (ref($curr_usermodification{$context}) eq 'HASH') {
19754:             foreach my $role (@{$roles{$context}}) {
19755:                 if (ref($curr_usermodification{$context}{$role}) eq 'HASH') {
19756:                     foreach my $field (@fields) {
19757:                         if ($modifyhash{$context}{$role}{$field} ne 
19758:                                 $curr_usermodification{$context}{$role}{$field}) {
19759:                             push(@{$changes{$context}},$role);
19760:                             last;
19761:                         }
19762:                     }
19763:                 }
19764:             }
19765:         } else {
19766:             foreach my $context (@contexts) {
19767:                 foreach my $role (@{$roles{$context}}) {
19768:                     push(@{$changes{$context}},$role);
19769:                 }
19770:             }
19771:         }
19772:     }
19773:     my %usermodification_hash =  (
19774:                                    usermodification => \%modifyhash,
19775:                                  );
19776:     my $putresult = &Apache::lonnet::put_dom('configuration',
19777:                                              \%usermodification_hash,$dom);
19778:     if ($putresult eq 'ok') {
19779:         if (keys(%changes) > 0) {
19780:             $resulttext = &mt('Changes made: ').'<ul>';
19781:             foreach my $context (@contexts) {
19782:                 if (ref($changes{$context}) eq 'ARRAY') {
19783:                     $resulttext .= '<li>'.$context_title{$context}.':<ul>';
19784:                     if (ref($changes{$context}) eq 'ARRAY') {
19785:                         foreach my $role (@{$changes{$context}}) {
19786:                             my $rolename;
19787:                             if ($role eq 'cr') {
19788:                                 $rolename = &mt('Custom');
19789:                             } else {
19790:                                 $rolename = &Apache::lonnet::plaintext($role);
19791:                             }
19792:                             my @modifiable;
19793:                             $resulttext .= '<li><span class="LC_cusr_emph">'.&mt('Target user with [_1] role',$rolename).'</span> - '.&mt('modifiable fields: ');
19794:                             foreach my $field (@fields) {
19795:                                 if ($modifyhash{$context}{$role}{$field}) {
19796:                                     push(@modifiable,$fieldtitles{$field});
19797:                                 }
19798:                             }
19799:                             if (@modifiable > 0) {
19800:                                 $resulttext .= join(', ',@modifiable);
19801:                             } else {
19802:                                 $resulttext .= &mt('none'); 
19803:                             }
19804:                             $resulttext .= '</li>';
19805:                         }
19806:                         $resulttext .= '</ul></li>';
19807:                     }
19808:                 }
19809:             }
19810:             $resulttext .= '</ul>';
19811:         } else {
19812:             $resulttext = &mt('No changes made to user modification settings');
19813:         }
19814:     } else {
19815:         $resulttext = '<span class="LC_error">'.
19816:             &mt('An error occurred: [_1]',$putresult).'</span>';
19817:     }
19818:     return $resulttext;
19819: }
19820: 
19821: sub modify_defaults {
19822:     my ($dom,$lastactref,%domconfig) = @_;
19823:     my ($resulttext,$mailmsgtxt,%newvalues,%changes,@errors);
19824:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
19825:     my @items = ('auth_def','auth_arg_def','lang_def','timezone_def','datelocale_def',
19826:                  'portal_def');
19827:     my @authtypes = ('internal','krb4','krb5','localauth','lti');
19828:     foreach my $item (@items) {
19829:         $newvalues{$item} = $env{'form.'.$item};
19830:         if ($item eq 'auth_def') {
19831:             if ($newvalues{$item} ne '') {
19832:                 if (!grep(/^\Q$newvalues{$item}\E$/,@authtypes)) {
19833:                     push(@errors,$item);
19834:                 }
19835:             }
19836:         } elsif ($item eq 'lang_def') {
19837:             if ($newvalues{$item} ne '') {
19838:                 if ($newvalues{$item} =~ /^(\w+)/) {
19839:                     my $langcode = $1;
19840:                     if ($langcode ne 'x_chef') {
19841:                         if (code2language($langcode) eq '') {
19842:                             push(@errors,$item);
19843:                         }
19844:                     }
19845:                 } else {
19846:                     push(@errors,$item);
19847:                 }
19848:             }
19849:         } elsif ($item eq 'timezone_def') {
19850:             if ($newvalues{$item} ne '') {
19851:                 if (!DateTime::TimeZone->is_valid_name($newvalues{$item})) {
19852:                     push(@errors,$item);   
19853:                 }
19854:             }
19855:         } elsif ($item eq 'datelocale_def') {
19856:             if ($newvalues{$item} ne '') {
19857:                 my @datelocale_ids = DateTime::Locale->ids();
19858:                 if (!grep(/^\Q$newvalues{$item}\E$/,@datelocale_ids)) {
19859:                     push(@errors,$item);
19860:                 }
19861:             }
19862:         } elsif ($item eq 'portal_def') {
19863:             if ($newvalues{$item} ne '') {
19864:                 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])\/?$/) {
19865:                     push(@errors,$item);
19866:                 }
19867:             }
19868:         }
19869:         if (grep(/^\Q$item\E$/,@errors)) {
19870:             $newvalues{$item} = $domdefaults{$item};
19871:         } elsif ($domdefaults{$item} ne $newvalues{$item}) {
19872:             $changes{$item} = 1;
19873:         }
19874:         $domdefaults{$item} = $newvalues{$item};
19875:     }
19876:     my %staticdefaults = (
19877:                            'intauth_cost'   => 10,
19878:                            'intauth_check'  => 0,
19879:                            'intauth_switch' => 0,
19880:                          );
19881:     foreach my $item ('intauth_cost','intauth_check','intauth_switch') {
19882:         if (exists($domdefaults{$item})) {
19883:             $newvalues{$item} = $domdefaults{$item};
19884:         } else {
19885:             $newvalues{$item} = $staticdefaults{$item};
19886:         }
19887:     }
19888:     my %defaults_hash = (
19889:                          defaults => \%newvalues,
19890:                         );
19891:     my $title = &defaults_titles();
19892: 
19893:     my $currinststatus;
19894:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
19895:         $currinststatus = $domconfig{'inststatus'};
19896:     } else {
19897:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
19898:         $currinststatus = {
19899:                              inststatustypes => $usertypes,
19900:                              inststatusorder => $types,
19901:                              inststatusguest => [],
19902:                           };
19903:     }
19904:     my @todelete = &Apache::loncommon::get_env_multiple('form.inststatus_delete');
19905:     my @allpos;
19906:     my %alltypes;
19907:     my @inststatusguest;
19908:     if (ref($currinststatus->{'inststatusguest'}) eq 'ARRAY') {
19909:         foreach my $type (@{$currinststatus->{'inststatusguest'}}) {
19910:             unless (grep(/^\Q$type\E$/,@todelete)) {
19911:                 push(@inststatusguest,$type);
19912:             }
19913:         }
19914:     }
19915:     my ($currtitles,$currorder);
19916:     if (ref($currinststatus) eq 'HASH') {
19917:         if (ref($currinststatus->{'inststatusorder'}) eq 'ARRAY') {
19918:             foreach my $type (@{$currinststatus->{'inststatusorder'}}) {
19919:                 if (ref($currinststatus->{inststatustypes}) eq 'HASH') {
19920:                     if ($currinststatus->{inststatustypes}->{$type} ne '') {
19921:                         $currtitles .= $currinststatus->{inststatustypes}->{$type}.',';
19922:                     }
19923:                 }
19924:                 unless (grep(/^\Q$type\E$/,@todelete)) { 
19925:                     my $position = $env{'form.inststatus_pos_'.$type};
19926:                     $position =~ s/\D+//g;
19927:                     $allpos[$position] = $type;
19928:                     $alltypes{$type} = $env{'form.inststatus_title_'.$type};
19929:                     $alltypes{$type} =~ s/`//g;
19930:                 }
19931:             }
19932:             $currorder = join(',',@{$currinststatus->{'inststatusorder'}});
19933:             $currtitles =~ s/,$//;
19934:         }
19935:     }
19936:     if ($env{'form.addinststatus'}) {
19937:         my $newtype = $env{'form.addinststatus'};
19938:         $newtype =~ s/\W//g;
19939:         unless (exists($alltypes{$newtype})) {
19940:             $alltypes{$newtype} = $env{'form.addinststatus_title'};
19941:             $alltypes{$newtype} =~ s/`//g; 
19942:             my $position = $env{'form.addinststatus_pos'};
19943:             $position =~ s/\D+//g;
19944:             if ($position ne '') {
19945:                 $allpos[$position] = $newtype;
19946:             }
19947:         }
19948:     }
19949:     my @orderedstatus;
19950:     foreach my $type (@allpos) {
19951:         unless (($type eq '') || (grep(/^\Q$type\E$/,@orderedstatus))) {
19952:             push(@orderedstatus,$type);
19953:         }
19954:     }
19955:     foreach my $type (keys(%alltypes)) {
19956:         unless (grep(/^\Q$type\E$/,@orderedstatus)) {
19957:             delete($alltypes{$type});
19958:         }
19959:     }
19960:     $defaults_hash{'inststatus'} = {
19961:                                      inststatustypes => \%alltypes,
19962:                                      inststatusorder => \@orderedstatus,
19963:                                      inststatusguest => \@inststatusguest,
19964:                                    };
19965:     if (ref($defaults_hash{'inststatus'}) eq 'HASH') {
19966:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
19967:             $domdefaults{$item} = $defaults_hash{'inststatus'}{$item};
19968:         }
19969:     }
19970:     if ($currorder ne join(',',@orderedstatus)) {
19971:         $changes{'inststatus'}{'inststatusorder'} = 1;
19972:     }
19973:     my $newtitles;
19974:     foreach my $item (@orderedstatus) {
19975:         $newtitles .= $alltypes{$item}.',';
19976:     }
19977:     $newtitles =~ s/,$//;
19978:     if ($currtitles ne $newtitles) {
19979:         $changes{'inststatus'}{'inststatustypes'} = 1;
19980:     }
19981:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaults_hash,
19982:                                              $dom);
19983:     if ($putresult eq 'ok') {
19984:         if (keys(%changes) > 0) {
19985:             $resulttext = &mt('Changes made:').'<ul>';
19986:             my $version = &Apache::lonnet::get_server_loncaparev($dom);
19987:             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";
19988:             foreach my $item (sort(keys(%changes))) {
19989:                 if ($item eq 'inststatus') {
19990:                     if (ref($changes{'inststatus'}) eq 'HASH') {
19991:                         if (@orderedstatus) {
19992:                             $resulttext .= '<li>'.&mt('Institutional user status types set to:').' ';
19993:                             foreach my $type (@orderedstatus) { 
19994:                                 $resulttext .= $alltypes{$type}.', ';
19995:                             }
19996:                             $resulttext =~ s/, $//;
19997:                             $resulttext .= '</li>';
19998:                         } else {
19999:                             $resulttext .= '<li>'.&mt('Institutional user status types deleted').'</li>'; 
20000:                         }
20001:                     }
20002:                 } else {
20003:                     my $value = $env{'form.'.$item};
20004:                     if ($value eq '') {
20005:                         $value = &mt('none');
20006:                     } elsif ($item eq 'auth_def') {
20007:                         my %authnames = &authtype_names();
20008:                         my %shortauth = (
20009:                                           internal   => 'int',
20010:                                           krb4       => 'krb4',
20011:                                           krb5       => 'krb5',
20012:                                           localauth  => 'loc',
20013:                                           lti        => 'lti',
20014:                         );
20015:                         $value = $authnames{$shortauth{$value}};
20016:                     }
20017:                     $resulttext .= '<li>'.&mt('[_1] set to "[_2]"',$title->{$item},$value).'</li>';
20018:                     $mailmsgtext .= "$title->{$item} set to $value\n";  
20019:                 }
20020:             }
20021:             $resulttext .= '</ul>';
20022:             $mailmsgtext .= "\n";
20023:             my $cachetime = 24*60*60;
20024:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20025:             if (ref($lastactref) eq 'HASH') {
20026:                 $lastactref->{'domdefaults'} = 1;
20027:             }
20028:             if ($changes{'auth_def'} || $changes{'auth_arg_def'} || $changes{'lang_def'} || $changes{'datelocale_def'}) {
20029:                 my $notify = 1;
20030:                 if (ref($domconfig{'contacts'}) eq 'HASH') {
20031:                     if ($domconfig{'contacts'}{'reportupdates'} == 0) {
20032:                         $notify = 0;
20033:                     }
20034:                 }
20035:                 if ($notify) {
20036:                     &Apache::lonmsg::sendemail('installrecord@loncapa.org',
20037:                                                "LON-CAPA Domain Settings Change - $dom",
20038:                                                $mailmsgtext);
20039:                 }
20040:             }
20041:         } else {
20042:             $resulttext = &mt('No changes made to default authentication/language/timezone settings');
20043:         }
20044:     } else {
20045:         $resulttext = '<span class="LC_error">'.
20046:             &mt('An error occurred: [_1]',$putresult).'</span>';
20047:     }
20048:     if (@errors > 0) {
20049:         $resulttext .= '<br />'.&mt('The following were left unchanged because the values entered were invalid:');
20050:         foreach my $item (@errors) {
20051:             $resulttext .= ' "'.$title->{$item}.'",';
20052:         }
20053:         $resulttext =~ s/,$//;
20054:     }
20055:     return $resulttext;
20056: }
20057: 
20058: sub modify_scantron {
20059:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20060:     my ($resulttext,%confhash,%changes,$errors);
20061:     my $custom = 'custom.tab';
20062:     my $default = 'default.tab';
20063:     my $servadm = $r->dir_config('lonAdmEMail');
20064:     my ($configuserok,$author_ok,$switchserver) =
20065:         &config_check($dom,$confname,$servadm);
20066:     if ($env{'form.scantronformat.filename'} ne '') {
20067:         my $error;
20068:         if ($configuserok eq 'ok') {
20069:             if ($switchserver) {
20070:                 $error = &mt("Upload of bubblesheet format file is not permitted to this server: [_1]",$switchserver);
20071:             } else {
20072:                 if ($author_ok eq 'ok') {
20073:                     my ($result,$scantronurl) =
20074:                         &publishlogo($r,'upload','scantronformat',$dom,
20075:                                      $confname,'scantron','','',$custom);
20076:                     if ($result eq 'ok') {
20077:                         $confhash{'scantron'}{'scantronformat'} = $scantronurl;
20078:                         $changes{'scantronformat'} = 1;
20079:                     } else {
20080:                         $error = &mt("Upload of [_1] failed because an error occurred publishing the file in RES space. Error was: [_2].",$custom,$result);
20081:                     }
20082:                 } else {
20083:                     $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);
20084:                 }
20085:             }
20086:         } else {
20087:             $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);
20088:         }
20089:         if ($error) {
20090:             &Apache::lonnet::logthis($error);
20091:             $errors .= '<li><span class="LC_error">'.$error.'</span></li>';
20092:         }
20093:     }
20094:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20095:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
20096:             if ($env{'form.scantronformat_del'}) {
20097:                 $confhash{'scantron'}{'scantronformat'} = '';
20098:                 $changes{'scantronformat'} = 1;
20099:             } else {
20100:                 $confhash{'scantron'}{'scantronformat'} = $domconfig{'scantron'}{'scantronformat'};
20101:             }
20102:         }
20103:     }
20104:     my @options = ('hdr','pad','rem');
20105:     my @fields = &scantroncsv_fields();
20106:     my %titles = &scantronconfig_titles();
20107:     my @formats = &Apache::loncommon::get_env_multiple('form.scantronconfig');
20108:     my ($newdat,$currdat,%newcol,%currcol);
20109:     if (grep(/^dat$/,@formats)) {
20110:         $confhash{'scantron'}{config}{dat} = 1;
20111:         $newdat = 1;
20112:     } else {
20113:         $newdat = 0;
20114:     }
20115:     if (grep(/^csv$/,@formats)) {
20116:         my %bynum;
20117:         foreach my $field (@fields) {
20118:             if ($env{'form.scantronconfig_csv_'.$field} =~ /^(\d+)$/) {
20119:                 my $posscol = $1;
20120:                 if (($posscol < 20) && (!$bynum{$posscol})) {
20121:                     $confhash{'scantron'}{config}{csv}{fields}{$field} = $posscol;
20122:                     $bynum{$posscol} = $field;
20123:                     $newcol{$field} = $posscol;
20124:                 }
20125:             }
20126:         }
20127:         if (keys(%newcol)) {
20128:             foreach my $option (@options) {
20129:                 if ($env{'form.scantroncsv_'.$option}) {
20130:                     $confhash{'scantron'}{config}{csv}{options}{$option} = 1;
20131:                 }
20132:             }
20133:         }
20134:     }
20135:     $currdat = 1;
20136:     if (ref($domconfig{'scantron'}) eq 'HASH') {
20137:         if (ref($domconfig{'scantron'}{'config'}) eq 'HASH') {
20138:             unless (exists($domconfig{'scantron'}{'config'}{'dat'})) {
20139:                 $currdat = 0;
20140:             }
20141:             if (ref($domconfig{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20142:                 if (ref($domconfig{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20143:                     %currcol = %{$domconfig{'scantron'}{'config'}{'csv'}{'fields'}};
20144:                 }
20145:             }
20146:         }
20147:     }
20148:     if ($currdat != $newdat) {
20149:         $changes{'config'} = 1;
20150:     } else {
20151:         foreach my $field (@fields) {
20152:             if ($currcol{$field} ne '') {
20153:                 if ($currcol{$field} ne $newcol{$field}) {
20154:                     $changes{'config'} = 1;
20155:                     last;
20156:                 }
20157:             } elsif ($newcol{$field} ne '') {
20158:                 $changes{'config'} = 1;
20159:                 last;
20160:             }
20161:         }
20162:     }
20163:     if (keys(%confhash) > 0) {
20164:         my $putresult = &Apache::lonnet::put_dom('configuration',\%confhash,
20165:                                                  $dom);
20166:         if ($putresult eq 'ok') {
20167:             if (keys(%changes) > 0) {
20168:                 if (ref($confhash{'scantron'}) eq 'HASH') {
20169:                     $resulttext = &mt('Changes made:').'<ul>';
20170:                     if ($changes{'scantronformat'}) {
20171:                         if ($confhash{'scantron'}{'scantronformat'} eq '') {
20172:                             $resulttext .= '<li>'.&mt('[_1] bubblesheet format file removed; [_2] file will be used for courses in this domain.',$custom,$default).'</li>';
20173:                         } else {
20174:                             $resulttext .= '<li>'.&mt('Custom bubblesheet format file ([_1]) uploaded for use with courses in this domain.',$custom).'</li>';
20175:                         }
20176:                     }
20177:                     if ($changes{'config'}) {
20178:                         if (ref($confhash{'scantron'}{'config'}) eq 'HASH') {
20179:                             if ($confhash{'scantron'}{'config'}{'dat'}) {
20180:                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .dat format').'</li>';
20181:                             }
20182:                             if (ref($confhash{'scantron'}{'config'}{'csv'}) eq 'HASH') {
20183:                                 if (ref($confhash{'scantron'}{'config'}{'csv'}{'fields'}) eq 'HASH') {
20184:                                     if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'fields'}})) {
20185:                                         $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following fields/column numbers supported:').'<ul>';
20186:                                         foreach my $field (@fields) {
20187:                                             if ($confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} ne '') {
20188:                                                 my $showcol = $confhash{'scantron'}{'config'}{'csv'}{'fields'}{$field} + 1;
20189:                                                 $resulttext .= '<li>'.$titles{$field}.': '.$showcol.'</li>';
20190:                                             }
20191:                                         }
20192:                                         $resulttext .= '</ul></li>';
20193:                                         if (ref($confhash{'scantron'}{'config'}{'csv'}{'options'}) eq 'HASH') {
20194:                                             if (keys(%{$confhash{'scantron'}{'config'}{'csv'}{'options'}})) {
20195:                                                 $resulttext .= '<li>'.&mt('Bubblesheet data upload formats includes .csv format, with following options:').'<ul>';
20196:                                                 foreach my $option (@options) {
20197:                                                     if ($confhash{'scantron'}{'config'}{'csv'}{'options'}{$option} ne '') {
20198:                                                         $resulttext .= '<li>'.$titles{$option}.'</li>';
20199:                                                     }
20200:                                                 }
20201:                                                 $resulttext .= '</ul></li>';
20202:                                             }
20203:                                         }
20204:                                     }
20205:                                 }
20206:                             }
20207:                         } else {
20208:                             $resulttext .= '<li>'.&mt('No bubblesheet data upload formats set -- will default to assuming .dat format').'</li>';
20209:                         }
20210:                     }
20211:                     $resulttext .= '</ul>';
20212:                 } else {
20213:                     $resulttext = &mt('Changes made to bubblesheet format file.');
20214:                 }
20215:                 &Apache::loncommon::devalidate_domconfig_cache($dom);
20216:                 if (ref($lastactref) eq 'HASH') {
20217:                     $lastactref->{'domainconfig'} = 1;
20218:                 }
20219:             } else {
20220:                 $resulttext = &mt('No changes made to bubblesheet format settings');
20221:             }
20222:         } else {
20223:             $resulttext = '<span class="LC_error">'.
20224:                 &mt('An error occurred: [_1]',$putresult).'</span>';
20225:         }
20226:     } else {
20227:         $resulttext = &mt('No changes made to bubblesheet format file'); 
20228:     }
20229:     if ($errors) {
20230:         $resulttext .= '<p>'.&mt('The following errors occurred: ').'<ul>'.
20231:                        $errors.'</ul></p>';
20232:     }
20233:     return $resulttext;
20234: }
20235: 
20236: sub modify_coursecategories {
20237:     my ($dom,$lastactref,%domconfig) = @_;
20238:     my ($resulttext,%deletions,%reorderings,%needreordering,%adds,%changes,$errors,
20239:         $cathash);
20240:     my @deletecategory = &Apache::loncommon::get_env_multiple('form.deletecategory');
20241:     my @catitems = ('unauth','auth');
20242:     my @cattypes = ('std','domonly','codesrch','none');
20243:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20244:         $cathash = $domconfig{'coursecategories'}{'cats'};
20245:         if ($domconfig{'coursecategories'}{'togglecats'} ne $env{'form.togglecats'}) {
20246:             $changes{'togglecats'} = 1;
20247:             $domconfig{'coursecategories'}{'togglecats'} = $env{'form.togglecats'};
20248:         }
20249:         if ($domconfig{'coursecategories'}{'categorize'} ne $env{'form.categorize'}) {
20250:             $changes{'categorize'} = 1;
20251:             $domconfig{'coursecategories'}{'categorize'} = $env{'form.categorize'};
20252:         }
20253:         if ($domconfig{'coursecategories'}{'togglecatscomm'} ne $env{'form.togglecatscomm'}) {
20254:             $changes{'togglecatscomm'} = 1;
20255:             $domconfig{'coursecategories'}{'togglecatscomm'} = $env{'form.togglecatscomm'};
20256:         }
20257:         if ($domconfig{'coursecategories'}{'categorizecomm'} ne $env{'form.categorizecomm'}) {
20258:             $changes{'categorizecomm'} = 1;
20259:             $domconfig{'coursecategories'}{'categorizecomm'} = $env{'form.categorizecomm'};
20260: 
20261:         }
20262:         if ($domconfig{'coursecategories'}{'togglecatsplace'} ne $env{'form.togglecatsplace'}) {
20263:             $changes{'togglecatsplace'} = 1;
20264:             $domconfig{'coursecategories'}{'togglecatsplace'} = $env{'form.togglecatsplace'};
20265:         }
20266:         if ($domconfig{'coursecategories'}{'categorizeplace'} ne $env{'form.categorizeplace'}) {
20267:             $changes{'categorizeplace'} = 1;
20268:             $domconfig{'coursecategories'}{'categorizeplace'} = $env{'form.categorizeplace'};
20269:         }
20270:         foreach my $item (@catitems) {
20271:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20272:                 if ($domconfig{'coursecategories'}{$item} ne $env{'form.coursecat_'.$item}) {
20273:                     $changes{$item} = 1;
20274:                     $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20275:                 }
20276:             }
20277:         }
20278:     } else {
20279:         $changes{'togglecats'} = 1;
20280:         $changes{'categorize'} = 1;
20281:         $changes{'togglecatscomm'} = 1;
20282:         $changes{'categorizecomm'} = 1;
20283:         $changes{'togglecatsplace'} = 1;
20284:         $changes{'categorizeplace'} = 1;
20285:         $domconfig{'coursecategories'} = {
20286:                                              togglecats => $env{'form.togglecats'},
20287:                                              categorize => $env{'form.categorize'},
20288:                                              togglecatscomm => $env{'form.togglecatscomm'},
20289:                                              categorizecomm => $env{'form.categorizecomm'},
20290:                                              togglecatsplace => $env{'form.togglecatsplace'},
20291:                                              categorizeplace => $env{'form.categorizeplace'},
20292:                                          };
20293:         foreach my $item (@catitems) {
20294:             if ($env{'form.coursecat_'.$item} ne 'std') {
20295:                 $changes{$item} = 1;
20296:             }
20297:             if (grep(/^\Q$env{'form.coursecat_'.$item}\E$/,@cattypes)) {
20298:                 $domconfig{'coursecategories'}{$item} = $env{'form.coursecat_'.$item};
20299:             }
20300:         }
20301:     }
20302:     if (ref($cathash) eq 'HASH') {
20303:         if (($domconfig{'coursecategories'}{'cats'}{'instcode::0'} ne '')  && ($env{'form.instcode'} == 0)) {
20304:             push (@deletecategory,'instcode::0');
20305:         }
20306:         if (($domconfig{'coursecategories'}{'cats'}{'communities::0'} ne '')  && ($env{'form.communities'} == 0)) {
20307:             push(@deletecategory,'communities::0');
20308:         }
20309:         if (($domconfig{'coursecategories'}{'cats'}{'placement::0'} ne '')  && ($env{'form.placement'} == 0)) {
20310:             push(@deletecategory,'placement::0');
20311:         }
20312:     }
20313:     my (@predelcats,@predeltrails,%predelallitems,%sort_by_deltrail);
20314:     if (ref($cathash) eq 'HASH') {
20315:         if (@deletecategory > 0) {
20316:             #FIXME Need to remove category from all courses using a deleted category 
20317:             &Apache::loncommon::extract_categories($cathash,\@predelcats,\@predeltrails,\%predelallitems);
20318:             foreach my $item (@deletecategory) {
20319:                 if ($domconfig{'coursecategories'}{'cats'}{$item} ne '') {
20320:                     delete($domconfig{'coursecategories'}{'cats'}{$item});
20321:                     $deletions{$item} = 1;
20322:                     &recurse_cat_deletes($item,$cathash,\%deletions);
20323:                 }
20324:             }
20325:         }
20326:         foreach my $item (keys(%{$cathash})) {
20327:             my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
20328:             if ($cathash->{$item} ne $env{'form.'.$item}) {
20329:                 $reorderings{$item} = 1;
20330:                 $domconfig{'coursecategories'}{'cats'}{$item} = $env{'form.'.$item};
20331:             }
20332:             if ($env{'form.addcategory_name_'.$item} ne '') {
20333:                 my $newcat = $env{'form.addcategory_name_'.$item};
20334:                 my $newdepth = $depth+1;
20335:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20336:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos_'.$item};
20337:                 $adds{$newitem} = 1; 
20338:             }
20339:             if ($env{'form.subcat_'.$item} ne '') {
20340:                 my $newcat = $env{'form.subcat_'.$item};
20341:                 my $newdepth = $depth+1;
20342:                 my $newitem = &escape($newcat).':'.&escape($cat).':'.$newdepth;
20343:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = 0;
20344:                 $adds{$newitem} = 1;
20345:             }
20346:         }
20347:     }
20348:     if ($env{'form.instcode'} eq '1') {
20349:         if (ref($cathash) eq 'HASH') {
20350:             my $newitem = 'instcode::0';
20351:             if ($cathash->{$newitem} eq '') {  
20352:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20353:                 $adds{$newitem} = 1;
20354:             }
20355:         } else {
20356:             my $newitem = 'instcode::0';
20357:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.instcode_pos'};
20358:             $adds{$newitem} = 1;
20359:         }
20360:     }
20361:     if ($env{'form.communities'} eq '1') {
20362:         if (ref($cathash) eq 'HASH') {
20363:             my $newitem = 'communities::0';
20364:             if ($cathash->{$newitem} eq '') {
20365:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20366:                 $adds{$newitem} = 1;
20367:             }
20368:         } else {
20369:             my $newitem = 'communities::0';
20370:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.communities_pos'};
20371:             $adds{$newitem} = 1;
20372:         }
20373:     }
20374:     if ($env{'form.placement'} eq '1') {
20375:         if (ref($cathash) eq 'HASH') {
20376:             my $newitem = 'placement::0';
20377:             if ($cathash->{$newitem} eq '') {
20378:                 $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20379:                 $adds{$newitem} = 1;
20380:             }
20381:         } else {
20382:             my $newitem = 'placement::0';
20383:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.placement_pos'};
20384:             $adds{$newitem} = 1;
20385:         }
20386:     }
20387:     if ($env{'form.addcategory_name'} ne '') {
20388:         if (($env{'form.addcategory_name'} ne 'instcode') &&
20389:             ($env{'form.addcategory_name'} ne 'communities') &&
20390:             ($env{'form.addcategory_name'} ne 'placement')) {
20391:             my $newitem = &escape($env{'form.addcategory_name'}).'::0';
20392:             $domconfig{'coursecategories'}{'cats'}{$newitem} = $env{'form.addcategory_pos'};
20393:             $adds{$newitem} = 1;
20394:         }
20395:     }
20396:     my $putresult;
20397:     if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20398:         if (keys(%deletions) > 0) {
20399:             foreach my $key (keys(%deletions)) {
20400:                 if ($predelallitems{$key} ne '') {
20401:                     $sort_by_deltrail{$predelallitems{$key}} = $predeltrails[$predelallitems{$key}];
20402:                 }
20403:             }
20404:         }
20405:         my (@chkcats,@chktrails,%chkallitems);
20406:         &Apache::loncommon::extract_categories($domconfig{'coursecategories'}{'cats'},\@chkcats,\@chktrails,\%chkallitems);
20407:         if (ref($chkcats[0]) eq 'ARRAY') {
20408:             my $depth = 0;
20409:             my $chg = 0;
20410:             for (my $i=0; $i<@{$chkcats[0]}; $i++) {
20411:                 my $name = $chkcats[0][$i];
20412:                 my $item;
20413:                 if ($name eq '') {
20414:                     $chg ++;
20415:                 } else {
20416:                     $item = &escape($name).'::0';
20417:                     if ($chg) {
20418:                         $domconfig{'coursecategories'}{'cats'}{$item} -= $chg;
20419:                     }
20420:                     $depth ++; 
20421:                     &recurse_check(\@chkcats,$domconfig{'coursecategories'}{'cats'},$depth,$name);
20422:                     $depth --;
20423:                 }
20424:             }
20425:         }
20426:     }
20427:     if ((keys(%changes) > 0) || (keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20428:         $putresult = &Apache::lonnet::put_dom('configuration',\%domconfig,$dom);
20429:         if ($putresult eq 'ok') {
20430:             my %title = (
20431:                          togglecats     => 'Show/Hide a course in catalog',
20432:                          categorize     => 'Assign a category to a course',
20433:                          togglecatscomm => 'Show/Hide a community in catalog',
20434:                          categorizecomm => 'Assign a category to a community',
20435:                         );
20436:             my %level = (
20437:                          dom  => 'set in Domain ("Modify Course/Community")',
20438:                          crs  => 'set in Course ("Course Configuration")',
20439:                          comm => 'set in Community ("Community Configuration")',
20440:                          none     => 'No catalog',
20441:                          std      => 'Standard catalog',
20442:                          domonly  => 'Domain-only catalog',
20443:                          codesrch => 'Code search form',
20444:                         );
20445:             $resulttext = &mt('Changes made:').'<ul>';
20446:             if ($changes{'togglecats'}) {
20447:                 $resulttext .= '<li>'.&mt("$title{'togglecats'} $level{$env{'form.togglecats'}}").'</li>'; 
20448:             }
20449:             if ($changes{'categorize'}) {
20450:                 $resulttext .= '<li>'.&mt("$title{'categorize'} $level{$env{'form.categorize'}}").'</li>';
20451:             }
20452:             if ($changes{'togglecatscomm'}) {
20453:                 $resulttext .= '<li>'.&mt("$title{'togglecatscomm'} $level{$env{'form.togglecatscomm'}}").'</li>';
20454:             }
20455:             if ($changes{'categorizecomm'}) {
20456:                 $resulttext .= '<li>'.&mt("$title{'categorizecomm'} $level{$env{'form.categorizecomm'}}").'</li>';
20457:             }
20458:             if ($changes{'unauth'}) {
20459:                 $resulttext .= '<li>'.&mt('Catalog type for unauthenticated users set to "'.$level{$env{'form.coursecat_unauth'}}.'"').'</li>';
20460:             }
20461:             if ($changes{'auth'}) {
20462:                 $resulttext .= '<li>'.&mt('Catalog type for authenticated users set to "'.$level{$env{'form.coursecat_auth'}}.'"').'</li>';
20463:             }
20464:             if ((keys(%deletions) > 0) || (keys(%reorderings) > 0) || (keys(%adds) > 0)) {
20465:                 my $cathash;
20466:                 if (ref($domconfig{'coursecategories'}) eq 'HASH') {
20467:                     $cathash = $domconfig{'coursecategories'}{'cats'};
20468:                 } else {
20469:                     $cathash = {};
20470:                 } 
20471:                 my (@cats,@trails,%allitems);
20472:                     &Apache::loncommon::extract_categories($cathash,\@cats,\@trails,\%allitems);
20473:                 if (keys(%deletions) > 0) {
20474:                     $resulttext .= '<li>'.&mt('Deleted categories:').'<ul>';
20475:                     foreach my $predeltrail (sort {$a <=> $b } (keys(%sort_by_deltrail))) { 
20476:                         $resulttext .= '<li>'.$predeltrails[$predeltrail].'</li>';
20477:                     }
20478:                     $resulttext .= '</ul></li>';
20479:                 }
20480:                 if (keys(%reorderings) > 0) {
20481:                     my %sort_by_trail;
20482:                     $resulttext .= '<li>'.&mt('Reordered categories:').'<ul>';
20483:                     foreach my $key (keys(%reorderings)) {
20484:                         if ($allitems{$key} ne '') {
20485:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20486:                         }
20487:                     }
20488:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20489:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20490:                     }
20491:                     $resulttext .= '</ul></li>';
20492:                 }
20493:                 if (keys(%adds) > 0) {
20494:                     my %sort_by_trail;
20495:                     $resulttext .= '<li>'.&mt('Added categories:').'<ul>';
20496:                     foreach my $key (keys(%adds)) {
20497:                         if ($allitems{$key} ne '') {
20498:                             $sort_by_trail{$allitems{$key}} = $trails[$allitems{$key}];
20499:                         }
20500:                     }
20501:                     foreach my $trail (sort {$a <=> $b } (keys(%sort_by_trail))) {
20502:                         $resulttext .= '<li>'.$trails[$trail].'</li>';
20503:                     }
20504:                     $resulttext .= '</ul></li>';
20505:                 }
20506:                 &Apache::lonnet::do_cache_new('cats',$dom,$cathash,3600);
20507:                 if (ref($lastactref) eq 'HASH') {
20508:                     $lastactref->{'cats'} = 1;
20509:                 }
20510:             }
20511:             $resulttext .= '</ul>';
20512:             if ($changes{'unauth'} || $changes{'auth'}) {
20513:                 my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
20514:                 if ($changes{'auth'}) {
20515:                     $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
20516:                 }
20517:                 if ($changes{'unauth'}) {
20518:                     $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
20519:                 }
20520:                 my $cachetime = 24*60*60;
20521:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20522:                 if (ref($lastactref) eq 'HASH') {
20523:                     $lastactref->{'domdefaults'} = 1;
20524:                 }
20525:             }
20526:         } else {
20527:             $resulttext = '<span class="LC_error">'.
20528:                           &mt('An error occurred: [_1]',$putresult).'</span>';
20529:         }
20530:     } else {
20531:         $resulttext = &mt('No changes made to course and community categories');
20532:     }
20533:     return $resulttext;
20534: }
20535: 
20536: sub modify_serverstatuses {
20537:     my ($dom,%domconfig) = @_;
20538:     my ($resulttext,%changes,%currserverstatus,%newserverstatus);
20539:     if (ref($domconfig{'serverstatuses'}) eq 'HASH') {
20540:         %currserverstatus = %{$domconfig{'serverstatuses'}};
20541:     }
20542:     my @pages = &serverstatus_pages();
20543:     foreach my $type (@pages) {
20544:         $newserverstatus{$type}{'namedusers'} = '';
20545:         $newserverstatus{$type}{'machines'} = '';
20546:         if (defined($env{'form.'.$type.'_namedusers'})) {
20547:             my @users = split(/,/,$env{'form.'.$type.'_namedusers'});
20548:             my @okusers;
20549:             foreach my $user (@users) {
20550:                 my ($uname,$udom) = split(/:/,$user);
20551:                 if (($udom =~ /^$match_domain$/) &&   
20552:                     (&Apache::lonnet::domain($udom)) &&
20553:                     ($uname =~ /^$match_username$/)) {
20554:                     if (!grep(/^\Q$user\E/,@okusers)) {
20555:                         push(@okusers,$user);
20556:                     }
20557:                 }
20558:             }
20559:             if (@okusers > 0) {
20560:                  @okusers = sort(@okusers);
20561:                  $newserverstatus{$type}{'namedusers'} = join(',',@okusers);
20562:             }
20563:         }
20564:         if (defined($env{'form.'.$type.'_machines'})) {
20565:             my @machines = split(/,/,$env{'form.'.$type.'_machines'});
20566:             my @okmachines;
20567:             foreach my $ip (@machines) {
20568:                 my @parts = split(/\./,$ip);
20569:                 next if (@parts < 4);
20570:                 my $badip = 0;
20571:                 for (my $i=0; $i<4; $i++) {
20572:                     if (!(($parts[$i] >= 0) && ($parts[$i] <= 255))) {
20573:                         $badip = 1;
20574:                         last;
20575:                     }
20576:                 }
20577:                 if (!$badip) {
20578:                     push(@okmachines,$ip);     
20579:                 }
20580:             }
20581:             @okmachines = sort(@okmachines);
20582:             $newserverstatus{$type}{'machines'} = join(',',@okmachines);
20583:         }
20584:     }
20585:     my %serverstatushash =  (
20586:                                 serverstatuses => \%newserverstatus,
20587:                             );
20588:     foreach my $type (@pages) {
20589:         foreach my $setting ('namedusers','machines') {
20590:             my (@current,@new);
20591:             if (ref($currserverstatus{$type}) eq 'HASH') {
20592:                 if ($currserverstatus{$type}{$setting} ne '') { 
20593:                     @current = split(/,/,$currserverstatus{$type}{$setting});
20594:                 }
20595:             }
20596:             if ($newserverstatus{$type}{$setting} ne '') {
20597:                 @new = split(/,/,$newserverstatus{$type}{$setting});
20598:             }
20599:             if (@current > 0) {
20600:                 if (@new > 0) {
20601:                     foreach my $item (@current) {
20602:                         if (!grep(/^\Q$item\E$/,@new)) {
20603:                             $changes{$type}{$setting} = 1;
20604:                             last;
20605:                         }
20606:                     }
20607:                     foreach my $item (@new) {
20608:                         if (!grep(/^\Q$item\E$/,@current)) {
20609:                             $changes{$type}{$setting} = 1;
20610:                             last;
20611:                         }
20612:                     }
20613:                 } else {
20614:                     $changes{$type}{$setting} = 1;
20615:                 }
20616:             } elsif (@new > 0) {
20617:                 $changes{$type}{$setting} = 1;
20618:             }
20619:         }
20620:     }
20621:     if (keys(%changes) > 0) {
20622:         my $titles= &LONCAPA::lonauthcgi::serverstatus_titles();
20623:         my $putresult = &Apache::lonnet::put_dom('configuration',
20624:                                                  \%serverstatushash,$dom);
20625:         if ($putresult eq 'ok') {
20626:             $resulttext .= &mt('Changes made:').'<ul>';
20627:             foreach my $type (@pages) {
20628:                 if (ref($changes{$type}) eq 'HASH') {
20629:                     $resulttext .= '<li>'.$titles->{$type}.'<ul>';
20630:                     if ($changes{$type}{'namedusers'}) {
20631:                         if ($newserverstatus{$type}{'namedusers'} eq '') {
20632:                             $resulttext .= '<li>'.&mt("Access terminated for all specific (named) users").'</li>'."\n";
20633:                         } else {
20634:                             $resulttext .= '<li>'.&mt("Access available for the following specified users: ").$newserverstatus{$type}{'namedusers'}.'</li>'."\n";
20635:                         }
20636:                     }
20637:                     if ($changes{$type}{'machines'}) {
20638:                         if ($newserverstatus{$type}{'machines'} eq '') {
20639:                             $resulttext .= '<li>'.&mt("Access terminated for all specific IP addresses").'</li>'."\n";
20640:                         } else {
20641:                             $resulttext .= '<li>'.&mt("Access available for the following specified IP addresses: ").$newserverstatus{$type}{'machines'}.'</li>'."\n";
20642:                         }
20643: 
20644:                     }
20645:                     $resulttext .= '</ul></li>';
20646:                 }
20647:             }
20648:             $resulttext .= '</ul>';
20649:         } else {
20650:             $resulttext = '<span class="LC_error">'.
20651:                           &mt('An error occurred saving access settings for server status pages: [_1].',$putresult).'</span>';
20652: 
20653:         }
20654:     } else {
20655:         $resulttext = &mt('No changes made to access to server status pages');
20656:     }
20657:     return $resulttext;
20658: }
20659: 
20660: sub modify_helpsettings {
20661:     my ($r,$dom,$confname,$lastactref,%domconfig) = @_;
20662:     my ($resulttext,$errors,%changes,%helphash);
20663:     my %defaultchecked = ('submitbugs' => 'on');
20664:     my @offon = ('off','on');
20665:     my @toggles = ('submitbugs');
20666:     my %current = ('submitbugs' => '',
20667:                    'adhoc'      => {},
20668:                   );
20669:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
20670:         %current = %{$domconfig{'helpsettings'}};
20671:     }
20672:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
20673:     foreach my $item (@toggles) {
20674:         if ($defaultchecked{$item} eq 'on') { 
20675:             if ($current{$item} eq '') {
20676:                 if ($env{'form.'.$item} eq '0') {
20677:                     $changes{$item} = 1;
20678:                 }
20679:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20680:                 $changes{$item} = 1;
20681:             }
20682:         } elsif ($defaultchecked{$item} eq 'off') {
20683:             if ($current{$item} eq '') {
20684:                 if ($env{'form.'.$item} eq '1') {
20685:                     $changes{$item} = 1;
20686:                 }
20687:             } elsif ($current{$item} ne $env{'form.'.$item}) {
20688:                 $changes{$item} = 1;
20689:             }
20690:         }
20691:         if (($env{'form.'.$item} eq '0') || ($env{'form.'.$item} eq '1')) {
20692:             $helphash{'helpsettings'}{$item} = $env{'form.'.$item};
20693:         }
20694:     }
20695:     my $maxnum = $env{'form.helproles_maxnum'};
20696:     my $confname = $dom.'-domainconfig';
20697:     my %existing=&Apache::lonnet::dump('roles',$dom,$confname,'rolesdef_');
20698:     my (@allpos,%newsettings,%changedprivs,$newrole);
20699:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($dom);
20700:     my @accesstypes = ('all','dh','da','none','status','inc','exc');
20701:     my %domhelpdesk = &Apache::lonnet::get_active_domroles($dom,['dh','da']);
20702:     my %lt = &Apache::lonlocal::texthash(
20703:                     s      => 'system',
20704:                     d      => 'domain',
20705:                     order  => 'Display order',
20706:                     access => 'Role usage',
20707:                     all    => 'All with domain helpdesk or helpdesk assistant role',
20708:                     dh     => 'All with domain helpdesk role',
20709:                     da     => 'All with domain helpdesk assistant role',
20710:                     none   => 'None',
20711:                     status => 'Determined based on institutional status',
20712:                     inc    => 'Include all, but exclude specific personnel',
20713:                     exc    => 'Exclude all, but include specific personnel',
20714:     );
20715:     for (my $num=0; $num<=$maxnum; $num++) {
20716:         my ($prefix,$identifier,$rolename,%curr);
20717:         if ($num == $maxnum) {
20718:             next unless ($env{'form.newcusthelp'} == $maxnum);
20719:             $identifier = 'custhelp'.$num;
20720:             $prefix = 'helproles_'.$num;
20721:             $rolename = $env{'form.custhelpname'.$num};
20722:             $rolename=~s/[^A-Za-z0-9]//gs;
20723:             next if ($rolename eq '');
20724:             next if (exists($existing{'rolesdef_'.$rolename}));
20725:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20726:             my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20727:                                                      $newprivs{'c'},$confname,$dom);
20728:             if ($result ne 'ok') {
20729:                 $errors .= '<li><span class="LC_error">'.
20730:                            &mt('An error occurred storing the new custom role: [_1]',
20731:                            $result).'</span></li>';
20732:                 next;
20733:             } else {
20734:                 $changedprivs{$rolename} = \%newprivs;
20735:                 $newrole = $rolename;
20736:             }
20737:         } else {
20738:             $prefix = 'helproles_'.$num;
20739:             $rolename = $env{'form.'.$prefix};
20740:             next if ($rolename eq '');
20741:             next unless (exists($existing{'rolesdef_'.$rolename}));
20742:             $identifier = 'custhelp'.$num;
20743:             my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$identifier);
20744:             my %currprivs;
20745:             ($currprivs{'s'},$currprivs{'d'},$currprivs{'c'}) =
20746:                 split(/\_/,$existing{'rolesdef_'.$rolename});
20747:             foreach my $level ('c','d','s') {
20748:                 if ($newprivs{$level} ne $currprivs{$level}) {
20749:                     my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
20750:                                                              $newprivs{'c'},$confname,$dom);
20751:                     if ($result ne 'ok') {
20752:                         $errors .= '<li><span class="LC_error">'.
20753:                                    &mt('An error occurred storing privileges for existing role [_1]: [_2]',
20754:                                        $rolename,$result).'</span></li>';
20755:                     } else {
20756:                         $changedprivs{$rolename} = \%newprivs;
20757:                     }
20758:                     last;
20759:                 }
20760:             }
20761:             if (ref($current{'adhoc'}) eq 'HASH') {
20762:                 if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20763:                     %curr = %{$current{'adhoc'}{$rolename}};
20764:                 }
20765:             }
20766:         }
20767:         my $newpos = $env{'form.'.$prefix.'_pos'};
20768:         $newpos =~ s/\D+//g;
20769:         $allpos[$newpos] = $rolename;
20770:         my $newdesc = $env{'form.'.$prefix.'_desc'};
20771:         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'desc'} = $newdesc;
20772:         if ($curr{'desc'}) {
20773:             if ($curr{'desc'} ne $newdesc) {
20774:                 $changes{'customrole'}{$rolename}{'desc'} = 1;
20775:                 $newsettings{$rolename}{'desc'} = $newdesc;
20776:             }
20777:         } elsif ($newdesc ne '') {
20778:             $changes{'customrole'}{$rolename}{'desc'} = 1;
20779:             $newsettings{$rolename}{'desc'} = $newdesc;
20780:         }
20781:         my $access = $env{'form.'.$prefix.'_access'};
20782:         if (grep(/^\Q$access\E$/,@accesstypes)) {
20783:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = $access;
20784:             if ($access eq 'status') {
20785:                 my @statuses = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_status');
20786:                 if (scalar(@statuses) == 0) {
20787:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'none';
20788:                 } else {
20789:                     my (@shownstatus,$numtypes);
20790:                     $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20791:                     if (ref($types) eq 'ARRAY') {
20792:                         $numtypes = scalar(@{$types});
20793:                         foreach my $type (sort(@statuses)) {
20794:                             if ($type eq 'default') {
20795:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20796:                             } elsif (grep(/^\Q$type\E$/,@{$types})) {
20797:                                 push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$type);
20798:                                 push(@shownstatus,$usertypes->{$type});
20799:                             }
20800:                         }
20801:                     }
20802:                     if (grep(/^default$/,@statuses)) {
20803:                         push(@shownstatus,$othertitle);
20804:                     }
20805:                     if (scalar(@shownstatus) == 1+$numtypes) {
20806:                         $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'} = 'all';
20807:                         delete($helphash{'helpsettings'}{'adhoc'}{$rolename}{'status'});
20808:                     } else {
20809:                         $newsettings{$rolename}{'status'} = join(' '.&mt('or').' ',@shownstatus);
20810:                         if (ref($curr{'status'}) eq 'ARRAY') {
20811:                             my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20812:                             if (@diffs) {
20813:                                 $changes{'customrole'}{$rolename}{$access} = 1;
20814:                             }
20815:                         } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20816:                             $changes{'customrole'}{$rolename}{$access} = 1;
20817:                         }
20818:                     }
20819:                 }
20820:             } elsif (($access eq 'inc') || ($access eq 'exc')) {
20821:                 my @personnel = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_staff_'.$access);
20822:                 my @newspecstaff;
20823:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{$access} = [];
20824:                 foreach my $person (sort(@personnel)) {
20825:                     if ($domhelpdesk{$person}) {
20826:                         push(@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}},$person);
20827:                     }
20828:                 }
20829:                 if (ref($curr{$access}) eq 'ARRAY') {
20830:                     my @diffs = &Apache::loncommon::compare_arrays($helphash{'helpsettings'}{'adhoc'}{$rolename}{$access},$curr{$access});
20831:                     if (@diffs) {
20832:                         $changes{'customrole'}{$rolename}{$access} = 1;
20833:                     }
20834:                 } elsif (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20835:                     $changes{'customrole'}{$rolename}{$access} = 1;
20836:                 }
20837:                 foreach my $person (@{$helphash{'helpsettings'}{'adhoc'}{$rolename}{$access}}) {
20838:                     my ($uname,$udom) = split(/:/,$person);
20839:                         push(@newspecstaff,&Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom,'lastname'),$uname,$udom));
20840:                 }
20841:                 $newsettings{$rolename}{$access} = join(', ',sort(@newspecstaff));
20842:             }
20843:         } else {
20844:             $helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}= 'all';
20845:         }
20846:         unless ($curr{'access'} eq $access) {
20847:             $changes{'customrole'}{$rolename}{'access'} = 1;
20848:             $newsettings{$rolename}{'access'} = $lt{$helphash{'helpsettings'}{'adhoc'}{$rolename}{'access'}};
20849:         }
20850:     }
20851:     if (@allpos > 0) {
20852:         my $idx = 0;
20853:         foreach my $rolename (@allpos) {
20854:             if ($rolename ne '') {
20855:                 $helphash{'helpsettings'}{'adhoc'}{$rolename}{'order'} = $idx;
20856:                 if (ref($current{'adhoc'}) eq 'HASH') {
20857:                     if (ref($current{'adhoc'}{$rolename}) eq 'HASH') {
20858:                         if ($current{'adhoc'}{$rolename}{'order'} ne $idx) {
20859:                             $changes{'customrole'}{$rolename}{'order'} = 1;
20860:                             $newsettings{$rolename}{'order'} = $idx+1;
20861:                         }
20862:                     }
20863:                 }
20864:                 $idx ++;
20865:             }
20866:         }
20867:     }
20868:     my $putresult;
20869:     if (keys(%changes) > 0) {
20870:         $putresult = &Apache::lonnet::put_dom('configuration',\%helphash,$dom);
20871:         if ($putresult eq 'ok') {
20872:             if (ref($helphash{'helpsettings'}) eq 'HASH') {
20873:                 $domdefaults{'submitbugs'} = $helphash{'helpsettings'}{'submitbugs'};
20874:                 if (ref($helphash{'helpsettings'}{'adhoc'}) eq 'HASH') {
20875:                     $domdefaults{'adhocroles'} = $helphash{'helpsettings'}{'adhoc'};
20876:                 }
20877:             }
20878:             my $cachetime = 24*60*60;
20879:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
20880:             if (ref($lastactref) eq 'HASH') {
20881:                 $lastactref->{'domdefaults'} = 1;
20882:             }
20883:         } else {
20884:             $errors .= '<li><span class="LC_error">'.
20885:                        &mt('An error occurred storing the settings: [_1]',
20886:                            $putresult).'</span></li>';
20887:         }
20888:     }
20889:     if ((keys(%changes) && ($putresult eq 'ok')) || (keys(%changedprivs))) {
20890:         $resulttext = &mt('Changes made:').'<ul>';
20891:         my (%shownprivs,@levelorder);
20892:         @levelorder = ('c','d','s');
20893:         if ((keys(%changes)) && ($putresult eq 'ok')) {
20894:             foreach my $item (sort(keys(%changes))) {
20895:                 if ($item eq 'submitbugs') {
20896:                     $resulttext .= '<li>'.&mt('Display link to: [_1] set to "'.$offon[$env{'form.'.$item}].'".',
20897:                                               &Apache::loncommon::modal_link('http://bugs.loncapa.org',
20898:                                               &mt('LON-CAPA bug tracker'),600,500)).'</li>';
20899:                 } elsif ($item eq 'customrole') {
20900:                     if (ref($changes{'customrole'}) eq 'HASH') {
20901:                         my @keyorder = ('order','desc','access','status','exc','inc');
20902:                         my %keytext = &Apache::lonlocal::texthash(
20903:                                                                    order  => 'Order',
20904:                                                                    desc   => 'Role description',
20905:                                                                    access => 'Role usage',
20906:                                                                    status => 'Allowed institutional types',
20907:                                                                    exc    => 'Allowed personnel',
20908:                                                                    inc    => 'Disallowed personnel',
20909:                         );
20910:                         foreach my $role (sort(keys(%{$changes{'customrole'}}))) {
20911:                             if (ref($changes{'customrole'}{$role}) eq 'HASH') {
20912:                                 if ($role eq $newrole) {
20913:                                     $resulttext .= '<li>'.&mt('New custom role added: [_1]',
20914:                                                               $role).'<ul>';
20915:                                 } else {
20916:                                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
20917:                                                               $role).'<ul>';
20918:                                 }
20919:                                 foreach my $key (@keyorder) {
20920:                                     if ($changes{'customrole'}{$role}{$key}) {
20921:                                         $resulttext .= '<li>'.&mt("[_1] set to: [_2]",
20922:                                                                   $keytext{$key},$newsettings{$role}{$key}).
20923:                                                        '</li>';
20924:                                     }
20925:                                 }
20926:                                 if (ref($changedprivs{$role}) eq 'HASH') {
20927:                                     $shownprivs{$role} = 1;
20928:                                     $resulttext .= '<li>'.&mt('Privileges set to :').'<ul>';
20929:                                     foreach my $level (@levelorder) {
20930:                                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
20931:                                             next if ($item eq '');
20932:                                             my ($priv) = split(/\&/,$item,2);
20933:                                             if (&Apache::lonnet::plaintext($priv)) {
20934:                                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
20935:                                                 unless ($level eq 'c') {
20936:                                                     $resulttext .= ' ('.$lt{$level}.')';
20937:                                                 }
20938:                                                 $resulttext .= '</li>';
20939:                                             }
20940:                                         }
20941:                                     }
20942:                                     $resulttext .= '</ul>';
20943:                                 }
20944:                                 $resulttext .= '</ul></li>';
20945:                             }
20946:                         }
20947:                     }
20948:                 }
20949:             }
20950:         }
20951:         if (keys(%changedprivs)) {
20952:             foreach my $role (sort(keys(%changedprivs))) {
20953:                 unless ($shownprivs{$role}) {
20954:                     $resulttext .= '<li>'.&mt('Existing custom role modified: [_1]',
20955:                                               $role).'<ul>'.
20956:                                    '<li>'.&mt('Privileges set to :').'<ul>';
20957:                     foreach my $level (@levelorder) {
20958:                         foreach my $item (split(/\:/,$changedprivs{$role}{$level})) {
20959:                             next if ($item eq '');
20960:                             my ($priv) = split(/\&/,$item,2);
20961:                             if (&Apache::lonnet::plaintext($priv)) {
20962:                                 $resulttext .= '<li>'.&Apache::lonnet::plaintext($priv);
20963:                                 unless ($level eq 'c') {
20964:                                     $resulttext .= ' ('.$lt{$level}.')';
20965:                                 }
20966:                                 $resulttext .= '</li>';
20967:                             }
20968:                         }
20969:                     }
20970:                     $resulttext .= '</ul></li></ul></li>';
20971:                 }
20972:             }
20973:         }
20974:         $resulttext .= '</ul>';
20975:     } else {
20976:         $resulttext = &mt('No changes made to help settings');
20977:     }
20978:     if ($errors) {
20979:         $resulttext .= '<br />'.&mt('The following errors occurred: ').'<ul>'.
20980:                                     $errors.'</ul>';
20981:     }
20982:     return $resulttext;
20983: }
20984: 
20985: sub modify_coursedefaults {
20986:     my ($dom,$lastactref,%domconfig) = @_;
20987:     my ($resulttext,$errors,%changes,%defaultshash);
20988:     my %defaultchecked = (
20989:                            'canuse_pdfforms' => 'off',
20990:                            'uselcmath'       => 'on',
20991:                            'usejsme'         => 'on',
20992:                            'inline_chem'     => 'on',
20993:                            'ltiauth'         => 'off',
20994:                          );
20995:     my @toggles = ('canuse_pdfforms','uselcmath','usejsme','inline_chem','ltiauth');
20996:     my @numbers = ('anonsurvey_threshold','uploadquota_official','uploadquota_unofficial',
20997:                    'uploadquota_community','uploadquota_textbook','uploadquota_placement',
20998:                    'mysqltables_official','mysqltables_unofficial','mysqltables_community',
20999:                    'mysqltables_textbook','mysqltables_placement');
21000:     my @types = ('official','unofficial','community','textbook','placement');
21001:     my %staticdefaults = (
21002:                            anonsurvey_threshold => 10,
21003:                            uploadquota          => 500,
21004:                            postsubmit           => 60,
21005:                            mysqltables          => 172800,
21006:                          );
21007:     my %texoptions = (
21008:                         MathJax  => 'MathJax',
21009:                         mimetex  => &mt('Convert to Images'),
21010:                         tth      => &mt('TeX to HTML'),
21011:                      );
21012:     $defaultshash{'coursedefaults'} = {};
21013: 
21014:     if (ref($domconfig{'coursedefaults'}) ne 'HASH') {
21015:         if ($domconfig{'coursedefaults'} eq '') {
21016:             $domconfig{'coursedefaults'} = {};
21017:         }
21018:     }
21019: 
21020:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
21021:         foreach my $item (@toggles) {
21022:             if ($defaultchecked{$item} eq 'on') {
21023:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21024:                     ($env{'form.'.$item} eq '0')) {
21025:                     $changes{$item} = 1;
21026:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21027:                     $changes{$item} = 1;
21028:                 }
21029:             } elsif ($defaultchecked{$item} eq 'off') {
21030:                 if (($domconfig{'coursedefaults'}{$item} eq '') &&
21031:                     ($env{'form.'.$item} eq '1')) {
21032:                     $changes{$item} = 1;
21033:                 } elsif ($domconfig{'coursedefaults'}{$item} ne $env{'form.'.$item}) {
21034:                     $changes{$item} = 1;
21035:                 }
21036:             }
21037:             $defaultshash{'coursedefaults'}{$item} = $env{'form.'.$item};
21038:         }
21039:         foreach my $item (@numbers) {
21040:             my ($currdef,$newdef);
21041:             $newdef = $env{'form.'.$item};
21042:             if ($item eq 'anonsurvey_threshold') {
21043:                 $currdef = $domconfig{'coursedefaults'}{$item};
21044:                 $newdef =~ s/\D//g;
21045:                 if ($newdef eq '' || $newdef < 1) {
21046:                     $newdef = 1;
21047:                 }
21048:                 $defaultshash{'coursedefaults'}{$item} = $newdef;
21049:             } else {
21050:                 my ($setting,$type) = ($item =~ /^(uploadquota|mysqltables)_(\w+)$/);
21051:                 if (ref($domconfig{'coursedefaults'}{$setting}) eq 'HASH') {
21052:                     $currdef = $domconfig{'coursedefaults'}{$setting}{$type};
21053:                 }
21054:                 $newdef =~ s/[^\w.\-]//g;
21055:                 $defaultshash{'coursedefaults'}{$setting}{$type} = $newdef;
21056:             }
21057:             if ($currdef ne $newdef) {
21058:                 if ($item eq 'anonsurvey_threshold') {
21059:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$item})) {
21060:                         $changes{$item} = 1;
21061:                     }
21062:                 } elsif ($item =~ /^(uploadquota|mysqltables)_/) {
21063:                     my $setting = $1;
21064:                     unless (($currdef eq '') && ($newdef == $staticdefaults{$setting})) {
21065:                         $changes{$setting} = 1;
21066:                     }
21067:                 }
21068:             }
21069:         }
21070:         my $texengine;
21071:         if ($env{'form.texengine'} =~ /^(MathJax|mimetex|tth)$/) {
21072:             $texengine = $env{'form.texengine'};
21073:             my $currdef = $domconfig{'coursedefaults'}{'texengine'};
21074:             if ($currdef eq '') {
21075:                 unless ($texengine eq $Apache::lonnet::deftex) {
21076:                     $changes{'texengine'} = 1;
21077:                 }
21078:             } elsif ($currdef ne $texengine) {
21079:                 $changes{'texengine'} = 1;
21080:             }
21081:         }
21082:         if ($texengine ne '') {
21083:             $defaultshash{'coursedefaults'}{'texengine'} = $texengine;
21084:         }
21085:         my $currclone = $domconfig{'coursedefaults'}{'canclone'};
21086:         my @currclonecode;
21087:         if (ref($currclone) eq 'HASH') {
21088:             if (ref($currclone->{'instcode'}) eq 'ARRAY') {
21089:                 @currclonecode = @{$currclone->{'instcode'}};
21090:             }
21091:         }
21092:         my $newclone;
21093:         if ($env{'form.canclone'} =~ /^(none|domain|instcode)$/) {
21094:             $newclone = $env{'form.canclone'};
21095:         }
21096:         if ($newclone eq 'instcode') {
21097:             my @newcodes = &Apache::loncommon::get_env_multiple('form.clonecode');
21098:             my (%codedefaults,@code_order,@clonecode);
21099:             &Apache::lonnet::auto_instcode_defaults($dom,\%codedefaults,
21100:                                                     \@code_order);
21101:             foreach my $item (@code_order) {
21102:                 if (grep(/^\Q$item\E$/,@newcodes)) {
21103:                     push(@clonecode,$item);
21104:                 }
21105:             }
21106:             if (@clonecode) {
21107:                 $defaultshash{'coursedefaults'}{'canclone'} = { $newclone => \@clonecode };
21108:                 my @diffs = &Apache::loncommon::compare_arrays(\@currclonecode,\@clonecode);
21109:                 if (@diffs) {
21110:                     $changes{'canclone'} = 1;
21111:                 }
21112:             } else {
21113:                 $newclone eq '';
21114:             }
21115:         } elsif ($newclone ne '') {
21116:             $defaultshash{'coursedefaults'}{'canclone'} = $newclone;
21117:         }
21118:         if ($newclone ne $currclone) {
21119:             $changes{'canclone'} = 1;
21120:         }
21121:         my %credits;
21122:         foreach my $type (@types) {
21123:             unless ($type eq 'community') {
21124:                 $credits{$type} = $env{'form.'.$type.'_credits'};
21125:                 $credits{$type} =~ s/[^\d.]+//g;
21126:             }
21127:         }
21128:         if ((ref($domconfig{'coursedefaults'}{'coursecredits'}) ne 'HASH') &&
21129:             ($env{'form.coursecredits'} eq '1')) {
21130:             $changes{'coursecredits'} = 1;
21131:             foreach my $type (keys(%credits)) {
21132:                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21133:             }
21134:         } else {
21135:             if ($env{'form.coursecredits'} eq '1') {
21136:                 foreach my $type (@types) {
21137:                     unless ($type eq 'community') {
21138:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type} ne $credits{$type}) {
21139:                             $changes{'coursecredits'} = 1;
21140:                         }
21141:                         $defaultshash{'coursedefaults'}{'coursecredits'}{$type} = $credits{$type};
21142:                     }
21143:                 }
21144:             } elsif (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21145:                 foreach my $type (@types) {
21146:                     unless ($type eq 'community') {
21147:                         if ($domconfig{'coursedefaults'}{'coursecredits'}{$type}) {
21148:                             $changes{'coursecredits'} = 1;
21149:                             last;
21150:                         }
21151:                     }
21152:                 }
21153:             }
21154:         }
21155:         if ($env{'form.postsubmit'} eq '1') {
21156:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'on';
21157:             my %currtimeout;
21158:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21159:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'off') {
21160:                     $changes{'postsubmit'} = 1;
21161:                 }
21162:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21163:                     %currtimeout = %{$domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}};
21164:                 }
21165:             } else {
21166:                 $changes{'postsubmit'} = 1;
21167:             }
21168:             foreach my $type (@types) {
21169:                 my $timeout = $env{'form.'.$type.'_timeout'};
21170:                 $timeout =~ s/\D//g;
21171:                 if ($timeout == $staticdefaults{'postsubmit'}) {
21172:                     $timeout = '';
21173:                 } elsif (($timeout eq '') || ($timeout =~ /^0+$/)) {
21174:                     $timeout = '0';
21175:                 }
21176:                 unless ($timeout eq '') {
21177:                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type} = $timeout;
21178:                 }
21179:                 if (exists($currtimeout{$type})) {
21180:                     if ($timeout ne $currtimeout{$type}) {
21181:                         $changes{'postsubmit'} = 1;
21182:                     }
21183:                 } elsif ($timeout ne '') {
21184:                     $changes{'postsubmit'} = 1;
21185:                 }
21186:             }
21187:         } else {
21188:             $defaultshash{'coursedefaults'}{'postsubmit'}{'client'} = 'off';
21189:             if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21190:                 if ($domconfig{'coursedefaults'}{'postsubmit'}{'client'} eq 'on') {
21191:                     $changes{'postsubmit'} = 1;
21192:                 }
21193:             } else {
21194:                 $changes{'postsubmit'} = 1;
21195:             }
21196:         }
21197:     }
21198:     my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21199:                                              $dom);
21200:     if ($putresult eq 'ok') {
21201:         if (keys(%changes) > 0) {
21202:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21203:             if (($changes{'canuse_pdfforms'}) || ($changes{'uploadquota'}) || ($changes{'postsubmit'}) ||
21204:                 ($changes{'coursecredits'}) || ($changes{'uselcmath'}) || ($changes{'usejsme'}) ||
21205:                 ($changes{'canclone'}) || ($changes{'mysqltables'}) || ($changes{'texengine'}) ||
21206:                 ($changes{'inline_chem'}) || ($changes{'ltiauth'})) {
21207:                 foreach my $item ('canuse_pdfforms','uselcmath','usejsme','inline_chem','texengine','ltiauth') {
21208:                     if ($changes{$item}) {
21209:                         $domdefaults{$item}=$defaultshash{'coursedefaults'}{$item};
21210:                     }
21211:                 }
21212:                 if ($changes{'coursecredits'}) {
21213:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21214:                         foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'coursecredits'}})) {
21215:                             $domdefaults{$type.'credits'} =
21216:                                 $defaultshash{'coursedefaults'}{'coursecredits'}{$type};
21217:                         }
21218:                     }
21219:                 }
21220:                 if ($changes{'postsubmit'}) {
21221:                     if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21222:                         $domdefaults{'postsubmit'} = $defaultshash{'coursedefaults'}{'postsubmit'}{'client'};
21223:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21224:                             foreach my $type (keys(%{$defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}})) {
21225:                                 $domdefaults{$type.'postsubtimeout'} =
21226:                                     $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21227:                             }
21228:                         }
21229:                     }
21230:                 }
21231:                 if ($changes{'uploadquota'}) {
21232:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21233:                         foreach my $type (@types) {
21234:                             $domdefaults{$type.'quota'}=$defaultshash{'coursedefaults'}{'uploadquota'}{$type};
21235:                         }
21236:                     }
21237:                 }
21238:                 if ($changes{'canclone'}) {
21239:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21240:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21241:                             my @clonecodes = @{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}};
21242:                             if (@clonecodes) {
21243:                                 $domdefaults{'canclone'} = join('+',@clonecodes);
21244:                             }
21245:                         }
21246:                     } else {
21247:                         $domdefaults{'canclone'}=$defaultshash{'coursedefaults'}{'canclone'};
21248:                     }
21249:                 }
21250:                 my $cachetime = 24*60*60;
21251:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21252:                 if (ref($lastactref) eq 'HASH') {
21253:                     $lastactref->{'domdefaults'} = 1;
21254:                 }
21255:             }
21256:             $resulttext = &mt('Changes made:').'<ul>';
21257:             foreach my $item (sort(keys(%changes))) {
21258:                 if ($item eq 'canuse_pdfforms') {
21259:                     if ($env{'form.'.$item} eq '1') {
21260:                         $resulttext .= '<li>'.&mt("Course/Community users can create/upload PDF forms set to 'on'").'</li>';
21261:                     } else {
21262:                         $resulttext .= '<li>'.&mt('Course/Community users can create/upload PDF forms set to "off"').'</li>';
21263:                     }
21264:                 } elsif ($item eq 'uselcmath') {
21265:                     if ($env{'form.'.$item} eq '1') {
21266:                         $resulttext .= '<li>'.&mt('Math preview uses LON-CAPA previewer (javascript), if supported by browser.').'</li>';
21267:                     } else {
21268:                         $resulttext .= '<li>'.&mt('Math preview uses DragMath (Java), if supported by client OS.').'</li>';
21269:                     }
21270:                 } elsif ($item eq 'usejsme') {
21271:                     if ($env{'form.'.$item} eq '1') {
21272:                         $resulttext .= '<li>'.&mt('Molecule editor uses JSME (HTML5), if supported by browser.').'</li>';
21273:                     } else {
21274:                         $resulttext .= '<li>'.&mt('Molecule editor uses JME (Java), if supported by client OS.').'</li>';
21275:                     }
21276:                 } elsif ($item eq 'inline_chem') {
21277:                     if ($env{'form.'.$item} eq '1') {
21278:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses inline previewer').'</li>';
21279:                     } else {
21280:                         $resulttext .= '<li>'.&mt('Chemical Reaction Response uses pop-up previewer').'</li>';
21281:                     }
21282:                 } elsif ($item eq 'texengine') {
21283:                     if ($defaultshash{'coursedefaults'}{'texengine'} ne '') {
21284:                         $resulttext .= '<li>'.&mt('Default method to display mathematics set to: "[_1]"',
21285:                                                   $texoptions{$defaultshash{'coursedefaults'}{'texengine'}}).'</li>';
21286:                     }
21287:                 } elsif ($item eq 'anonsurvey_threshold') {
21288:                     $resulttext .= '<li>'.&mt('Responder count required for display of anonymous survey submissions set to [_1].',$defaultshash{'coursedefaults'}{'anonsurvey_threshold'}).'</li>';
21289:                 } elsif ($item eq 'uploadquota') {
21290:                     if (ref($defaultshash{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
21291:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded to a course/community via Course Editor set as follows:').'<ul>'.
21292:                                        '<li>'.&mt('Official courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'official'}.'</b>').'</li>'.
21293:                                        '<li>'.&mt('Unofficial courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'unofficial'}.'</b>').'</li>'.
21294:                                        '<li>'.&mt('Textbook courses: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'textbook'}.'</b>').'</li>'.
21295:                                        '<li>'.&mt('Placement tests: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'placement'}.'</b>').'</li>'. 
21296:                                        '<li>'.&mt('Communities: [_1] MB','<b>'.$defaultshash{'coursedefaults'}{'uploadquota'}{'community'}.'</b>').'</li>'.
21297:                                        '</ul>'.
21298:                                        '</li>';
21299:                     } else {
21300:                         $resulttext .= '<li>'.&mt('Default quota for content uploaded via Course Editor remains default: [_1] MB',$staticdefaults{'uploadquota'}).'</li>';
21301:                     }
21302:                 } elsif ($item eq 'mysqltables') {
21303:                     if (ref($defaultshash{'coursedefaults'}{'mysqltables'}) eq 'HASH') {
21304:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver').'<ul>'.
21305:                                        '<li>'.&mt('Official courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'official'}.'</b>').'</li>'.
21306:                                        '<li>'.&mt('Unofficial courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'unofficial'}.'</b>').'</li>'.
21307:                                        '<li>'.&mt('Textbook courses: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'textbook'}.'</b>').'</li>'.
21308:                                        '<li>'.&mt('Placement tests: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'placement'}.'</b>').'</li>'.
21309:                                        '<li>'.&mt('Communities: [_1] s','<b>'.$defaultshash{'coursedefaults'}{'mysqltables'}{'community'}.'</b>').'</li>'.
21310:                                        '</ul>'.
21311:                                        '</li>';
21312:                     } else {
21313:                         $resulttext .= '<li>'.&mt('Lifetime of "Temporary" MySQL tables (student performance data) on homeserver remains default: [_1] s',$staticdefaults{'uploadquota'}).'</li>';
21314:                     }
21315:                 } elsif ($item eq 'postsubmit') {
21316:                     if ($domdefaults{'postsubmit'} eq 'off') {
21317:                         $resulttext .= '<li>'.&mt('Submit button(s) remain enabled on page after student makes submission.');
21318:                     } else {
21319:                         $resulttext .= '<li>'.&mt('Submit button(s) disabled on page after student makes submission').'; ';
21320:                         if (ref($defaultshash{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
21321:                             $resulttext .= &mt('durations:').'<ul>';
21322:                             foreach my $type (@types) {
21323:                                 $resulttext .= '<li>';
21324:                                 my $timeout;
21325:                                 if (ref($defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
21326:                                     $timeout = $defaultshash{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
21327:                                 }
21328:                                 my $display;
21329:                                 if ($timeout eq '0') {
21330:                                     $display = &mt('unlimited');
21331:                                 } elsif ($timeout eq '') {
21332:                                     $display = &mt('[quant,_1,second] (default)',$staticdefaults{'postsubmit'});
21333:                                 } else {
21334:                                     $display = &mt('[quant,_1,second]',$timeout);
21335:                                 }
21336:                                 if ($type eq 'community') {
21337:                                     $resulttext .= &mt('Communities');
21338:                                 } elsif ($type eq 'official') {
21339:                                     $resulttext .= &mt('Official courses');
21340:                                 } elsif ($type eq 'unofficial') {
21341:                                     $resulttext .= &mt('Unofficial courses');
21342:                                 } elsif ($type eq 'textbook') {
21343:                                     $resulttext .= &mt('Textbook courses');
21344:                                 } elsif ($type eq 'placement') {
21345:                                     $resulttext .= &mt('Placement tests');
21346:                                 }
21347:                                 $resulttext .= ' -- '.$display.'</li>';
21348:                             }
21349:                             $resulttext .= '</ul>';
21350:                         }
21351:                         $resulttext .= '</li>';
21352:                     }
21353:                 } elsif ($item eq 'coursecredits') {
21354:                     if (ref($defaultshash{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
21355:                         if (($domdefaults{'officialcredits'} eq '') &&
21356:                             ($domdefaults{'unofficialcredits'} eq '') &&
21357:                             ($domdefaults{'textbookcredits'} eq '')) {
21358:                             $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21359:                         } else {
21360:                             $resulttext .= '<li>'.&mt('Student credits can be set per course by a Domain Coordinator, with the following defaults applying:').'<ul>'.
21361:                                            '<li>'.&mt('Official courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'official'}).'</li>'.
21362:                                            '<li>'.&mt('Unofficial courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'unofficial'}).'</li>'.
21363:                                            '<li>'.&mt('Textbook courses: [_1]',$defaultshash{'coursedefaults'}{'coursecredits'}{'textbook'}).'</li>'.
21364:                                            '</ul>'.
21365:                                            '</li>';
21366:                         }
21367:                     } else {
21368:                         $resulttext .= '<li>'.&mt('Student credits not in use for courses in this domain').'</li>';
21369:                     }
21370:                 } elsif ($item eq 'canclone') {
21371:                     if (ref($defaultshash{'coursedefaults'}{'canclone'}) eq 'HASH') {
21372:                         if (ref($defaultshash{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
21373:                             my $clonecodes = join(' '.&mt('and').' ',@{$defaultshash{'coursedefaults'}{'canclone'}{'instcode'}});
21374:                             $resulttext .= '<li>'.&mt('By default, official courses can be cloned from existing courses with the same: [_1]','<b>'.$clonecodes.'</b>').'</li>';
21375:                         }
21376:                     } elsif ($defaultshash{'coursedefaults'}{'canclone'} eq 'domain') {
21377:                         $resulttext .= '<li>'.&mt('By default, a course requester can clone any course from his/her domain.').'</li>';
21378:                     } else {
21379:                         $resulttext .= '<li>'.&mt('By default, only course owner and coordinators may clone a course.').'</li>';
21380:                     }
21381:                 } elsif ($item eq 'ltiauth') {
21382:                     if ($env{'form.'.$item} eq '1') {
21383:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL need not require re-authentication').'</li>';
21384:                     } else {
21385:                         $resulttext .= '<li>'.&mt('LTI launch of deep-linked URL will require re-authentication').'</li>';
21386:                     }
21387:                 }
21388:             }
21389:             $resulttext .= '</ul>';
21390:         } else {
21391:             $resulttext = &mt('No changes made to course defaults');
21392:         }
21393:     } else {
21394:         $resulttext = '<span class="LC_error">'.
21395:             &mt('An error occurred: [_1]',$putresult).'</span>';
21396:     }
21397:     return $resulttext;
21398: }
21399: 
21400: sub modify_selfenrollment {
21401:     my ($dom,$lastactref,%domconfig) = @_;
21402:     my ($resulttext,$errors,%changes,%selfenrollhash,%ordered);
21403:     my @types = ('official','unofficial','community','textbook','placement');
21404:     my %titles = &tool_titles();
21405:     my %descs = &Apache::lonuserutils::selfenroll_default_descs();
21406:     ($ordered{'admin'},my $titlesref) = &Apache::lonuserutils::get_selfenroll_titles();
21407:     $ordered{'default'} = ['types','registered','approval','limit'];
21408: 
21409:     my (%roles,%shown,%toplevel);
21410:     $roles{'0'} = &Apache::lonnet::plaintext('dc');
21411: 
21412:     if (ref($domconfig{'selfenrollment'}) ne 'HASH') {
21413:         if ($domconfig{'selfenrollment'} eq '') {
21414:             $domconfig{'selfenrollment'} = {};
21415:         }
21416:     }
21417:     %toplevel = (
21418:                   admin      => 'Configuration Rights',
21419:                   default    => 'Default settings',
21420:                   validation => 'Validation of self-enrollment requests',
21421:                 );
21422:     my ($itemsref,$namesref,$fieldsref) = &Apache::lonuserutils::selfenroll_validation_types();
21423: 
21424:     if (ref($ordered{'admin'}) eq 'ARRAY') {
21425:         foreach my $item (@{$ordered{'admin'}}) {
21426:             foreach my $type (@types) {
21427:                 if ($env{'form.selfenrolladmin_'.$item.'_'.$type}) {
21428:                     $selfenrollhash{'admin'}{$type}{$item} = 1;
21429:                 } else {
21430:                     $selfenrollhash{'admin'}{$type}{$item} = 0;
21431:                 }
21432:                 if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
21433:                     if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
21434:                         if ($selfenrollhash{'admin'}{$type}{$item} ne
21435:                             $domconfig{'selfenrollment'}{'admin'}{$type}{$item})  {
21436:                             push(@{$changes{'admin'}{$type}},$item);
21437:                         }
21438:                     } else {
21439:                         if (!$selfenrollhash{'admin'}{$type}{$item}) {
21440:                             push(@{$changes{'admin'}{$type}},$item);
21441:                         }
21442:                     }
21443:                 } elsif (!$selfenrollhash{'admin'}{$type}{$item}) {
21444:                     push(@{$changes{'admin'}{$type}},$item);
21445:                 }
21446:             }
21447:         }
21448:     }
21449: 
21450:     foreach my $item (@{$ordered{'default'}}) {
21451:         foreach my $type (@types) {
21452:             my $value = $env{'form.selfenrolldefault_'.$item.'_'.$type};
21453:             if ($item eq 'types') {
21454:                 unless (($value eq 'all') || ($value eq 'dom')) {
21455:                     $value = '';
21456:                 }
21457:             } elsif ($item eq 'registered') {
21458:                 unless ($value eq '1') {
21459:                     $value = 0;
21460:                 }
21461:             } elsif ($item eq 'approval') {
21462:                 unless ($value =~ /^[012]$/) {
21463:                     $value = 0;
21464:                 }
21465:             } else {
21466:                 unless (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21467:                     $value = 'none';
21468:                 }
21469:             }
21470:             $selfenrollhash{'default'}{$type}{$item} = $value;
21471:             if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
21472:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21473:                     if ($selfenrollhash{'default'}{$type}{$item} ne
21474:                          $domconfig{'selfenrollment'}{'default'}{$type}{$item})  {
21475:                          push(@{$changes{'default'}{$type}},$item);
21476:                     }
21477:                 } else {
21478:                     push(@{$changes{'default'}{$type}},$item);
21479:                 }
21480:             } else {
21481:                 push(@{$changes{'default'}{$type}},$item);
21482:             }
21483:             if ($item eq 'limit') {
21484:                 if (($value eq 'allstudents') || ($value eq 'selfenrolled')) {
21485:                     $env{'form.selfenrolldefault_cap_'.$type} =~ s/\D//g;
21486:                     if ($env{'form.selfenrolldefault_cap_'.$type} ne '') {
21487:                         $selfenrollhash{'default'}{$type}{'cap'} = $env{'form.selfenrolldefault_cap_'.$type};
21488:                     }
21489:                 } else {
21490:                     $selfenrollhash{'default'}{$type}{'cap'} = '';
21491:                 }
21492:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
21493:                     if ($selfenrollhash{'default'}{$type}{'cap'} ne
21494:                          $domconfig{'selfenrollment'}{'admin'}{$type}{'cap'})  {
21495:                          push(@{$changes{'default'}{$type}},'cap');
21496:                     }
21497:                 } elsif ($selfenrollhash{'default'}{$type}{'cap'} ne '') {
21498:                     push(@{$changes{'default'}{$type}},'cap');
21499:                 }
21500:             }
21501:         }
21502:     }
21503: 
21504:     foreach my $item (@{$itemsref}) {
21505:         if ($item eq 'fields') {
21506:             my @changed;
21507:             @{$selfenrollhash{'validation'}{$item}} = &Apache::loncommon::get_env_multiple('form.selfenroll_validation_'.$item);
21508:             if (@{$selfenrollhash{'validation'}{$item}} > 0) {
21509:                 @{$selfenrollhash{'validation'}{$item}} = sort(@{$selfenrollhash{'validation'}{$item}});
21510:             }
21511:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21512:                 if (ref($domconfig{'selfenrollment'}{'validation'}{$item}) eq 'ARRAY') {
21513:                     @changed = &Apache::loncommon::compare_arrays($selfenrollhash{'validation'}{$item},
21514:                                                                   $domconfig{'selfenrollment'}{'validation'}{$item});
21515:                 } else {
21516:                     @changed = @{$selfenrollhash{'validation'}{$item}};
21517:                 }
21518:             } else {
21519:                 @changed = @{$selfenrollhash{'validation'}{$item}};
21520:             }
21521:             if (@changed) {
21522:                 if ($selfenrollhash{'validation'}{$item}) { 
21523:                     $changes{'validation'}{$item} = join(', ',@{$selfenrollhash{'validation'}{$item}});
21524:                 } else {
21525:                     $changes{'validation'}{$item} = &mt('None');
21526:                 }
21527:             }
21528:         } else {
21529:             $selfenrollhash{'validation'}{$item} = $env{'form.selfenroll_validation_'.$item};
21530:             if ($item eq 'markup') {
21531:                if ($env{'form.selfenroll_validation_'.$item}) {
21532:                    $env{'form.selfenroll_validation_'.$item} =~ s/[\n\r\f]+/\s/gs;
21533:                }
21534:             }
21535:             if (ref($domconfig{'selfenrollment'}{'validation'}) eq 'HASH') {
21536:                 if ($domconfig{'selfenrollment'}{'validation'}{$item} ne $selfenrollhash{'validation'}{$item}) {
21537:                     $changes{'validation'}{$item} = $selfenrollhash{'validation'}{$item};
21538:                 }
21539:             }
21540:         }
21541:     }
21542: 
21543:     my $putresult = &Apache::lonnet::put_dom('configuration',{'selfenrollment' => \%selfenrollhash},
21544:                                              $dom);
21545:     if ($putresult eq 'ok') {
21546:         if (keys(%changes) > 0) {
21547:             my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21548:             $resulttext = &mt('Changes made:').'<ul>';
21549:             foreach my $key ('admin','default','validation') {
21550:                 if (ref($changes{$key}) eq 'HASH') {
21551:                     $resulttext .= '<li>'.$toplevel{$key}.'<ul>';
21552:                     if ($key eq 'validation') {
21553:                         foreach my $item (@{$itemsref}) {
21554:                             if (exists($changes{$key}{$item})) {
21555:                                 if ($item eq 'markup') {
21556:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21557:                                                               '<br /><pre>'.$changes{$key}{$item}.'</pre>').'</li>';
21558:                                 } else {  
21559:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2]',$namesref->{$item},
21560:                                                               '<b>'.$changes{$key}{$item}.'</b>').'</li>';
21561:                                 }
21562:                             }
21563:                         }
21564:                     } else {
21565:                         foreach my $type (@types) {
21566:                             if ($type eq 'community') {
21567:                                 $roles{'1'} = &mt('Community personnel');
21568:                             } else {
21569:                                 $roles{'1'} = &mt('Course personnel');
21570:                             }
21571:                             if (ref($changes{$key}{$type}) eq 'ARRAY') {
21572:                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') {
21573:                                     if ($key eq 'admin') {
21574:                                         my @mgrdc = ();
21575:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21576:                                             foreach my $item (@{$ordered{'admin'}}) {
21577:                                                 if (ref($selfenrollhash{$key}{$type}) eq 'HASH') { 
21578:                                                     if ($selfenrollhash{$key}{$type}{$item} eq '0') {
21579:                                                         push(@mgrdc,$item);
21580:                                                     }
21581:                                                 }
21582:                                             }
21583:                                             if (@mgrdc) {
21584:                                                 $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
21585:                                             } else {
21586:                                                 delete($domdefaults{$type.'selfenrolladmdc'});
21587:                                             }
21588:                                         }
21589:                                     } else {
21590:                                         if (ref($ordered{$key}) eq 'ARRAY') {
21591:                                             foreach my $item (@{$ordered{$key}}) {
21592:                                                 if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21593:                                                     $domdefaults{$type.'selfenroll'.$item} =
21594:                                                         $selfenrollhash{$key}{$type}{$item};
21595:                                                 }
21596:                                             }
21597:                                         }
21598:                                     }
21599:                                 }
21600:                                 $resulttext .= '<li>'.$titles{$type}.'<ul>';
21601:                                 foreach my $item (@{$ordered{$key}}) {
21602:                                     if (grep(/^\Q$item\E$/,@{$changes{$key}{$type}})) {
21603:                                         $resulttext .= '<li>';
21604:                                         if ($key eq 'admin') {
21605:                                             $resulttext .= &mt('[_1] -- management by: [_2]',$titlesref->{$item},
21606:                                                                '<b>'.$roles{$selfenrollhash{'admin'}{$type}{$item}}.'</b>');
21607:                                         } else {
21608:                                             $resulttext .= &mt('[_1] set to: [_2]',$titlesref->{$item},
21609:                                                                '<b>'.$descs{$item}{$selfenrollhash{'default'}{$type}{$item}}.'</b>');
21610:                                         }
21611:                                         $resulttext .= '</li>';
21612:                                     }
21613:                                 }
21614:                                 $resulttext .= '</ul></li>';
21615:                             }
21616:                         }
21617:                         $resulttext .= '</ul></li>'; 
21618:                     }
21619:                 }
21620:             }
21621:             if ((exists($changes{'admin'})) || (exists($changes{'default'}))) {
21622:                 my $cachetime = 24*60*60;
21623:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21624:                 if (ref($lastactref) eq 'HASH') {
21625:                     $lastactref->{'domdefaults'} = 1;
21626:                 }
21627:             }
21628:             $resulttext .= '</ul>';
21629:         } else {
21630:             $resulttext = &mt('No changes made to self-enrollment settings');
21631:         }
21632:     } else {
21633:         $resulttext = '<span class="LC_error">'.
21634:             &mt('An error occurred: [_1]',$putresult).'</span>';
21635:     }
21636:     return $resulttext;
21637: }
21638: 
21639: sub modify_wafproxy {
21640:     my ($dom,$action,$lastactref,%domconfig) = @_;
21641:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
21642:     my (%othercontrol,%canset,%values,%curralias,%currsaml,%currvalue,@warnings,
21643:         %wafproxy,%changes,%expirecache,%expiresaml);
21644:     foreach my $server (sort(keys(%servers))) {
21645:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
21646:         if ($serverhome eq $server) {
21647:             my $serverdom = &Apache::lonnet::host_domain($server);
21648:             if ($serverdom eq $dom) {
21649:                 $canset{$server} = 1;
21650:             }
21651:         }
21652:     }
21653:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
21654:         %{$values{$dom}} = ();
21655:         if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
21656:             %curralias = %{$domconfig{'wafproxy'}{'alias'}};
21657:         }
21658:         if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
21659:             %currsaml = %{$domconfig{'wafproxy'}{'saml'}};
21660:         }
21661:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21662:             $currvalue{$item} = $domconfig{'wafproxy'}{$item};
21663:         }
21664:     }
21665:     my $output;
21666:     if (keys(%canset)) {
21667:         %{$wafproxy{'alias'}} = ();
21668:         %{$wafproxy{'saml'}} = ();
21669:         foreach my $key (sort(keys(%canset))) {
21670:             if ($env{'form.wafproxy_'.$dom}) {
21671:                 $wafproxy{'alias'}{$key} = $env{'form.wafproxy_alias_'.$key};
21672:                 $wafproxy{'alias'}{$key} =~ s/^\s+|\s+$//g;
21673:                 if ($wafproxy{'alias'}{$key} ne $curralias{$key}) {
21674:                     $changes{'alias'} = 1;
21675:                 }
21676:                 if ($env{'form.wafproxy_alias_saml_'.$key}) {
21677:                     $wafproxy{'saml'}{$key} = 1;
21678:                 }
21679:                 if ($wafproxy{'saml'}{$key} ne $currsaml{$key}) {
21680:                     $changes{'saml'} = 1;
21681:                 }
21682:             } else {
21683:                 $wafproxy{'alias'}{$key} = '';
21684:                 $wafproxy{'saml'}{$key} = '';
21685:                 if ($curralias{$key}) {
21686:                     $changes{'alias'} = 1;
21687:                 }
21688:                 if ($currsaml{$key}) {
21689:                     $changes{'saml'} = 1;
21690:                 }
21691:             }
21692:             if ($wafproxy{'alias'}{$key} eq '') {
21693:                 if ($curralias{$key}) {
21694:                     $expirecache{$key} = 1;
21695:                 }
21696:                 delete($wafproxy{'alias'}{$key});
21697:             }
21698:             if ($wafproxy{'saml'}{$key} eq '') {
21699:                 if ($currsaml{$key}) {
21700:                     $expiresaml{$key} = 1;
21701:                 }
21702:                 delete($wafproxy{'saml'}{$key});
21703:             }
21704:         }
21705:         unless (keys(%{$wafproxy{'alias'}})) {
21706:             delete($wafproxy{'alias'});
21707:         }
21708:         unless (keys(%{$wafproxy{'saml'}})) {
21709:             delete($wafproxy{'saml'});
21710:         }
21711:         # Localization for values in %warn occurs in &mt() calls separately.
21712:         my %warn = (
21713:                      trusted => 'trusted IP range(s)',
21714:                      vpnint => 'internal IP range(s) for VPN sessions(s)',
21715:                      vpnext => 'IP range(s) for backend WAF connections',
21716:                    );
21717:         foreach my $item ('remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21718:             my $possible = $env{'form.wafproxy_'.$item};
21719:             $possible =~ s/^\s+|\s+$//g;
21720:             if ($possible ne '') {
21721:                 if ($item eq 'remoteip') {
21722:                     if ($possible =~ /^[mhn]$/) {
21723:                         $wafproxy{$item} = $possible;
21724:                     }
21725:                 } elsif ($item eq 'ipheader') {
21726:                     if ($wafproxy{'remoteip'} eq 'h') {
21727:                         $wafproxy{$item} = $possible;
21728:                     }
21729:                 } elsif ($item eq 'sslopt') {
21730:                     if ($possible =~ /^0|1$/) {
21731:                         $wafproxy{$item} = $possible;
21732:                     }
21733:                 } else {
21734:                     my (@ok,$count);
21735:                     if (($item eq 'vpnint') || ($item eq 'vpnext')) {
21736:                         unless ($env{'form.wafproxy_vpnaccess'}) {
21737:                             $possible = '';
21738:                         }
21739:                     } elsif ($item eq 'trusted') {
21740:                         unless ($wafproxy{'remoteip'} eq 'h') {
21741:                             $possible = '';
21742:                         }
21743:                     }
21744:                     unless ($possible eq '') {
21745:                         $possible =~ s/[\r\n]+/\s/g;
21746:                         $possible =~ s/\s*-\s*/-/g;
21747:                         $possible =~ s/\s+/,/g;
21748:                         $possible =~ s/,+/,/g;
21749:                     }
21750:                     $count = 0;
21751:                     if ($possible ne '') {
21752:                         foreach my $poss (split(/\,/,$possible)) {
21753:                             $count ++;
21754:                             $poss = &validate_ip_pattern($poss);
21755:                             if ($poss ne '') {
21756:                                 push(@ok,$poss);
21757:                             }
21758:                         }
21759:                         my $diff = $count - scalar(@ok);
21760:                         if ($diff) {
21761:                             push(@warnings,'<li>'.
21762:                                  &mt('[quant,_1,IP] invalid and excluded from saved value for [_2]',
21763:                                      $diff,$warn{$item}).
21764:                                  '</li>');
21765:                         }
21766:                         if (@ok) {
21767:                             my @cidr_list;
21768:                             foreach my $item (@ok) {
21769:                                 @cidr_list = &Net::CIDR::cidradd($item,@cidr_list);
21770:                             }
21771:                             $wafproxy{$item} = join(',',@cidr_list);
21772:                         }
21773:                     }
21774:                 }
21775:                 if ($wafproxy{$item} ne $currvalue{$item}) {
21776:                     $changes{$item} = 1;
21777:                 }
21778:             } elsif ($currvalue{$item}) {
21779:                 $changes{$item} = 1;
21780:             } 
21781:         }
21782:     } else {
21783:         if (keys(%curralias)) {
21784:             $changes{'alias'} = 1;
21785:         }
21786:         if (keys(%currsaml)) {
21787:             $changes{'saml'} = 1;
21788:         } 
21789:         if (keys(%currvalue)) {
21790:             foreach my $key (keys(%currvalue)) {
21791:                 $changes{$key} = 1;
21792:             }
21793:         }
21794:     }
21795:     if (keys(%changes)) {
21796:         my %defaultshash = (
21797:                               wafproxy => \%wafproxy,
21798:                            ); 
21799:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
21800:                                                  $dom);
21801:         if ($putresult eq 'ok') {
21802:             my $cachetime = 24*60*60;
21803:             my (%domdefaults,$updatedomdefs);
21804:             foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
21805:                 if ($changes{$item}) {
21806:                     unless ($updatedomdefs) {
21807:                         %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
21808:                         $updatedomdefs = 1;
21809:                     }
21810:                     if ($wafproxy{$item}) {
21811:                         $domdefaults{'waf_'.$item} = $wafproxy{$item};
21812:                     } elsif (exists($domdefaults{'waf_'.$item})) {
21813:                         delete($domdefaults{'waf_'.$item});
21814:                     } 
21815:                 }
21816:             }
21817:             if ($updatedomdefs) {
21818:                 &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
21819:                 if (ref($lastactref) eq 'HASH') {
21820:                     $lastactref->{'domdefaults'} = 1;
21821:                 }
21822:             }
21823:             if ((exists($wafproxy{'alias'})) || (keys(%expirecache))) {
21824:                 my %updates = %expirecache;
21825:                 foreach my $key (keys(%expirecache)) {
21826:                     &Apache::lonnet::devalidate_cache_new('proxyalias',$key);
21827:                 }
21828:                 if (ref($wafproxy{'alias'}) eq 'HASH') {
21829:                     my $cachetime = 24*60*60;
21830:                     foreach my $key (keys(%{$wafproxy{'alias'}})) {
21831:                         $updates{$key} = 1;
21832:                         &Apache::lonnet::do_cache_new('proxyalias',$key,$wafproxy{'alias'}{$key},
21833:                                                       $cachetime);
21834:                     }
21835:                 }
21836:                 if (ref($lastactref) eq 'HASH') {
21837:                     $lastactref->{'proxyalias'} = \%updates;
21838:                 }
21839:             }
21840:             if ((exists($wafproxy{'saml'})) || (keys(%expiresaml))) {
21841:                 my %samlupdates = %expiresaml;
21842:                 foreach my $key (keys(%expiresaml)) {
21843:                     &Apache::lonnet::devalidate_cache_new('proxysaml',$key);
21844:                 }
21845:                 if (ref($wafproxy{'saml'}) eq 'HASH') {
21846:                     my $cachetime = 24*60*60;
21847:                     foreach my $key (keys(%{$wafproxy{'saml'}})) {
21848:                         $samlupdates{$key} = 1;
21849:                         &Apache::lonnet::do_cache_new('proxysaml',$key,$wafproxy{'saml'}{$key},
21850:                                                       $cachetime);
21851:                     }
21852:                 }
21853:                 if (ref($lastactref) eq 'HASH') {
21854:                     $lastactref->{'proxysaml'} = \%samlupdates;
21855:                 }
21856:             }
21857:             $output = &mt('Changes were made to Web Application Firewall/Reverse Proxy').'<ul>';
21858:             foreach my $item ('alias','saml','remoteip','ipheader','trusted','vpnint','vpnext','sslopt') {
21859:                 if ($changes{$item}) {
21860:                     if ($item eq 'alias') {
21861:                         my $numaliased = 0;
21862:                         if (ref($wafproxy{'alias'}) eq 'HASH') {
21863:                             my $shown;
21864:                             if (keys(%{$wafproxy{'alias'}})) {
21865:                                 foreach my $server (sort(keys(%{$wafproxy{'alias'}}))) {
21866:                                     $shown .= '<li>'.&mt('[_1] aliased by [_2]',
21867:                                                          &Apache::lonnet::hostname($server),
21868:                                                          $wafproxy{'alias'}{$server}).'</li>';
21869:                                     $numaliased ++;
21870:                                 }
21871:                                 if ($numaliased) {
21872:                                     $output .= '<li>'.&mt('Aliases for hostnames set to: [_1]',
21873:                                                           '<ul>'.$shown.'</ul>').'</li>';
21874:                                 }
21875:                             }
21876:                         }
21877:                         unless ($numaliased) {
21878:                             $output .= '<li>'.&mt('Aliases deleted for hostnames').'</li>';
21879:                         }
21880:                     } elsif ($item eq 'saml') {
21881:                         my $shown; 
21882:                         if (ref($wafproxy{'saml'}) eq 'HASH') {
21883:                             if (keys(%{$wafproxy{'saml'}})) {
21884:                                 $shown = join(', ',sort(keys(%{$wafproxy{'saml'}})));
21885:                             }
21886:                         }
21887:                         if ($shown) {
21888:                             $output .= '<li>'.&mt('Alias used by SSO Auth for: [_1]',
21889:                                                   $shown).'</li>';
21890:                         } else {
21891:                             $output .= '<li>'.&mt('No alias used for SSO Auth').'</li>';
21892:                         }
21893:                     } else {
21894:                         if ($item eq 'remoteip') {
21895:                             my %ip_methods = &remoteip_methods();
21896:                             if ($wafproxy{$item} =~ /^[mh]$/) {
21897:                                 $output .= '<li>'.&mt("Method for determining user's IP set to: [_1]",
21898:                                                       $ip_methods{$wafproxy{$item}}).'</li>';
21899:                             } else {
21900:                                 if (($env{'form.wafproxy_'.$dom}) && (ref($wafproxy{'alias'}) eq 'HASH')) {
21901:                                     $output .= '<li>'.&mt("No method in use to get user's real IP (will report IP used by WAF).").
21902:                                                '</li>';
21903:                                 } else {
21904:                                     $output .= '<li>'.&mt('WAF/Reverse Proxy not in use').'</li>';
21905:                                 }
21906:                             }
21907:                         } elsif ($item eq 'ipheader') {
21908:                             if ($wafproxy{$item}) {
21909:                                 $output .= '<li>'.&mt('Request header with remote IP set to: [_1]',
21910:                                                       $wafproxy{$item}).'</li>';
21911:                             } else {
21912:                                 $output .= '<li>'.&mt('Request header with remote IP deleted').'</li>';
21913:                             }
21914:                         } elsif ($item eq 'trusted') {
21915:                             if ($wafproxy{$item}) {
21916:                                 $output .= '<li>'.&mt('Trusted IP range(s) set to: [_1]',
21917:                                                       $wafproxy{$item}).'</li>';
21918:                             } else {
21919:                                 $output .= '<li>'.&mt('Trusted IP range(s) deleted').'</li>';
21920:                             }
21921:                         } elsif ($item eq 'vpnint') {
21922:                             if ($wafproxy{$item}) {
21923:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions set to: [_1]',
21924:                                                        $wafproxy{$item}).'</li>';
21925:                             } else {
21926:                                 $output .= '<li>'.&mt('Internal IP Range(s) for VPN sessions deleted').'</li>';
21927:                             }
21928:                         } elsif ($item eq 'vpnext') {
21929:                             if ($wafproxy{$item}) {
21930:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections set to: [_1]',
21931:                                                        $wafproxy{$item}).'</li>';
21932:                             } else {
21933:                                 $output .= '<li>'.&mt('IP Range(s) for backend WAF connections deleted').'</li>';
21934:                             }
21935:                         } elsif ($item eq 'sslopt') {
21936:                             if ($wafproxy{$item}) {
21937:                                 $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>';
21938:                             } else {
21939:                                 $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>';
21940:                             }
21941:                         }
21942:                     }
21943:                 }
21944:             }
21945:         } else {
21946:             $output = '<span class="LC_error">'.
21947:                       &mt('An error occurred: [_1]',$putresult).'</span>';
21948:         }
21949:     } elsif (keys(%canset)) {
21950:         $output = &mt('No changes made to Web Application Firewall/Reverse Proxy settings');
21951:     }
21952:     if (@warnings) {
21953:         $output .= '<br />'.&mt('Warnings:').'<ul>'.
21954:                        join("\n",@warnings).'</ul>';
21955:     }
21956:     return $output;
21957: }
21958: 
21959: sub validate_ip_pattern {
21960:     my ($pattern) = @_;
21961:     if ($pattern =~ /^([^-]+)\-([^-]+)$/) {
21962:         my ($start,$end) = ($1,$2);
21963:         if ((&Net::CIDR::cidrvalidate($start)) && (&Net::CIDR::cidrvalidate($end))) {
21964:             if (($start !~ m{/}) && ($end !~ m{/})) {
21965:                 return $start.'-'.$end;
21966:             }
21967:         }
21968:     } elsif ($pattern ne '') {
21969:         $pattern = &Net::CIDR::cidrvalidate($pattern);
21970:         if ($pattern ne '') {
21971:             return $pattern;
21972:         }
21973:     }
21974:     return;
21975: }
21976: 
21977: sub modify_usersessions {
21978:     my ($dom,$lastactref,%domconfig) = @_;
21979:     my @hostingtypes = ('version','excludedomain','includedomain');
21980:     my @offloadtypes = ('primary','default');
21981:     my %types = (
21982:                   remote => \@hostingtypes,
21983:                   hosted => \@hostingtypes,
21984:                   spares => \@offloadtypes,
21985:                 );
21986:     my @prefixes = ('remote','hosted','spares');
21987:     my @lcversions = &Apache::lonnet::all_loncaparevs();
21988:     my (%by_ip,%by_location,@intdoms,@instdoms);
21989:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
21990:     my @locations = sort(keys(%by_location));
21991:     my (%defaultshash,%changes);
21992:     foreach my $prefix (@prefixes) {
21993:         $defaultshash{'usersessions'}{$prefix} = {};
21994:     }
21995:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
21996:     my $resulttext;
21997:     my %iphost = &Apache::lonnet::get_iphost();
21998:     foreach my $prefix (@prefixes) {
21999:         next if ($prefix eq 'spares');
22000:         foreach my $type (@{$types{$prefix}}) {
22001:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22002:             if ($type eq 'version') {
22003:                 my $value = $env{'form.'.$prefix.'_'.$type};
22004:                 my $okvalue;
22005:                 if ($value ne '') {
22006:                     if (grep(/^\Q$value\E$/,@lcversions)) {
22007:                         $okvalue = $value;
22008:                     }
22009:                 }
22010:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22011:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22012:                         if ($domconfig{'usersessions'}{$prefix}{$type} ne '') {
22013:                             if ($inuse == 0) {
22014:                                 $changes{$prefix}{$type} = 1;
22015:                             } else {
22016:                                 if ($okvalue ne $domconfig{'usersessions'}{$prefix}{$type}) {
22017:                                     $changes{$prefix}{$type} = 1;
22018:                                 }
22019:                                 if ($okvalue ne '') {
22020:                                     $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22021:                                 } 
22022:                             }
22023:                         } else {
22024:                             if (($inuse == 1) && ($okvalue ne '')) {
22025:                                 $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22026:                                 $changes{$prefix}{$type} = 1;
22027:                             }
22028:                         }
22029:                     } else {
22030:                         if (($inuse == 1) && ($okvalue ne '')) {
22031:                             $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22032:                             $changes{$prefix}{$type} = 1;
22033:                         }
22034:                     }
22035:                 } else {
22036:                     if (($inuse == 1) && ($okvalue ne '')) {
22037:                         $defaultshash{'usersessions'}{$prefix}{$type} = $okvalue;
22038:                         $changes{$prefix}{$type} = 1;
22039:                     }
22040:                 }
22041:             } else {
22042:                 my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22043:                 my @okvals;
22044:                 foreach my $val (@vals) {
22045:                     if ($val =~ /:/) {
22046:                         my @items = split(/:/,$val);
22047:                         foreach my $item (@items) {
22048:                             if (ref($by_location{$item}) eq 'ARRAY') {
22049:                                 push(@okvals,$item);
22050:                             }
22051:                         }
22052:                     } else {
22053:                         if (ref($by_location{$val}) eq 'ARRAY') {
22054:                             push(@okvals,$val);
22055:                         }
22056:                     }
22057:                 }
22058:                 @okvals = sort(@okvals);
22059:                 if (ref($domconfig{'usersessions'}) eq 'HASH') {
22060:                     if (ref($domconfig{'usersessions'}{$prefix}) eq 'HASH') {
22061:                         if (ref($domconfig{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22062:                             if ($inuse == 0) {
22063:                                 $changes{$prefix}{$type} = 1; 
22064:                             } else {
22065:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22066:                                 my @changed = &Apache::loncommon::compare_arrays($domconfig{'usersessions'}{$prefix}{$type},$defaultshash{'usersessions'}{$prefix}{$type});
22067:                                 if (@changed > 0) {
22068:                                     $changes{$prefix}{$type} = 1;
22069:                                 }
22070:                             }
22071:                         } else {
22072:                             if ($inuse == 1) {
22073:                                 $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22074:                                 $changes{$prefix}{$type} = 1;
22075:                             }
22076:                         } 
22077:                     } else {
22078:                         if ($inuse == 1) {
22079:                             $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22080:                             $changes{$prefix}{$type} = 1;
22081:                         }
22082:                     }
22083:                 } else {
22084:                     if ($inuse == 1) {
22085:                         $defaultshash{'usersessions'}{$prefix}{$type} = \@okvals;
22086:                         $changes{$prefix}{$type} = 1;
22087:                     }
22088:                 }
22089:             }
22090:         }
22091:     }
22092: 
22093:     my @alldoms = &Apache::lonnet::all_domains();
22094:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22095:     my %spareid = &current_offloads_to($dom,$domconfig{'usersessions'},\%servers);
22096:     my $savespares;
22097: 
22098:     foreach my $lonhost (sort(keys(%servers))) {
22099:         my $serverhomeID =
22100:             &Apache::lonnet::get_server_homeID($servers{$lonhost});
22101:         my $serverhostname = &Apache::lonnet::hostname($lonhost);
22102:         $defaultshash{'usersessions'}{'spares'}{$lonhost} = {};
22103:         my %spareschg;
22104:         foreach my $type (@{$types{'spares'}}) {
22105:             my @okspares;
22106:             my @checked = &Apache::loncommon::get_env_multiple('form.spare_'.$type.'_'.$lonhost);
22107:             foreach my $server (@checked) {
22108:                 if (&Apache::lonnet::hostname($server) ne '') {
22109:                     unless (&Apache::lonnet::hostname($server) eq $serverhostname) {
22110:                         unless (grep(/^\Q$server\E$/,@okspares)) {
22111:                             push(@okspares,$server);
22112:                         }
22113:                     }
22114:                 }
22115:             }
22116:             my $new = $env{'form.newspare_'.$type.'_'.$lonhost};
22117:             my $newspare;
22118:             if (($new ne '') && (&Apache::lonnet::hostname($new))) {
22119:                 unless (&Apache::lonnet::hostname($new) eq $serverhostname) {
22120:                     $newspare = $new;
22121:                 }
22122:             }
22123:             my @spares;
22124:             if (($newspare ne '') && (!grep(/^\Q$newspare\E$/,@okspares))) {
22125:                 @spares = sort(@okspares,$newspare);
22126:             } else {
22127:                 @spares = sort(@okspares);
22128:             }
22129:             $defaultshash{'usersessions'}{'spares'}{$lonhost}{$type} = \@spares;
22130:             if (ref($spareid{$lonhost}) eq 'HASH') {
22131:                 if (ref($spareid{$lonhost}{$type}) eq 'ARRAY') {
22132:                     my @diffs = &Apache::loncommon::compare_arrays($spareid{$lonhost}{$type},\@spares);
22133:                     if (@diffs > 0) {
22134:                         $spareschg{$type} = 1;
22135:                     }
22136:                 }
22137:             }
22138:         }
22139:         if (keys(%spareschg) > 0) {
22140:             $changes{'spares'}{$lonhost} = \%spareschg;
22141:         }
22142:     }
22143:     $defaultshash{'usersessions'}{'offloadnow'} = {};
22144:     $defaultshash{'usersessions'}{'offloadoth'} = {};
22145:     my @offloadnow = &Apache::loncommon::get_env_multiple('form.offloadnow');
22146:     my @okoffload;
22147:     if (@offloadnow) {
22148:         foreach my $server (@offloadnow) {
22149:             if (&Apache::lonnet::hostname($server) ne '') {
22150:                 unless (grep(/^\Q$server\E$/,@okoffload)) {
22151:                     push(@okoffload,$server);
22152:                 }
22153:             }
22154:         }
22155:         if (@okoffload) {
22156:             foreach my $lonhost (@okoffload) {
22157:                 $defaultshash{'usersessions'}{'offloadnow'}{$lonhost} = 1;
22158:             }
22159:         }
22160:     }
22161:     my @offloadoth = &Apache::loncommon::get_env_multiple('form.offloadoth');
22162:     my @okoffloadoth;
22163:     if (@offloadoth) {
22164:         foreach my $server (@offloadoth) {
22165:             if (&Apache::lonnet::hostname($server) ne '') {
22166:                 unless (grep(/^\Q$server\E$/,@okoffloadoth)) {
22167:                     push(@okoffloadoth,$server);
22168:                 }
22169:             }
22170:         }
22171:         if (@okoffloadoth) {
22172:             foreach my $lonhost (@okoffloadoth) {
22173:                 $defaultshash{'usersessions'}{'offloadoth'}{$lonhost} = 1;
22174:             }
22175:         }
22176:     }
22177:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
22178:         if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
22179:             if (ref($changes{'spares'}) eq 'HASH') {
22180:                 if (keys(%{$changes{'spares'}}) > 0) {
22181:                     $savespares = 1;
22182:                 }
22183:             }
22184:         } else {
22185:             $savespares = 1;
22186:         }
22187:         foreach my $offload ('offloadnow','offloadoth') {
22188:             if (ref($domconfig{'usersessions'}{$offload}) eq 'HASH') {
22189:                 foreach my $lonhost (keys(%{$domconfig{'usersessions'}{$offload}})) {
22190:                     unless ($defaultshash{'usersessions'}{$offload}{$lonhost}) {
22191:                         $changes{$offload} = 1;
22192:                         last;
22193:                     }
22194:                 }
22195:                 unless ($changes{$offload}) {
22196:                     foreach my $lonhost (keys(%{$defaultshash{'usersessions'}{$offload}})) {
22197:                         unless ($domconfig{'usersessions'}{$offload}{$lonhost}) {
22198:                             $changes{$offload} = 1;
22199:                             last;
22200:                         }
22201:                     }
22202:                 }
22203:             } else {
22204:                 if (($offload eq 'offloadnow') && (@okoffload)) {
22205:                      $changes{'offloadnow'} = 1;
22206:                 }
22207:                 if (($offload eq 'offloadoth') && (@okoffloadoth)) {
22208:                     $changes{'offloadoth'} = 1;
22209:                 }
22210:             } 
22211:         }
22212:     } else {
22213:         if (@okoffload) {
22214:             $changes{'offloadnow'} = 1;
22215:         }
22216:         if (@okoffloadoth) {
22217:             $changes{'offloadoth'} = 1;
22218:         }
22219:     }
22220:     my $nochgmsg = &mt('No changes made to settings for user session hosting/offloading.');
22221:     if ((keys(%changes) > 0) || ($savespares)) {
22222:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22223:                                                  $dom);
22224:         if ($putresult eq 'ok') {
22225:             if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22226:                 if (ref($defaultshash{'usersessions'}{'remote'}) eq 'HASH') {
22227:                     $domdefaults{'remotesessions'} = $defaultshash{'usersessions'}{'remote'};
22228:                 }
22229:                 if (ref($defaultshash{'usersessions'}{'hosted'}) eq 'HASH') {
22230:                     $domdefaults{'hostedsessions'} = $defaultshash{'usersessions'}{'hosted'};
22231:                 }
22232:                 if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22233:                     $domdefaults{'offloadnow'} = $defaultshash{'usersessions'}{'offloadnow'};
22234:                 }
22235:                 if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22236:                     $domdefaults{'offloadoth'} = $defaultshash{'usersessions'}{'offloadoth'};
22237:                 }
22238:             }
22239:             my $cachetime = 24*60*60;
22240:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22241:             &Apache::lonnet::do_cache_new('usersessions',$dom,$defaultshash{'usersessions'},3600);
22242:             if (ref($lastactref) eq 'HASH') {
22243:                 $lastactref->{'domdefaults'} = 1;
22244:                 $lastactref->{'usersessions'} = 1;
22245:             }
22246:             if (keys(%changes) > 0) {
22247:                 my %lt = &usersession_titles();
22248:                 $resulttext = &mt('Changes made:').'<ul>';
22249:                 foreach my $prefix (@prefixes) {
22250:                     if (ref($changes{$prefix}) eq 'HASH') {
22251:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22252:                         if ($prefix eq 'spares') {
22253:                             if (ref($changes{$prefix}) eq 'HASH') {
22254:                                 foreach my $lonhost (sort(keys(%{$changes{$prefix}}))) {
22255:                                     $resulttext .= '<li><b>'.$lonhost.'</b> ';
22256:                                     my $lonhostdom = &Apache::lonnet::host_domain($lonhost);
22257:                                     my $cachekey = &escape('spares').':'.&escape($lonhostdom);
22258:                                     &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
22259:                                     if (ref($changes{$prefix}{$lonhost}) eq 'HASH') {
22260:                                         foreach my $type (@{$types{$prefix}}) {
22261:                                             if ($changes{$prefix}{$lonhost}{$type}) {
22262:                                                 my $offloadto = &mt('None');
22263:                                                 if (ref($defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}) eq 'ARRAY') {
22264:                                                     if (@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}} > 0) {   
22265:                                                         $offloadto = join(', ',@{$defaultshash{'usersessions'}{'spares'}{$lonhost}{$type}});
22266:                                                     }
22267:                                                 }
22268:                                                 $resulttext .= &mt('[_1] set to: [_2].','<i>'.$lt{$type}.'</i>',$offloadto).('&nbsp;'x3);
22269:                                             }
22270:                                         }
22271:                                     }
22272:                                     $resulttext .= '</li>';
22273:                                 }
22274:                             }
22275:                         } else {
22276:                             foreach my $type (@{$types{$prefix}}) {
22277:                                 if (defined($changes{$prefix}{$type})) {
22278:                                     my ($newvalue,$notinuse);
22279:                                     if (ref($defaultshash{'usersessions'}) eq 'HASH') {
22280:                                         if (ref($defaultshash{'usersessions'}{$prefix})) {
22281:                                             if ($type eq 'version') {
22282:                                                 $newvalue = $defaultshash{'usersessions'}{$prefix}{$type};
22283:                                             } else {
22284:                                                 if (ref($defaultshash{'usersessions'}{$prefix}{$type}) eq 'ARRAY') {
22285:                                                     if (@{$defaultshash{'usersessions'}{$prefix}{$type}} > 0) {
22286:                                                         $newvalue = join(', ',@{$defaultshash{'usersessions'}{$prefix}{$type}});
22287:                                                     }
22288:                                                 } else {
22289:                                                     $notinuse = 1;
22290:                                                 }
22291:                                             }
22292:                                         }
22293:                                     }
22294:                                     if ($newvalue eq '') {
22295:                                         if ($type eq 'version') {
22296:                                             $resulttext .= '<li>'.&mt('[_1] set to: off',$lt{$type}).'</li>';
22297:                                         } elsif ($notinuse) {
22298:                                             $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22299:                                         } else {
22300:                                             $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22301:                                         }
22302:                                     } else {
22303:                                         if ($type eq 'version') {
22304:                                             $newvalue .= ' '.&mt('(or later)');
22305:                                         }
22306:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22307:                                     }
22308:                                 }
22309:                             }
22310:                         }
22311:                         $resulttext .= '</ul>';
22312:                     }
22313:                 }
22314:                 if ($changes{'offloadnow'}) {
22315:                     if (ref($defaultshash{'usersessions'}{'offloadnow'}) eq 'HASH') {
22316:                         if (keys(%{$defaultshash{'usersessions'}{'offloadnow'}}) > 0) {
22317:                             $resulttext .= '<li>'.&mt('Switch any active user on next access, for server(s):').'<ul>';
22318:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadnow'}}))) {
22319:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22320:                             }
22321:                             $resulttext .= '</ul>';
22322:                         } else {
22323:                             $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.');
22324:                         }
22325:                     } else {
22326:                         $resulttext .= '<li>'.&mt('No servers now set to switch any active user on next access.').'</li>';
22327:                     }
22328:                 }
22329:                 if ($changes{'offloadoth'}) {
22330:                     if (ref($defaultshash{'usersessions'}{'offloadoth'}) eq 'HASH') {
22331:                         if (keys(%{$defaultshash{'usersessions'}{'offloadoth'}}) > 0) {
22332:                             $resulttext .= '<li>'.&mt('Switch other institutions on next access, for server(s):').'<ul>';
22333:                             foreach my $lonhost (sort(keys(%{$defaultshash{'usersessions'}{'offloadoth'}}))) {
22334:                                 $resulttext .= '<li>'.$lonhost.'</li>';
22335:                             }
22336:                             $resulttext .= '</ul>';
22337:                         } else {
22338:                             $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.');
22339:                         }
22340:                     } else {
22341:                         $resulttext .= '<li>'.&mt('No servers now set to switch other institutions on next access.').'</li>';
22342:                     }
22343:                 }
22344:                 $resulttext .= '</ul>';
22345:             } else {
22346:                 $resulttext = $nochgmsg;
22347:             }
22348:         } else {
22349:             $resulttext = '<span class="LC_error">'.
22350:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22351:         }
22352:     } else {
22353:         $resulttext = $nochgmsg;
22354:     }
22355:     return $resulttext;
22356: }
22357: 
22358: sub modify_ssl {
22359:     my ($dom,$lastactref,%domconfig) = @_;
22360:     my (%by_ip,%by_location,@intdoms,@instdoms);
22361:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22362:     my @locations = sort(keys(%by_location));
22363:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22364:     my (%defaultshash,%changes);
22365:     my $action = 'ssl';
22366:     my @prefixes = ('connto','connfrom','replication');
22367:     foreach my $prefix (@prefixes) {
22368:         $defaultshash{$action}{$prefix} = {};
22369:     }
22370:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22371:     my $resulttext;
22372:     my %iphost = &Apache::lonnet::get_iphost();
22373:     my @reptypes = ('certreq','nocertreq');
22374:     my @connecttypes = ('dom','intdom','other');
22375:     my %types = (
22376:                   connto      => \@connecttypes,
22377:                   connfrom    => \@connecttypes,
22378:                   replication => \@reptypes,
22379:                 );
22380:     foreach my $prefix (sort(keys(%types))) {
22381:         foreach my $type (@{$types{$prefix}}) {
22382:             if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22383:                 my $value = 'yes';
22384:                 if ($env{'form.'.$prefix.'_'.$type} =~ /^(no|req)$/) {
22385:                     $value = $env{'form.'.$prefix.'_'.$type};
22386:                 }
22387:                 if (ref($domconfig{$action}) eq 'HASH') {
22388:                     if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22389:                         if ($domconfig{$action}{$prefix}{$type} ne '') {
22390:                             if ($value ne $domconfig{$action}{$prefix}{$type}) {
22391:                                 $changes{$prefix}{$type} = 1;
22392:                             }
22393:                             $defaultshash{$action}{$prefix}{$type} = $value;
22394:                         } else {
22395:                             $defaultshash{$action}{$prefix}{$type} = $value;
22396:                             $changes{$prefix}{$type} = 1;
22397:                         }
22398:                     } else {
22399:                         $defaultshash{$action}{$prefix}{$type} = $value;
22400:                         $changes{$prefix}{$type} = 1;
22401:                     }
22402:                 } else {
22403:                     $defaultshash{$action}{$prefix}{$type} = $value;
22404:                     $changes{$prefix}{$type} = 1;
22405:                 }
22406:                 if (($type eq 'dom') && (keys(%servers) == 1)) {
22407:                     delete($changes{$prefix}{$type});
22408:                 } elsif (($type eq 'intdom') && (@instdoms == 1)) {
22409:                     delete($changes{$prefix}{$type});
22410:                 } elsif (($type eq 'other') && (keys(%by_location) == 0)) { 
22411:                     delete($changes{$prefix}{$type});
22412:                 }
22413:             } elsif ($prefix eq 'replication') {
22414:                 if (@locations > 0) {
22415:                     my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22416:                     my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22417:                     my @okvals;
22418:                     foreach my $val (@vals) {
22419:                         if ($val =~ /:/) {
22420:                             my @items = split(/:/,$val);
22421:                             foreach my $item (@items) {
22422:                                 if (ref($by_location{$item}) eq 'ARRAY') {
22423:                                     push(@okvals,$item);
22424:                                 }
22425:                             }
22426:                         } else {
22427:                             if (ref($by_location{$val}) eq 'ARRAY') {
22428:                                 push(@okvals,$val);
22429:                             }
22430:                         }
22431:                     }
22432:                     @okvals = sort(@okvals);
22433:                     if (ref($domconfig{$action}) eq 'HASH') {
22434:                         if (ref($domconfig{$action}{$prefix}) eq 'HASH') {
22435:                             if (ref($domconfig{$action}{$prefix}{$type}) eq 'ARRAY') {
22436:                                 if ($inuse == 0) {
22437:                                     $changes{$prefix}{$type} = 1;
22438:                                 } else {
22439:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22440:                                     my @changed = &Apache::loncommon::compare_arrays($domconfig{$action}{$prefix}{$type},$defaultshash{$action}{$prefix}{$type});
22441:                                     if (@changed > 0) {
22442:                                         $changes{$prefix}{$type} = 1;
22443:                                     }
22444:                                 }
22445:                             } else {
22446:                                 if ($inuse == 1) {
22447:                                     $defaultshash{$action}{$prefix}{$type} = \@okvals;
22448:                                     $changes{$prefix}{$type} = 1;
22449:                                 }
22450:                             }
22451:                         } else {
22452:                             if ($inuse == 1) {
22453:                                 $defaultshash{$action}{$prefix}{$type} = \@okvals;
22454:                                 $changes{$prefix}{$type} = 1;
22455:                             }
22456:                         }
22457:                     } else {
22458:                         if ($inuse == 1) {
22459:                             $defaultshash{$action}{$prefix}{$type} = \@okvals;
22460:                             $changes{$prefix}{$type} = 1;
22461:                         }
22462:                     }
22463:                 }
22464:             }
22465:         }
22466:     }
22467:     if (keys(%changes)) {
22468:         foreach my $prefix (keys(%changes)) {
22469:             if (ref($changes{$prefix}) eq 'HASH') {
22470:                 if (scalar(keys(%{$changes{$prefix}})) == 0) {
22471:                     delete($changes{$prefix});
22472:                 }
22473:             } else {
22474:                 delete($changes{$prefix});
22475:             }
22476:         }
22477:     }
22478:     my $nochgmsg = &mt('No changes made to LON-CAPA SSL settings');
22479:     if (keys(%changes) > 0) {
22480:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22481:                                                  $dom);
22482:         if ($putresult eq 'ok') {
22483:             if (ref($defaultshash{$action}) eq 'HASH') {
22484:                 if (ref($defaultshash{$action}{'replication'}) eq 'HASH') {
22485:                     $domdefaults{'replication'} = $defaultshash{$action}{'replication'};
22486:                 }
22487:                 if (ref($defaultshash{$action}{'connto'}) eq 'HASH') {
22488:                     $domdefaults{'connto'} = $defaultshash{$action}{'connto'};
22489:                 }
22490:                 if (ref($defaultshash{$action}{'connfrom'}) eq 'HASH') {
22491:                     $domdefaults{'connfrom'} = $defaultshash{$action}{'connfrom'};
22492:                 }
22493:             }
22494:             my $cachetime = 24*60*60;
22495:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22496:             if (ref($lastactref) eq 'HASH') {
22497:                 $lastactref->{'domdefaults'} = 1;
22498:             }
22499:             if (keys(%changes) > 0) {
22500:                 my %titles = &ssl_titles();
22501:                 $resulttext = &mt('Changes made:').'<ul>';
22502:                 foreach my $prefix (@prefixes) {
22503:                     if (ref($changes{$prefix}) eq 'HASH') {
22504:                         $resulttext .= '<li>'.$titles{$prefix}.'<ul>';
22505:                         foreach my $type (@{$types{$prefix}}) {
22506:                             if (defined($changes{$prefix}{$type})) {
22507:                                 my ($newvalue,$notinuse);
22508:                                 if (ref($defaultshash{$action}) eq 'HASH') {
22509:                                     if (ref($defaultshash{$action}{$prefix})) {
22510:                                         if (($prefix eq 'connto') || ($prefix eq 'connfrom')) {
22511:                                             $newvalue = $titles{$defaultshash{$action}{$prefix}{$type}};
22512:                                         } else {
22513:                                             if (ref($defaultshash{$action}{$prefix}{$type}) eq 'ARRAY') {
22514:                                                 if (@{$defaultshash{$action}{$prefix}{$type}} > 0) {
22515:                                                     $newvalue = join(', ',@{$defaultshash{$action}{$prefix}{$type}});
22516:                                                 }
22517:                                             } else {
22518:                                                 $notinuse = 1;
22519:                                             }
22520:                                         }
22521:                                     }
22522:                                     if ($notinuse) {
22523:                                         $resulttext .= '<li>'.&mt('[_1] set to: not in use',$titles{$type}).'</li>';
22524:                                     } elsif ($newvalue eq '') {
22525:                                         $resulttext .= '<li>'.&mt('[_1] set to: none',$titles{$type}).'</li>';
22526:                                     } else {
22527:                                         $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$titles{$type},$newvalue).'</li>';
22528:                                     }
22529:                                 }
22530:                             }
22531:                         }
22532:                         $resulttext .= '</ul>';
22533:                     }
22534:                 }
22535:             } else {
22536:                 $resulttext = $nochgmsg;
22537:             }
22538:         } else {
22539:             $resulttext = '<span class="LC_error">'.
22540:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22541:         }
22542:     } else {
22543:         $resulttext = $nochgmsg;
22544:     }
22545:     return $resulttext;
22546: }
22547: 
22548: sub modify_trust {
22549:     my ($dom,$lastactref,%domconfig) = @_;
22550:     my (%by_ip,%by_location,@intdoms,@instdoms);
22551:     &build_location_hashes(\@intdoms,\%by_ip,\%by_location,\@instdoms);
22552:     my @locations = sort(keys(%by_location));
22553:     my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
22554:     my @types = ('exc','inc');
22555:     my (%defaultshash,%changes);
22556:     foreach my $prefix (@prefixes) {
22557:         $defaultshash{'trust'}{$prefix} = {};
22558:     }
22559:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom,1);
22560:     my $resulttext;
22561:     foreach my $prefix (@prefixes) {
22562:         foreach my $type (@types) {
22563:             my $inuse = $env{'form.'.$prefix.'_'.$type.'_inuse'};
22564:             my @vals = &Apache::loncommon::get_env_multiple('form.'.$prefix.'_'.$type);
22565:             my @okvals;
22566:             foreach my $val (@vals) {
22567:                 if ($val =~ /:/) {
22568:                     my @items = split(/:/,$val);
22569:                     foreach my $item (@items) {
22570:                         if (ref($by_location{$item}) eq 'ARRAY') {
22571:                             push(@okvals,$item);
22572:                         }
22573:                     }
22574:                 } else {
22575:                     if (ref($by_location{$val}) eq 'ARRAY') {
22576:                         push(@okvals,$val);
22577:                     }
22578:                 }
22579:             }
22580:             @okvals = sort(@okvals);
22581:             if (ref($domconfig{'trust'}) eq 'HASH') {
22582:                 if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
22583:                     if (ref($domconfig{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22584:                         if ($inuse == 0) {
22585:                             $changes{$prefix}{$type} = 1;
22586:                         } else {
22587:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22588:                             my @changed = &Apache::loncommon::compare_arrays($domconfig{'trust'}{$prefix}{$type},$defaultshash{'trust'}{$prefix}{$type});
22589:                             if (@changed > 0) {
22590:                                 $changes{$prefix}{$type} = 1;
22591:                             }
22592:                         }
22593:                     } else {
22594:                         if ($inuse == 1) {
22595:                             $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22596:                             $changes{$prefix}{$type} = 1;
22597:                         }
22598:                     }
22599:                 } else {
22600:                     if ($inuse == 1) {
22601:                         $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22602:                         $changes{$prefix}{$type} = 1;
22603:                     }
22604:                 }
22605:             } else {
22606:                 if ($inuse == 1) {
22607:                     $defaultshash{'trust'}{$prefix}{$type} = \@okvals;
22608:                     $changes{$prefix}{$type} = 1;
22609:                 }
22610:             }
22611:         }
22612:     }
22613:     my $nochgmsg = &mt('No changes made to trust settings.');
22614:     if (keys(%changes) > 0) {
22615:         my $putresult = &Apache::lonnet::put_dom('configuration',\%defaultshash,
22616:                                                  $dom);
22617:         if ($putresult eq 'ok') {
22618:             if (ref($defaultshash{'trust'}) eq 'HASH') {
22619:                 foreach my $prefix (@prefixes) {
22620:                     if (ref($defaultshash{'trust'}{$prefix}) eq 'HASH') {
22621:                         $domdefaults{'trust'.$prefix} = $defaultshash{'trust'}{$prefix};
22622:                     }
22623:                 }
22624:             }
22625:             my $cachetime = 24*60*60;
22626:             &Apache::lonnet::do_cache_new('domdefaults',$dom,\%domdefaults,$cachetime);
22627:             if (ref($lastactref) eq 'HASH') {
22628:                 $lastactref->{'domdefaults'} = 1;
22629:             }
22630:             if (keys(%changes) > 0) {
22631:                 my %lt = &trust_titles();
22632:                 $resulttext = &mt('Changes made:').'<ul>';
22633:                 foreach my $prefix (@prefixes) {
22634:                     if (ref($changes{$prefix}) eq 'HASH') {
22635:                         $resulttext .= '<li>'.$lt{$prefix}.'<ul>';
22636:                         foreach my $type (@types) {
22637:                             if (defined($changes{$prefix}{$type})) {
22638:                                 my ($newvalue,$notinuse);
22639:                                 if (ref($defaultshash{'trust'}) eq 'HASH') {
22640:                                     if (ref($defaultshash{'trust'}{$prefix})) {
22641:                                         if (ref($defaultshash{'trust'}{$prefix}{$type}) eq 'ARRAY') {
22642:                                             if (@{$defaultshash{'trust'}{$prefix}{$type}} > 0) {
22643:                                                 $newvalue = join(', ',@{$defaultshash{'trust'}{$prefix}{$type}});
22644:                                             }
22645:                                         } else {
22646:                                             $notinuse = 1;
22647:                                         }
22648:                                     }
22649:                                 }
22650:                                 if ($notinuse) {
22651:                                     $resulttext .= '<li>'.&mt('[_1] set to: not in use',$lt{$type}).'</li>';
22652:                                 } elsif ($newvalue eq '') {
22653:                                     $resulttext .= '<li>'.&mt('[_1] set to: none',$lt{$type}).'</li>';
22654:                                 } else {
22655:                                     $resulttext .= '<li>'.&mt('[_1] set to: [_2].',$lt{$type},$newvalue).'</li>';
22656:                                 }
22657:                             }
22658:                         }
22659:                         $resulttext .= '</ul>';
22660:                     }
22661:                 }
22662:                 $resulttext .= '</ul>';
22663:             } else {
22664:                 $resulttext = $nochgmsg;
22665:             }
22666:         } else {
22667:             $resulttext = '<span class="LC_error">'.
22668:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22669:         }
22670:     } else {
22671:         $resulttext = $nochgmsg;
22672:     }
22673:     return $resulttext;
22674: }
22675: 
22676: sub modify_loadbalancing {
22677:     my ($dom,%domconfig) = @_;
22678:     my $primary_id = &Apache::lonnet::domain($dom,'primary');
22679:     my $intdom = &Apache::lonnet::internet_dom($primary_id);
22680:     my ($othertitle,$usertypes,$types) =
22681:         &Apache::loncommon::sorted_inst_types($dom);
22682:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
22683:     my %libraryservers = &Apache::lonnet::get_servers($dom,'library');
22684:     my @sparestypes = ('primary','default');
22685:     my %typetitles = &sparestype_titles();
22686:     my $resulttext;
22687:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
22688:     if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22689:         %existing = %{$domconfig{'loadbalancing'}};
22690:     }
22691:     &get_loadbalancers_config(\%servers,\%existing,\%currbalancer,
22692:                               \%currtargets,\%currrules,\%currcookies);
22693:     my ($saveloadbalancing,%defaultshash,%changes);
22694:     my ($alltypes,$othertypes,$titles) =
22695:         &loadbalancing_titles($dom,$intdom,$usertypes,$types);
22696:     my %ruletitles = &offloadtype_text();
22697:     my @deletions = &Apache::loncommon::get_env_multiple('form.loadbalancing_delete');
22698:     for (my $i=0; $i<$env{'form.loadbalancing_total'}; $i++) {
22699:         my $balancer = $env{'form.loadbalancing_lonhost_'.$i};
22700:         if ($balancer eq '') {
22701:             next;
22702:         }
22703:         if (!exists($servers{$balancer})) {
22704:             if (exists($currbalancer{$balancer})) {
22705:                 push(@{$changes{'delete'}},$balancer);
22706:             }
22707:             next;
22708:         }
22709:         if ((@deletions > 0) && (grep(/^\Q$i\E$/,@deletions))) {
22710:             push(@{$changes{'delete'}},$balancer);
22711:             next;
22712:         }
22713:         if (!exists($currbalancer{$balancer})) {
22714:             push(@{$changes{'add'}},$balancer);
22715:         }
22716:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'} = [];
22717:         $defaultshash{'loadbalancing'}{$balancer}{'targets'}{'default'} = [];
22718:         $defaultshash{'loadbalancing'}{$balancer}{'rules'} = {};
22719:         unless (ref($domconfig{'loadbalancing'}) eq 'HASH') {
22720:             $saveloadbalancing = 1;
22721:         }
22722:         foreach my $sparetype (@sparestypes) {
22723:             my @targets = &Apache::loncommon::get_env_multiple('form.loadbalancing_target_'.$i.'_'.$sparetype);
22724:             my @offloadto;
22725:             foreach my $target (@targets) {
22726:                 if (($servers{$target}) && ($target ne $balancer)) {
22727:                     if ($sparetype eq 'default') {
22728:                         if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}) eq 'ARRAY') {
22729:                             next if (grep(/^\Q$target\E$/,@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{'primary'}}));
22730:                         }
22731:                     }
22732:                     unless(grep(/^\Q$target\E$/,@offloadto)) {
22733:                         push(@offloadto,$target);
22734:                     }
22735:                 }
22736:             }
22737:             if ($env{'form.loadbalancing_target_'.$i.'_hosthere'} eq $sparetype) {
22738:                 unless(grep(/^\Q$balancer\E$/,@offloadto)) {
22739:                     push(@offloadto,$balancer);
22740:                 }
22741:             }
22742:             $defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype} = \@offloadto;
22743:         }
22744:         if ($env{'form.loadbalancing_cookie_'.$i}) {
22745:             $defaultshash{'loadbalancing'}{$balancer}{'cookie'} = 1;
22746:             if (exists($currbalancer{$balancer})) { 
22747:                 unless ($currcookies{$balancer}) {
22748:                     $changes{'curr'}{$balancer}{'cookie'} = 1;
22749:                 }
22750:             }
22751:         } elsif (exists($currbalancer{$balancer})) {
22752:             if ($currcookies{$balancer}) {
22753:                 $changes{'curr'}{$balancer}{'cookie'} = 1;
22754:             }
22755:         }
22756:         if (ref($currtargets{$balancer}) eq 'HASH') {
22757:             foreach my $sparetype (@sparestypes) {
22758:                 if (ref($currtargets{$balancer}{$sparetype}) eq 'ARRAY') {
22759:                     my @targetdiffs = &Apache::loncommon::compare_arrays($currtargets{$balancer}{$sparetype},$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype});
22760:                     if (@targetdiffs > 0) {
22761:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22762:                     }
22763:                 } elsif (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22764:                     if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22765:                         $changes{'curr'}{$balancer}{'targets'} = 1;
22766:                     }
22767:                 }
22768:             }
22769:         } else {
22770:             if (ref($defaultshash{'loadbalancing'}{$balancer}) eq 'HASH') {
22771:                 foreach my $sparetype (@sparestypes) {
22772:                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22773:                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22774:                             $changes{'curr'}{$balancer}{'targets'} = 1;
22775:                         }
22776:                     }
22777:                 }
22778:             }
22779:         }
22780:         my $ishomedom;
22781:         if (&Apache::lonnet::host_domain($balancer) eq $dom) {
22782:             $ishomedom = 1;
22783:         }
22784:         if (ref($alltypes) eq 'ARRAY') {
22785:             foreach my $type (@{$alltypes}) {
22786:                 my $rule;
22787:                 unless ((($type eq '_LC_external') || ($type eq '_LC_internetdom')) &&
22788:                          (!$ishomedom)) {
22789:                     $rule = $env{'form.loadbalancing_rules_'.$i.'_'.$type};
22790:                 }
22791:                 if ($rule eq 'specific') {
22792:                     my $specifiedhost = $env{'form.loadbalancing_singleserver_'.$i.'_'.$type};
22793:                     if (exists($servers{$specifiedhost})) {
22794:                         $rule = $specifiedhost;
22795:                     }
22796:                 }
22797:                 $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type} = $rule;
22798:                 if (ref($currrules{$balancer}) eq 'HASH') {
22799:                     if ($rule ne $currrules{$balancer}{$type}) {
22800:                         $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22801:                     }
22802:                 } elsif ($rule ne '') {
22803:                     $changes{'curr'}{$balancer}{'rules'}{$type} = 1;
22804:                 }
22805:             }
22806:         }
22807:     }
22808:     my $nochgmsg = &mt('No changes made to Load Balancer settings.');
22809:     if ((keys(%changes) > 0) || ($saveloadbalancing)) {
22810:         unless (ref($defaultshash{'loadbalancing'}) eq 'HASH') {
22811:             $defaultshash{'loadbalancing'} = {};
22812:         }
22813:         my $putresult = &Apache::lonnet::put_dom('configuration',
22814:                                                  \%defaultshash,$dom);
22815:         if ($putresult eq 'ok') {
22816:             if (keys(%changes) > 0) {
22817:                 my %toupdate;
22818:                 if (ref($changes{'delete'}) eq 'ARRAY') {
22819:                     foreach my $balancer (sort(@{$changes{'delete'}})) {
22820:                         $resulttext .= '<li>'.&mt('Load Balancing discontinued for: [_1]',$balancer).'</li>';
22821:                         $toupdate{$balancer} = 1;
22822:                     }
22823:                 }
22824:                 if (ref($changes{'add'}) eq 'ARRAY') {
22825:                     foreach my $balancer (sort(@{$changes{'add'}})) {
22826:                         $resulttext .= '<li>'.&mt('Load Balancing enabled for: [_1]',$balancer);
22827:                         $toupdate{$balancer} = 1;
22828:                     }
22829:                 }
22830:                 if (ref($changes{'curr'}) eq 'HASH') {
22831:                     foreach my $balancer (sort(keys(%{$changes{'curr'}}))) {
22832:                         $toupdate{$balancer} = 1;
22833:                         if (ref($changes{'curr'}{$balancer}) eq 'HASH') {
22834:                             if ($changes{'curr'}{$balancer}{'targets'}) {
22835:                                 my %offloadstr;
22836:                                 foreach my $sparetype (@sparestypes) {
22837:                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22838:                                         if (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}} > 0) {
22839:                                             $offloadstr{$sparetype} = join(', ',@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
22840:                                         }
22841:                                     }
22842:                                 }
22843:                                 if (keys(%offloadstr) == 0) {
22844:                                     $resulttext .= '<li>'.&mt("Servers to which Load Balance server offloads set to 'None', by default").'</li>';
22845:                                 } else {
22846:                                     my $showoffload;
22847:                                     foreach my $sparetype (@sparestypes) {
22848:                                         $showoffload .= '<i>'.$typetitles{$sparetype}.'</i>:&nbsp;';
22849:                                         if (defined($offloadstr{$sparetype})) {
22850:                                             $showoffload .= $offloadstr{$sparetype};
22851:                                         } else {
22852:                                             $showoffload .= &mt('None');
22853:                                         }
22854:                                         $showoffload .= ('&nbsp;'x3);
22855:                                     }
22856:                                     $resulttext .= '<li>'.&mt('By default, Load Balancer: [_1] set to offload to - [_2]',$balancer,$showoffload).'</li>';
22857:                                 }
22858:                             }
22859:                         }
22860:                         if (ref($changes{'curr'}{$balancer}{'rules'}) eq 'HASH') {
22861:                             if ((ref($alltypes) eq 'ARRAY') && (ref($titles) eq 'HASH')) {
22862:                                 foreach my $type (@{$alltypes}) {
22863:                                     if ($changes{'curr'}{$balancer}{'rules'}{$type}) {
22864:                                         my $rule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
22865:                                         my $balancetext;
22866:                                         if ($rule eq '') {
22867:                                             $balancetext =  $ruletitles{'default'};
22868:                                         } elsif (($rule eq 'homeserver') || ($rule eq 'externalbalancer') ||
22869:                                                  ($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
22870:                                             if (($type eq '_LC_ipchange') || ($type eq '_LC_ipchangesso')) {
22871:                                                 foreach my $sparetype (@sparestypes) {
22872:                                                     if (ref($defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}) eq 'ARRAY') {
22873:                                                         map { $toupdate{$_} = 1; } (@{$defaultshash{'loadbalancing'}{$balancer}{'targets'}{$sparetype}});
22874:                                                     }
22875:                                                 }
22876:                                                 foreach my $item (@{$alltypes}) {
22877:                                                     next if ($item =~  /^_LC_ipchange/);
22878:                                                     my $hasrule = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$item};
22879:                                                     if ($hasrule eq 'homeserver') {
22880:                                                         map { $toupdate{$_} = 1; } (keys(%libraryservers));
22881:                                                     } else {
22882:                                                         unless (($hasrule eq 'default') || ($hasrule eq 'none') || ($hasrule eq 'externalbalancer')) {
22883:                                                             if ($servers{$hasrule}) {
22884:                                                                 $toupdate{$hasrule} = 1;
22885:                                                             }
22886:                                                         }
22887:                                                     }
22888:                                                 }
22889:                                                 if (($rule eq 'balancer') || ($rule eq 'offloadedto')) {
22890:                                                     $balancetext =  $ruletitles{$rule};
22891:                                                 } else {
22892:                                                     my $receiver = $defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type};
22893:                                                     $balancetext = $ruletitles{'particular'}.' '.$receiver;
22894:                                                     if ($receiver) {
22895:                                                         $toupdate{$receiver};
22896:                                                     }
22897:                                                 }
22898:                                             } else {
22899:                                                 $balancetext =  $ruletitles{$rule};
22900:                                             }
22901:                                         } else {
22902:                                             $balancetext = &mt('offload to [_1]',$defaultshash{'loadbalancing'}{$balancer}{'rules'}{$type});
22903:                                         }
22904:                                         $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- balancing for [_2] set to - "[_3]"',$balancer,$titles->{$type},$balancetext).'</li>';
22905:                                     }
22906:                                 }
22907:                             }
22908:                         }
22909:                         if ($changes{'curr'}{$balancer}{'cookie'}) {
22910:                             if ($currcookies{$balancer}) {
22911:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use disabled',
22912:                                                           $balancer).'</li>';
22913:                             } else {
22914:                                 $resulttext .= '<li>'.&mt('Load Balancer: [_1] -- cookie use enabled',
22915:                                                           $balancer).'</li>';
22916:                             }
22917:                         }
22918:                     }
22919:                 }
22920:                 if (keys(%toupdate)) {
22921:                     my %thismachine;
22922:                     my $updatedhere;
22923:                     my $cachetime = 60*60*24;
22924:                     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
22925:                     foreach my $lonhost (keys(%toupdate)) {
22926:                         if ($thismachine{$lonhost}) {
22927:                             unless ($updatedhere) {
22928:                                 &Apache::lonnet::do_cache_new('loadbalancing',$dom,
22929:                                                               $defaultshash{'loadbalancing'},
22930:                                                               $cachetime);
22931:                                 $updatedhere = 1;
22932:                             }
22933:                         } else {
22934:                             my $cachekey = &escape('loadbalancing').':'.&escape($dom);
22935:                             &Apache::lonnet::remote_devalidate_cache($lonhost,[$cachekey]);
22936:                         }
22937:                     }
22938:                 }
22939:                 if ($resulttext ne '') {
22940:                     $resulttext = &mt('Changes made:').'<ul>'.$resulttext.'</ul>';
22941:                 } else {
22942:                     $resulttext = $nochgmsg;
22943:                 }
22944:             } else {
22945:                 $resulttext = $nochgmsg;
22946:             }
22947:         } else {
22948:             $resulttext = '<span class="LC_error">'.
22949:                           &mt('An error occurred: [_1]',$putresult).'</span>';
22950:         }
22951:     } else {
22952:         $resulttext = $nochgmsg;
22953:     }
22954:     return $resulttext;
22955: }
22956: 
22957: sub recurse_check {
22958:     my ($chkcats,$categories,$depth,$name) = @_;
22959:     if (ref($chkcats->[$depth]{$name}) eq 'ARRAY') {
22960:         my $chg = 0;
22961:         for (my $j=0; $j<@{$chkcats->[$depth]{$name}}; $j++) {
22962:             my $category = $chkcats->[$depth]{$name}[$j];
22963:             my $item;
22964:             if ($category eq '') {
22965:                 $chg ++;
22966:             } else {
22967:                 my $deeper = $depth + 1;
22968:                 $item = &escape($category).':'.&escape($name).':'.$depth;
22969:                 if ($chg) {
22970:                     $categories->{$item} -= $chg;
22971:                 }
22972:                 &recurse_check($chkcats,$categories,$deeper,$category);
22973:                 $deeper --;
22974:             }
22975:         }
22976:     }
22977:     return;
22978: }
22979: 
22980: sub recurse_cat_deletes {
22981:     my ($item,$coursecategories,$deletions) = @_;
22982:     my ($deleted,$container,$depth) = map { &unescape($_); } split(/:/,$item);
22983:     my $subdepth = $depth + 1;
22984:     if (ref($coursecategories) eq 'HASH') {
22985:         foreach my $subitem (keys(%{$coursecategories})) {
22986:             my ($child,$parent,$itemdepth) = map { &unescape($_); } split(/:/,$subitem);
22987:             if (($parent eq $deleted) && ($itemdepth == $subdepth)) {
22988:                 delete($coursecategories->{$subitem});
22989:                 $deletions->{$subitem} = 1;
22990:                 &recurse_cat_deletes($subitem,$coursecategories,$deletions);
22991:             }
22992:         }
22993:     }
22994:     return;
22995: }
22996: 
22997: sub active_dc_picker {
22998:     my ($dom,$numinrow,$inputtype,$name,%currhash) = @_;
22999:     my %domcoords = &Apache::lonnet::get_active_domroles($dom,['dc']);
23000:     my @domcoord = keys(%domcoords);
23001:     if (keys(%currhash)) {
23002:         foreach my $dc (keys(%currhash)) {
23003:             unless (exists($domcoords{$dc})) {
23004:                 push(@domcoord,$dc);
23005:             }
23006:         }
23007:     }
23008:     @domcoord = sort(@domcoord);
23009:     my $numdcs = scalar(@domcoord);
23010:     my $rows = 0;
23011:     my $table;
23012:     if ($numdcs > 1) {
23013:         $table = '<table>';
23014:         for (my $i=0; $i<@domcoord; $i++) {
23015:             my $rem = $i%($numinrow);
23016:             if ($rem == 0) {
23017:                 if ($i > 0) {
23018:                     $table .= '</tr>';
23019:                 }
23020:                 $table .= '<tr>';
23021:                 $rows ++;
23022:             }
23023:             my $check = '';
23024:             if ($inputtype eq 'radio') {
23025:                 if (keys(%currhash) == 0) {
23026:                     if (!$i) {
23027:                         $check = ' checked="checked"';
23028:                     }
23029:                 } elsif (exists($currhash{$domcoord[$i]})) {
23030:                     $check = ' checked="checked"';
23031:                 }
23032:             } else {
23033:                 if (exists($currhash{$domcoord[$i]})) {
23034:                     $check = ' checked="checked"';
23035:                 }
23036:             }
23037:             if ($i == @domcoord - 1) {
23038:                 my $colsleft = $numinrow - $rem;
23039:                 if ($colsleft > 1) {
23040:                     $table .= '<td class="LC_left_item" colspan="'.$colsleft.'">';
23041:                 } else {
23042:                     $table .= '<td class="LC_left_item">';
23043:                 }
23044:             } else {
23045:                 $table .= '<td class="LC_left_item">';
23046:             }
23047:             my ($dcname,$dcdom) = split(':',$domcoord[$i]);
23048:             my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23049:             $table .= '<span class="LC_nobreak"><label>'.
23050:                       '<input type="'.$inputtype.'" name="'.$name.'"'.
23051:                       ' value="'.$domcoord[$i].'"'.$check.' />'.$user;
23052:             if ($user ne $dcname.':'.$dcdom) {
23053:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23054:             }
23055:             $table .= '</label></span></td>';
23056:         }
23057:         $table .= '</tr></table>';
23058:     } elsif ($numdcs == 1) {
23059:         my ($dcname,$dcdom) = split(':',$domcoord[0]);
23060:         my $user = &Apache::loncommon::plainname($dcname,$dcdom);
23061:         if ($inputtype eq 'radio') {
23062:             $table = '<input type="hidden" name="'.$name.'" value="'.$domcoord[0].'" />'.$user;
23063:             if ($user ne $dcname.':'.$dcdom) {
23064:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23065:             }
23066:         } else {
23067:             my $check;
23068:             if (exists($currhash{$domcoord[0]})) {
23069:                 $check = ' checked="checked"';
23070:             }
23071:             $table = '<span class="LC_nobreak"><label>'.
23072:                      '<input type="checkbox" name="'.$name.'" '.
23073:                      'value="'.$domcoord[0].'"'.$check.' />'.$user;
23074:             if ($user ne $dcname.':'.$dcdom) {
23075:                 $table .=  ' ('.$dcname.':'.$dcdom.')';
23076:             }
23077:             $table .= '</label></span>';
23078:             $rows ++;
23079:         }
23080:     }
23081:     return ($numdcs,$table,$rows);
23082: }
23083: 
23084: sub usersession_titles {
23085:     return &Apache::lonlocal::texthash(
23086:                hosted => 'Hosting of sessions for users from other domains on servers in this domain',
23087:                remote => 'Hosting of sessions for users in this domain on servers in other domains',
23088:                spares => 'Servers offloaded to, when busy',
23089:                version => 'LON-CAPA version requirement',
23090:                excludedomain => 'Allow all, but exclude specific domains',
23091:                includedomain => 'Deny all, but include specific domains',
23092:                primary => 'Primary (checked first)',
23093:                default => 'Default',
23094:            );
23095: }
23096: 
23097: sub id_for_thisdom {
23098:     my (%servers) = @_;
23099:     my %altids;
23100:     foreach my $server (keys(%servers)) {
23101:         my $serverhome = &Apache::lonnet::get_server_homeID($servers{$server});
23102:         if ($serverhome ne $server) {
23103:             $altids{$serverhome} = $server;
23104:         }
23105:     }
23106:     return %altids;
23107: }
23108: 
23109: sub count_servers {
23110:     my ($currbalancer,%servers) = @_;
23111:     my (@spares,$numspares);
23112:     foreach my $lonhost (sort(keys(%servers))) {
23113:         next if ($currbalancer eq $lonhost);
23114:         push(@spares,$lonhost);
23115:     }
23116:     if ($currbalancer) {
23117:         $numspares = scalar(@spares);
23118:     } else {
23119:         $numspares = scalar(@spares) - 1;
23120:     }
23121:     return ($numspares,@spares);
23122: }
23123: 
23124: sub lonbalance_targets_js {
23125:     my ($dom,$types,$servers,$settings) = @_;
23126:     my $select = &mt('Select');
23127:     my ($alltargets,$allishome,$allinsttypes,@alltypes);
23128:     if (ref($servers) eq 'HASH') {
23129:         $alltargets = join("','",sort(keys(%{$servers})));
23130:         my @homedoms;
23131:         foreach my $server (sort(keys(%{$servers}))) {
23132:             if (&Apache::lonnet::host_domain($server) eq $dom) {
23133:                 push(@homedoms,'1');
23134:             } else {
23135:                 push(@homedoms,'0');
23136:             }
23137:         }
23138:         $allishome = join("','",@homedoms);
23139:     }
23140:     if (ref($types) eq 'ARRAY') {
23141:         if (@{$types} > 0) {
23142:             @alltypes = @{$types};
23143:         }
23144:     }
23145:     push(@alltypes,'default','_LC_adv','_LC_author','_LC_internetdom','_LC_external');
23146:     $allinsttypes = join("','",@alltypes);
23147:     my (%currbalancer,%currtargets,%currrules,%existing,%currcookies);
23148:     if (ref($settings) eq 'HASH') {
23149:         %existing = %{$settings};
23150:     }
23151:     &get_loadbalancers_config($servers,\%existing,\%currbalancer,
23152:                               \%currtargets,\%currrules,\%currcookies);
23153:     my $balancers = join("','",sort(keys(%currbalancer)));
23154:     return <<"END";
23155: 
23156: <script type="text/javascript">
23157: // <![CDATA[
23158: 
23159: currBalancers = new Array('$balancers');
23160: 
23161: function toggleTargets(balnum) {
23162:     var lonhostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23163:     var prevhostitem = document.getElementById('loadbalancing_prevlonhost_'+balnum);
23164:     var balancer = lonhostitem.options[lonhostitem.selectedIndex].value;
23165:     var prevbalancer = prevhostitem.value;
23166:     var baltotal = document.getElementById('loadbalancing_total').value;
23167:     prevhostitem.value = balancer;
23168:     if (prevbalancer != '') {
23169:         var prevIdx = currBalancers.indexOf(prevbalancer);
23170:         if (prevIdx != -1) {
23171:             currBalancers.splice(prevIdx,1);
23172:         }
23173:     }
23174:     if (balancer == '') {
23175:         hideSpares(balnum);
23176:     } else {
23177:         var currIdx = currBalancers.indexOf(balancer);
23178:         if (currIdx == -1) {
23179:             currBalancers.push(balancer);
23180:         }
23181:         var homedoms = new Array('$allishome');
23182:         var ishomedom = homedoms[lonhostitem.selectedIndex];
23183:         showSpares(balancer,ishomedom,balnum);
23184:     }
23185:     balancerChange(balnum,baltotal,'change',prevbalancer,balancer);
23186:     return;
23187: }
23188: 
23189: function showSpares(balancer,ishomedom,balnum) {
23190:     var alltargets = new Array('$alltargets');
23191:     var insttypes = new Array('$allinsttypes');
23192:     var offloadtypes = new Array('primary','default');
23193: 
23194:     document.getElementById('loadbalancing_targets_'+balnum).style.display='block';
23195:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='none';
23196:  
23197:     for (var i=0; i<offloadtypes.length; i++) {
23198:         var count = 0;
23199:         for (var j=0; j<alltargets.length; j++) {
23200:             if (alltargets[j] != balancer) {
23201:                 var item = document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+count);
23202:                 item.value = alltargets[j];
23203:                 item.style.textAlign='left';
23204:                 item.style.textFace='normal';
23205:                 document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+count).innerHTML = alltargets[j];
23206:                 if (currBalancers.indexOf(alltargets[j]) == -1) {
23207:                     item.disabled = '';
23208:                 } else {
23209:                     item.disabled = 'disabled';
23210:                     item.checked = false;
23211:                 }
23212:                 count ++;
23213:             }
23214:         }
23215:     }
23216:     for (var k=0; k<insttypes.length; k++) {
23217:         if ((insttypes[k] == '_LC_external') || (insttypes[k] == '_LC_internetdom')) {
23218:             if (ishomedom == 1) {
23219:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23220:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23221:             } else {
23222:                 document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23223:                 document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23224:             }
23225:         } else {
23226:             document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='block';
23227:             document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='block';
23228:         }
23229:         if ((insttypes[k] != '_LC_external') && 
23230:             ((insttypes[k] != '_LC_internetdom') ||
23231:              ((insttypes[k] == '_LC_internetdom') && (ishomedom == 1)))) {
23232:             var item = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]);
23233:             item.options.length = 0;
23234:             item.options[0] = new Option("","",true,true);
23235:             var idx = 0;
23236:             for (var m=0; m<alltargets.length; m++) {
23237:                 if ((currBalancers.indexOf(alltargets[m]) == -1) && (alltargets[m] != balancer)) {
23238:                     idx ++;
23239:                     item.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23240:                 }
23241:             }
23242:         }
23243:     }
23244:     return;
23245: }
23246: 
23247: function hideSpares(balnum) {
23248:     var alltargets = new Array('$alltargets');
23249:     var insttypes = new Array('$allinsttypes');
23250:     var offloadtypes = new Array('primary','default');
23251: 
23252:     document.getElementById('loadbalancing_targets_'+balnum).style.display='none';
23253:     document.getElementById('loadbalancing_disabled_'+balnum).style.display='block';
23254: 
23255:     var total = alltargets.length - 1;
23256:     for (var i=0; i<offloadtypes; i++) {
23257:         for (var j=0; j<total; j++) {
23258:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).checked = false;
23259:            document.getElementById('loadbalancing_target_'+balnum+'_'+offloadtypes[i]+'_'+j).value = '';
23260:            document.getElementById('loadbalancing_targettxt_'+balnum+'_'+offloadtypes[i]+'_'+j).innerHTML = '';
23261:         }
23262:     }
23263:     for (var k=0; k<insttypes.length; k++) {
23264:         document.getElementById('balanceruletitle_'+balnum+'_'+insttypes[k]).style.display='none';
23265:         document.getElementById('balancerule_'+balnum+'_'+insttypes[k]).style.display='none';
23266:         if (insttypes[k] != '_LC_external') {
23267:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).length = 0;
23268:             document.getElementById('loadbalancing_singleserver_'+balnum+'_'+insttypes[k]).options[0] = new Option("","",true,true);
23269:         }
23270:     }
23271:     return;
23272: }
23273: 
23274: function checkOffloads(item,balnum,type) {
23275:     var alltargets = new Array('$alltargets');
23276:     var offloadtypes = new Array('primary','default');
23277:     if (item.checked) {
23278:         var total = alltargets.length - 1;
23279:         var other;
23280:         if (type == offloadtypes[0]) {
23281:             other = offloadtypes[1];
23282:         } else {
23283:             other = offloadtypes[0];
23284:         }
23285:         for (var i=0; i<total; i++) {
23286:             var server = document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).value;
23287:             if (server == item.value) {
23288:                 if (document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked) {
23289:                     document.getElementById('loadbalancing_target_'+balnum+'_'+other+'_'+i).checked = false;
23290:                 }
23291:             }
23292:         }
23293:     }
23294:     return;
23295: }
23296: 
23297: function singleServerToggle(balnum,type) {
23298:     var offloadtoSelIdx = document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex;
23299:     if (offloadtoSelIdx == 0) {
23300:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_0').checked = true;
23301:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23302: 
23303:     } else {
23304:         document.getElementById('loadbalancing_rules_'+balnum+'_'+type+'_2').checked = true;
23305:         document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23306:     }
23307:     return;
23308: }
23309: 
23310: function balanceruleChange(formname,balnum,type) {
23311:     if (type == '_LC_external') {
23312:         return;
23313:     }
23314:     var typesRules = getIndicesByName(formname,'loadbalancing_rules_'+balnum+'_'+type);
23315:     for (var i=0; i<typesRules.length; i++) {
23316:         if (formname.elements[typesRules[i]].checked) {
23317:             if (formname.elements[typesRules[i]].value != 'specific') {
23318:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).selectedIndex = 0;
23319:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '';
23320:             } else {
23321:                 document.getElementById('loadbalancing_singleserver_'+balnum+'_'+type).options[0].text = '$select';
23322:             }
23323:         }
23324:     }
23325:     return;
23326: }
23327: 
23328: function balancerDeleteChange(balnum) {
23329:     var hostitem = document.getElementById('loadbalancing_lonhost_'+balnum);
23330:     var baltotal = document.getElementById('loadbalancing_total').value;
23331:     var addtarget;
23332:     var removetarget;
23333:     var action = 'delete';
23334:     if (document.getElementById('loadbalancing_delete_'+balnum)) {
23335:         var lonhost = hostitem.value;
23336:         var currIdx = currBalancers.indexOf(lonhost);
23337:         if (document.getElementById('loadbalancing_delete_'+balnum).checked) {
23338:             if (currIdx != -1) {
23339:                 currBalancers.splice(currIdx,1);
23340:             }
23341:             addtarget = lonhost;
23342:         } else {
23343:             if (currIdx == -1) {
23344:                 currBalancers.push(lonhost);
23345:             }
23346:             removetarget = lonhost;
23347:             action = 'undelete';
23348:         }
23349:         balancerChange(balnum,baltotal,action,addtarget,removetarget);
23350:     }
23351:     return;
23352: }
23353: 
23354: function balancerChange(balnum,baltotal,action,addtarget,removetarget) {
23355:     if (baltotal > 1) {
23356:         var offloadtypes = new Array('primary','default');
23357:         var alltargets = new Array('$alltargets');
23358:         var insttypes = new Array('$allinsttypes');
23359:         for (var i=0; i<baltotal; i++) {
23360:             if (i != balnum) {
23361:                 for (var j=0; j<offloadtypes.length; j++) {
23362:                     var total = alltargets.length - 1;
23363:                     for (var k=0; k<total; k++) {
23364:                         var serveritem = document.getElementById('loadbalancing_target_'+i+'_'+offloadtypes[j]+'_'+k);
23365:                         var server = serveritem.value;
23366:                         if ((action == 'delete') || (action == 'change' && addtarget != ''))  {
23367:                             if (server == addtarget) {
23368:                                 serveritem.disabled = '';
23369:                             }
23370:                         }
23371:                         if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23372:                             if (server == removetarget) {
23373:                                 serveritem.disabled = 'disabled';
23374:                                 serveritem.checked = false;
23375:                             }
23376:                         }
23377:                     }
23378:                 }
23379:                 for (var j=0; j<insttypes.length; j++) {
23380:                     if (insttypes[j] != '_LC_external') {
23381:                         if (document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j])) {
23382:                             var singleserver = document.getElementById('loadbalancing_singleserver_'+i+'_'+insttypes[j]);
23383:                             var currSel = singleserver.selectedIndex;
23384:                             var currVal = singleserver.options[currSel].value;
23385:                             if ((action == 'delete') || (action == 'change' && addtarget != '')) {
23386:                                 var numoptions = singleserver.options.length;
23387:                                 var needsnew = 1;
23388:                                 for (var k=0; k<numoptions; k++) {
23389:                                     if (singleserver.options[k] == addtarget) {
23390:                                         needsnew = 0;
23391:                                         break;
23392:                                     }
23393:                                 }
23394:                                 if (needsnew == 1) {
23395:                                     singleserver.options[numoptions] = new Option(addtarget,addtarget,false,false);
23396:                                 }
23397:                             }
23398:                             if ((action == 'undelete') || (action == 'change' && removetarget != '')) {
23399:                                 singleserver.options.length = 0;
23400:                                 if ((currVal) && (currVal != removetarget)) {
23401:                                     singleserver.options[0] = new Option("","",false,false);
23402:                                 } else {
23403:                                     singleserver.options[0] = new Option("","",true,true);
23404:                                 }
23405:                                 var idx = 0;
23406:                                 for (var m=0; m<alltargets.length; m++) {
23407:                                     if (currBalancers.indexOf(alltargets[m]) == -1) {
23408:                                         idx ++;
23409:                                         if (currVal == alltargets[m]) {
23410:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],true,true);
23411:                                         } else {
23412:                                             singleserver.options[idx] = new Option(alltargets[m],alltargets[m],false,false);
23413:                                         }
23414:                                     }
23415:                                 }
23416:                             }
23417:                         }
23418:                     }
23419:                 }
23420:             }
23421:         }
23422:     }
23423:     return;
23424: }
23425: 
23426: // ]]>
23427: </script>
23428: 
23429: END
23430: }
23431: 
23432: 
23433: sub new_spares_js {
23434:     my @sparestypes = ('primary','default');
23435:     my $types = join("','",@sparestypes);
23436:     my $select = &mt('Select');
23437:     return <<"END";
23438: 
23439: <script type="text/javascript">
23440: // <![CDATA[
23441: 
23442: function updateNewSpares(formname,lonhost) {
23443:     var types = new Array('$types');
23444:     var include = new Array();
23445:     var exclude = new Array();
23446:     for (var i=0; i<types.length; i++) {
23447:         var spareboxes = getIndicesByName(formname,'spare_'+types[i]+'_'+lonhost);
23448:         for (var j=0; j<spareboxes.length; j++) {
23449:             if (formname.elements[spareboxes[j]].checked) {
23450:                 exclude.push(formname.elements[spareboxes[j]].value);
23451:             } else {
23452:                 include.push(formname.elements[spareboxes[j]].value);
23453:             }
23454:         }
23455:     }
23456:     for (var i=0; i<types.length; i++) {
23457:         var newSpare = document.getElementById('newspare_'+types[i]+'_'+lonhost);
23458:         var selIdx = newSpare.selectedIndex;
23459:         var currnew = newSpare.options[selIdx].value;
23460:         var okSpares = new Array();
23461:         for (var j=0; j<newSpare.options.length; j++) {
23462:             var possible = newSpare.options[j].value;
23463:             if (possible != '') {
23464:                 if (exclude.indexOf(possible) == -1) {
23465:                     okSpares.push(possible);
23466:                 } else {
23467:                     if (currnew == possible) {
23468:                         selIdx = 0;
23469:                     }
23470:                 }
23471:             }
23472:         }
23473:         for (var k=0; k<include.length; k++) {
23474:             if (okSpares.indexOf(include[k]) == -1) {
23475:                 okSpares.push(include[k]);
23476:             }
23477:         }
23478:         okSpares.sort();
23479:         newSpare.options.length = 0;
23480:         if (selIdx == 0) {
23481:             newSpare.options[0] = new Option("$select","",true,true);
23482:         } else {
23483:             newSpare.options[0] = new Option("$select","",false,false);
23484:         }
23485:         for (var m=0; m<okSpares.length; m++) {
23486:             var idx = m+1;
23487:             var selThis = 0;
23488:             if (selIdx != 0) {
23489:                 if (okSpares[m] == currnew) {
23490:                     selThis = 1;
23491:                 }
23492:             }
23493:             if (selThis == 1) {
23494:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],true,true);
23495:             } else {
23496:                 newSpare.options[idx] = new Option(okSpares[m],okSpares[m],false,false);
23497:             }
23498:         }
23499:     }
23500:     return;
23501: }
23502: 
23503: function checkNewSpares(lonhost,type) {
23504:     var newSpare = document.getElementById('newspare_'+type+'_'+lonhost);
23505:     var chosen =  newSpare.options[newSpare.selectedIndex].value;
23506:     if (chosen != '') {
23507:         var othertype;
23508:         var othernewSpare;
23509:         if (type == 'primary') {
23510:             othernewSpare = document.getElementById('newspare_default_'+lonhost);
23511:         }
23512:         if (type == 'default') {
23513:             othernewSpare = document.getElementById('newspare_primary_'+lonhost);
23514:         }
23515:         if (othernewSpare.options[othernewSpare.selectedIndex].value == chosen) {
23516:             othernewSpare.selectedIndex = 0;
23517:         }
23518:     }
23519:     return;
23520: }
23521: 
23522: // ]]>
23523: </script>
23524: 
23525: END
23526: 
23527: }
23528: 
23529: sub common_domprefs_js {
23530:     return <<"END";
23531: 
23532: <script type="text/javascript">
23533: // <![CDATA[
23534: 
23535: function getIndicesByName(formname,item) {
23536:     var group = new Array();
23537:     for (var i=0;i<formname.elements.length;i++) {
23538:         if (formname.elements[i].name == item) {
23539:             group.push(formname.elements[i].id);
23540:         }
23541:     }
23542:     return group;
23543: }
23544: 
23545: // ]]>
23546: </script>
23547: 
23548: END
23549: 
23550: }
23551: 
23552: sub recaptcha_js {
23553:     my %lt = &captcha_phrases();
23554:     return <<"END";
23555: 
23556: <script type="text/javascript">
23557: // <![CDATA[
23558: 
23559: function updateCaptcha(caller,context) {
23560:     var privitem;
23561:     var pubitem;
23562:     var privtext;
23563:     var pubtext;
23564:     var versionitem;
23565:     var versiontext;
23566:     if (document.getElementById(context+'_recaptchapub')) {
23567:         pubitem = document.getElementById(context+'_recaptchapub');
23568:     } else {
23569:         return;
23570:     }
23571:     if (document.getElementById(context+'_recaptchapriv')) {
23572:         privitem = document.getElementById(context+'_recaptchapriv');
23573:     } else {
23574:         return;
23575:     }
23576:     if (document.getElementById(context+'_recaptchapubtxt')) {
23577:         pubtext = document.getElementById(context+'_recaptchapubtxt');
23578:     } else {
23579:         return;
23580:     }
23581:     if (document.getElementById(context+'_recaptchaprivtxt')) {
23582:         privtext = document.getElementById(context+'_recaptchaprivtxt');
23583:     } else {
23584:         return;
23585:     }
23586:     if (document.getElementById(context+'_recaptchaversion')) {
23587:         versionitem = document.getElementById(context+'_recaptchaversion');
23588:     } else {
23589:         return;
23590:     }
23591:     if (document.getElementById(context+'_recaptchavertxt')) {
23592:         versiontext = document.getElementById(context+'_recaptchavertxt');
23593:     } else {
23594:         return;
23595:     }
23596:     if (caller.checked) {
23597:         if (caller.value == 'recaptcha') {
23598:             pubitem.type = 'text';
23599:             privitem.type = 'text';
23600:             pubitem.size = '40';
23601:             privitem.size = '40';
23602:             pubtext.innerHTML = "$lt{'pub'}";
23603:             privtext.innerHTML = "$lt{'priv'}";
23604:             versionitem.type = 'text';
23605:             versionitem.size = '3';
23606:             versiontext.innerHTML = "$lt{'ver'}";
23607:         } else {
23608:             pubitem.type = 'hidden';
23609:             privitem.type = 'hidden';
23610:             versionitem.type = 'hidden';
23611:             pubtext.innerHTML = '';
23612:             privtext.innerHTML = '';
23613:             versiontext.innerHTML = '';
23614:         }
23615:     }
23616:     return;
23617: }
23618: 
23619: // ]]>
23620: </script>
23621: 
23622: END
23623: 
23624: }
23625: 
23626: sub toggle_display_js {
23627:     return <<"END";
23628: 
23629: <script type="text/javascript">
23630: // <![CDATA[
23631: 
23632: function toggleDisplay(domForm,caller) {
23633:     if (document.getElementById(caller)) {
23634:         var divitem = document.getElementById(caller);
23635:         var optionsElement = domForm.coursecredits;
23636:         var checkval = 1;
23637:         var dispval = 'block';
23638:         var selfcreateRegExp = /^cancreate_emailverified/;
23639:         if (caller == 'emailoptions') {
23640:             optionsElement = domForm.cancreate_email;
23641:         }
23642:         if (caller == 'studentsubmission') {
23643:             optionsElement = domForm.postsubmit;
23644:         }
23645:         if (caller == 'cloneinstcode') {
23646:             optionsElement = domForm.canclone;
23647:             checkval = 'instcode';
23648:         }
23649:         if (selfcreateRegExp.test(caller)) {
23650:             optionsElement = domForm.elements[caller];
23651:             checkval = 'other';
23652:             dispval = 'inline'
23653:         }
23654:         if (optionsElement.length) {
23655:             var currval;
23656:             for (var i=0; i<optionsElement.length; i++) {
23657:                 if (optionsElement[i].checked) {
23658:                    currval = optionsElement[i].value;
23659:                 }
23660:             }
23661:             if (currval == checkval) {
23662:                 divitem.style.display = dispval;
23663:             } else {
23664:                 divitem.style.display = 'none';
23665:             }
23666:         }
23667:     }
23668:     return;
23669: }
23670: 
23671: // ]]>
23672: </script>
23673: 
23674: END
23675: 
23676: }
23677: 
23678: sub captcha_phrases {
23679:     return &Apache::lonlocal::texthash (
23680:                  priv => 'Private key',
23681:                  pub  => 'Public key',
23682:                  original  => 'original (CAPTCHA)',
23683:                  recaptcha => 'successor (ReCAPTCHA)',
23684:                  notused   => 'unused',
23685:                  ver => 'ReCAPTCHA version (1 or 2)',
23686:     );
23687: }
23688: 
23689: sub devalidate_remote_domconfs {
23690:     my ($dom,$cachekeys) = @_;
23691:     return unless (ref($cachekeys) eq 'HASH');
23692:     my %servers = &Apache::lonnet::internet_dom_servers($dom);
23693:     my %thismachine;
23694:     map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
23695:     my @posscached = ('domainconfig','domdefaults','ltitools','usersessions',
23696:                       'directorysrch','passwdconf','cats','proxyalias','proxysaml',
23697:                       'ipaccess');
23698:     my %cache_by_lonhost;
23699:     if (exists($cachekeys->{'samllanding'})) {
23700:         if (ref($cachekeys->{'samllanding'}) eq 'HASH') {
23701:             my %landing = %{$cachekeys->{'samllanding'}};
23702:             my %domservers = &Apache::lonnet::get_servers($dom);
23703:             if (keys(%domservers)) {
23704:                 foreach my $server (keys(%domservers)) {
23705:                     my @cached;
23706:                     next if ($thismachine{$server});
23707:                     if ($landing{$server}) {
23708:                         push(@cached,&escape('samllanding').':'.&escape($server));
23709:                     }
23710:                     if (@cached) {
23711:                         $cache_by_lonhost{$server} = \@cached;
23712:                     }
23713:                 }
23714:             }
23715:         }
23716:     }
23717:     if (keys(%servers)) {
23718:         foreach my $server (keys(%servers)) {
23719:             next if ($thismachine{$server});
23720:             my @cached;
23721:             foreach my $name (@posscached) {
23722:                 if ($cachekeys->{$name}) {
23723:                     if (($name eq 'proxyalias') || ($name eq 'proxysaml')) {
23724:                         if (ref($cachekeys->{$name}) eq 'HASH') {
23725:                             foreach my $key (keys(%{$cachekeys->{$name}})) {
23726:                                 push(@cached,&escape($name).':'.&escape($key));
23727:                             }
23728:                         }
23729:                     } else {
23730:                         push(@cached,&escape($name).':'.&escape($dom));
23731:                     }
23732:                 }
23733:             }
23734:             if ((exists($cache_by_lonhost{$server})) &&
23735:                 (ref($cache_by_lonhost{$server}) eq 'ARRAY')) {
23736:                 push(@cached,@{$cache_by_lonhost{$server}});
23737:             }
23738:             if (@cached) {
23739:                 &Apache::lonnet::remote_devalidate_cache($server,\@cached);
23740:             }
23741:         }
23742:     }
23743:     return;
23744: }
23745: 
23746: 1;

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